7 Commits

Author SHA1 Message Date
cocool97
e2e1ae1202 Merge pull request #156 from cocool97/mdns-feature
feat(mdns): add feature flag + example
2025-12-26 12:24:00 +01:00
Corentin LIAUD
4f26ebfe29 fix: improve workflow 2025-12-26 12:19:44 +01:00
Corentin LIAUD
2a7c9bdc57 feat(mdns): add feature flag + example 2025-12-26 12:09:02 +01:00
Corentin LIAUD
d06b157255 chore: clippy improvements 2025-12-26 11:19:46 +01:00
Corentin LIAUD
947964163b fix(adb_client): image crate had no output format by default 2025-12-26 11:12:32 +01:00
Corentin LIAUD
5075e09d0e chore(adb_cli): improve error message in case of error 2025-12-26 11:12:08 +01:00
cocool97
f1d3f8d5f2 Merge pull request #155 from cocool97/sessions
feat: Track individual sessions (local and remote id) for each operation
2025-12-26 10:57:31 +01:00
22 changed files with 209 additions and 63 deletions

View File

@@ -36,10 +36,10 @@ jobs:
CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
- name: Build release
run: cargo build --all-features --release
run: cargo build -p adb_cli --release
- name: Rename binary
run: mv target/release/adb_cli target/release/adb_cli-linux
run: cp target/release/adb_cli target/release/adb_cli-linux
- name: Build DEB package
run: cargo deb -p adb_cli
@@ -69,10 +69,10 @@ jobs:
override: true
- name: Build release
run: cargo build --all-features --release
run: cargo build -p adb_cli --release
- name: Rename binary
run: mv target/release/adb_cli target/release/adb_cli-macos
run: cp target/release/adb_cli target/release/adb_cli-macos
- name: Upload macOS binary
uses: softprops/action-gh-release@v2
@@ -98,7 +98,7 @@ jobs:
python-version: "3.10"
- name: Build release
run: cargo build --all-features --release
run: cargo build -p adb_cli --release
- name: Rename binary
run: Rename-Item -Path target/release/adb_cli.exe -NewName adb_cli-windows.exe

View File

@@ -1,5 +1,5 @@
[workspace]
members = ["adb_cli", "adb_client", "pyadb_client"]
members = ["adb_cli", "adb_client", "pyadb_client", "examples/mdns"]
resolver = "2"
[workspace.package]

View File

@@ -42,6 +42,12 @@ Rust library implementing both ADB protocols (server and end-devices) and provid
Improved documentation available [here](./adb_client/README.md).
## examples
Some examples showing of to use this library are available in the `examples` directory:
- `examples/mdns`: mDNS device discovery
## adb_cli
Rust binary providing an improved version of Google's official `adb` CLI, by using `adb_client` library.

View File

@@ -11,7 +11,7 @@ rust-version.workspace = true
version.workspace = true
[dependencies]
adb_client = { version = "^2.1.18" }
adb_client = { version = "^2.1.19", features = ["mdns"] }
clap = { version = "4.5.53", features = ["derive"] }
env_logger = { version = "0.11.8" }
log = { version = "0.4.29" }

View File

@@ -9,7 +9,7 @@ mod utils;
use adb_client::{
ADBDeviceExt, ADBListItemType, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice,
MDNSDiscoveryService,
mdns::MDNSDiscoveryService,
};
#[cfg(any(target_os = "linux", target_os = "macos"))]
@@ -22,6 +22,7 @@ use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::ExitCode;
use utils::setup_logger;
use crate::models::{ADBCliError, ADBCliResult};
@@ -108,7 +109,16 @@ fn run_command(mut device: Box<dyn ADBDeviceExt>, command: DeviceCommands) -> AD
Ok(())
}
fn main() -> ADBCliResult<()> {
fn main() -> ExitCode {
if let Err(err) = inner_main() {
log::error!("{err}");
return ExitCode::FAILURE;
}
ExitCode::SUCCESS
}
fn inner_main() -> ADBCliResult<()> {
// This depends on `clap`
let opts = Opts::parse();
@@ -174,9 +184,10 @@ fn main() -> ADBCliResult<()> {
log::info!("Starting mdns discovery...");
while let Ok(device) = rx.recv() {
log::info!(
"Found device {} with addresses {:?}",
"Found device fullname='{}' with ipv4 addresses={:?} and ipv6 addresses={:?}",
device.fullname,
device.addresses
device.ipv4_addresses(),
device.ipv6_addresses()
);
}

View File

@@ -1,4 +1,4 @@
use std::fmt::Debug;
use std::fmt::Display;
use adb_client::RustADBError;
@@ -9,19 +9,18 @@ pub enum ADBCliError {
MayNeedAnIssue(Box<dyn std::error::Error>),
}
impl Debug for ADBCliError {
impl Display for ADBCliError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ADBCliError::Standard(error) => write!(f, "{error}"),
ADBCliError::MayNeedAnIssue(error) => write!(
f,
r"
This error is abnormal and may need to fill an issue.
Please submit it to this project's repository here: https://github.com/cocool97/adb_client/issues.
Error source:
{error}
",
),
ADBCliError::MayNeedAnIssue(error) => {
write!(
f,
r"Error: {error}
An unexpected error occurred and may indicate a bug.
Please report this issue on the project repository (including steps to reproduce if possible): https://github.com/cocool97/adb_client/issues.",
)
}
}
}
}
@@ -68,7 +67,7 @@ impl From<adb_client::RustADBError> for ADBCliError {
| RustADBError::PoisonError
| RustADBError::UpgradeError(_)
| RustADBError::MDNSError(_)
| RustADBError::SendError(_)
| RustADBError::SendError
| RustADBError::UnknownFileMode(_)
| RustADBError::UnknownTransport(_) => Self::MayNeedAnIssue(value),
// List of [`RustADBError`] that may occur in standard contexts and therefore do not require for issues

View File

@@ -10,16 +10,21 @@ repository.workspace = true
rust-version.workspace = true
version.workspace = true
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[features]
default = []
mdns = ["dep:mdns-sd"]
[dependencies]
base64 = { version = "0.22.1" }
bincode = { version = "2.0.1", features = ["serde"] }
byteorder = { version = "1.5.0" }
chrono = { version = "0.4.42", default-features = false, features = ["std"] }
image = { version = "0.25.9", default-features = false }
image = { version = "0.25.9", default-features = false, features = ["png"] }
log = { version = "0.4.29" }
mdns-sd = { version = "0.17.1", default-features = false, features = [
"logging",
] }
num-bigint = { version = "0.8.6", package = "num-bigint-dig" }
num-traits = { version = "0.2.19" }
quick-protobuf = { version = "0.8.1" }
@@ -35,6 +40,13 @@ serde_repr = { version = "0.1.20" }
sha1 = { version = "0.10.6", features = ["oid"] }
thiserror = { version = "2.0.17" }
#########
# `mdns` feature-specific dependencies
mdns-sd = { version = "0.17.1", default-features = false, features = [
"logging",
], optional = true }
#########
[dev-dependencies]
anyhow = { version = "1.0.100" }
criterion = { version = "0.7.0" } # Used for benchmarks

View File

@@ -16,6 +16,19 @@ Add `adb_client` crate as a dependency by simply adding it to your `Cargo.toml`:
adb_client = "*"
```
## Crate features
| Feature | Description | Default? |
| :-----: | :---------------------------------------------: | :------: |
| `mdns` | Enables mDNS device discovery on local network. | No |
To deactivate some default features you can use the `default-features = false` option in your `Cargo.toml` file and manually specify the features you want to activate:
```toml
[dependencies]
adb_client = { version = "*", default-features = false, features = ["mdns"] }
```
## Benchmarks
Benchmarks run on `v2.0.6`, on a **Samsung S10 SM-G973F** device and an **Intel i7-1265U** CPU laptop
@@ -24,11 +37,11 @@ Benchmarks run on `v2.0.6`, on a **Samsung S10 SM-G973F** device and an **Intel
`ADBServerDevice` performs all operations by using adb server as a bridge.
|File size|Sample size|`ADBServerDevice`|`adb`|Difference|
|:-------:|:---------:|:----------:|:---:|:-----:|
|10 MB|100|350,79 ms|356,30 ms|<div style="color:green">-1,57 %</div>|
|500 MB|50|15,60 s|15,64 s|<div style="color:green">-0,25 %</div>|
|1 GB|20|31,09 s|31,12 s|<div style="color:green">-0,10 %</div>|
| File size | Sample size | `ADBServerDevice` | `adb` | Difference |
| :-------: | :---------: | :---------------: | :-------: | :------------------------------------: |
| 10 MB | 100 | 350,79 ms | 356,30 ms | <div style="color:green">-1,57 %</div> |
| 500 MB | 50 | 15,60 s | 15,64 s | <div style="color:green">-0,25 %</div> |
| 1 GB | 20 | 31,09 s | 31,12 s | <div style="color:green">-0,10 %</div> |
## Examples

View File

@@ -50,7 +50,9 @@ pub trait ADBDeviceExt {
/// Inner method requesting framebuffer from an Android device
fn framebuffer_inner(&mut self) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>>;
/// Dump framebuffer of this device into given path
/// Dump framebuffer of this device into given path.
///
/// Output data format is currently only `PNG`.
fn framebuffer(&mut self, path: &dyn AsRef<Path>) -> Result<()> {
// Big help from AOSP source code (<https://android.googlesource.com/platform/system/adb/+/refs/heads/main/framebuffer_service.cpp>)
let img = self.framebuffer_inner()?;

View File

@@ -36,12 +36,12 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
/// payload Wanted in
/// Next payload
fn read_bytes_from_transport(
requested_bytes: &usize,
requested_bytes: usize,
current_index: &mut usize,
transport: &mut T,
payload: &mut Vec<u8>,
local_id: &u32,
remote_id: &u32,
local_id: u32,
remote_id: u32,
) -> Result<Vec<u8>> {
if *current_index + requested_bytes <= payload.len() {
// if there is enough bytes in this payload
@@ -59,7 +59,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
// Request the next message
let send_message =
ADBTransportMessage::new(MessageCommand::Okay, *local_id, *remote_id, &[]);
ADBTransportMessage::new(MessageCommand::Okay, local_id, remote_id, &[]);
transport.write_message(send_message)?;
// Read the new message
*payload = transport.read_message()?.into_payload();
@@ -80,7 +80,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
// SEE: https://github.com/cstyan/adbDocumentation?tab=readme-ov-file#adb-list
{
let mut len_buf = Vec::from([0_u8; 4]);
LittleEndian::write_u32(&mut len_buf, path.as_ref().len() as u32);
LittleEndian::write_u32(&mut len_buf, u32::try_from(path.as_ref().len())?);
let subcommand_data = MessageSubcommand::List;
@@ -109,12 +109,12 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
// Loop though the response for all the entries
const STATUS_CODE_LENGTH_IN_BYTES: usize = 4;
let status_code = Self::read_bytes_from_transport(
&STATUS_CODE_LENGTH_IN_BYTES,
STATUS_CODE_LENGTH_IN_BYTES,
&mut current_index,
transport,
&mut payload,
&local_id,
&remote_id,
local_id,
remote_id,
)?;
match str::from_utf8(&status_code)? {
"DENT" => {
@@ -122,12 +122,12 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
const U32_SIZE_IN_BYTES: usize = 4;
const SIZE_OF_METADATA: usize = U32_SIZE_IN_BYTES * 4;
let metadata = Self::read_bytes_from_transport(
&SIZE_OF_METADATA,
SIZE_OF_METADATA,
&mut current_index,
transport,
&mut payload,
&local_id,
&remote_id,
local_id,
remote_id,
)?;
let mode = metadata[..U32_SIZE_IN_BYTES].to_vec();
let size = metadata[U32_SIZE_IN_BYTES..2 * U32_SIZE_IN_BYTES].to_vec();
@@ -140,12 +140,12 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
let name_len = LittleEndian::read_u32(&name_len) as usize;
// Read the file name, since it requires the length from the name_len
let name_buf = Self::read_bytes_from_transport(
&name_len,
name_len,
&mut current_index,
transport,
&mut payload,
&local_id,
&remote_id,
local_id,
remote_id,
)?;
let name = String::from_utf8(name_buf)?;
@@ -170,7 +170,7 @@ impl<T: ADBMessageTransport> ADBMessageDevice<T> {
"DONE" => {
return Ok(list_items);
}
x => log::error!("Got an unknown response {}", x),
x => log::error!("Got an unknown response {x}"),
}
}
}

View File

@@ -1,4 +1,4 @@
/// Represent a session between an ADBDevice and remote `adbd`.
/// Represent a session between an `ADBDevice` and remote `adbd`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ADBSession {
local_id: u32,

View File

@@ -115,11 +115,13 @@ pub enum RustADBError {
#[error("upgrade error: {0}")]
UpgradeError(String),
/// An error occurred while getting mdns devices
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
#[error(transparent)]
MDNSError(#[from] mdns_sd::Error),
/// An error occurred while sending data to channel
#[error(transparent)]
SendError(#[from] std::sync::mpsc::SendError<crate::MDNSDevice>),
#[error("error sending data to channel")]
SendError,
/// An unknown transport has been provided
#[error("unknown transport: {0}")]
UnknownTransport(String),

View File

@@ -3,13 +3,23 @@
#![forbid(missing_debug_implementations)]
#![forbid(missing_docs)]
#![doc = include_str!("../README.md")]
// Feature `doc_cfg` is currently only available on nightly builds.
// It is activated when cfg `docsrs` is enabled.
// Documentation can be build locally using:
// `RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --no-deps --all-features`
#![cfg_attr(docsrs, feature(doc_cfg))]
mod adb_device_ext;
mod constants;
mod device;
mod emulator_device;
mod error;
mod mdns;
/// MDNS-related definitions
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
pub mod mdns;
mod models;
mod server;
mod server_device;
@@ -20,7 +30,6 @@ pub use adb_device_ext::ADBDeviceExt;
pub use device::{ADBTcpDevice, ADBUSBDevice, is_adb_device, search_adb_devices};
pub use emulator_device::ADBEmulatorDevice;
pub use error::{Result, RustADBError};
pub use mdns::*;
pub use models::{ADBListItem, ADBListItemType, AdbStatResponse, RebootType};
pub use server::*;
pub use server_device::ADBServerDevice;

View File

@@ -1,4 +1,8 @@
use std::{collections::HashSet, net::IpAddr};
use std::{
collections::HashSet,
fmt::Display,
net::{IpAddr, Ipv4Addr, Ipv6Addr},
};
use mdns_sd::{ResolvedService, ScopedIp};
@@ -8,7 +12,41 @@ pub struct MDNSDevice {
/// Full device address when resolved
pub fullname: String,
/// Device IP addresses
pub addresses: HashSet<IpAddr>,
addresses: HashSet<IpAddr>,
}
impl MDNSDevice {
/// Return all adresses linked to this device
#[must_use]
pub fn addresses(&self) -> HashSet<IpAddr> {
self.addresses.clone()
}
/// Return all IPv4 addresses linked to this device
#[must_use]
pub fn ipv4_addresses(&self) -> HashSet<Ipv4Addr> {
self.addresses
.iter()
.filter_map(|addr| match addr {
IpAddr::V4(addr) => Some(addr),
IpAddr::V6(_) => None,
})
.copied()
.collect()
}
/// Return all IPv6 addresses linked to this device
#[must_use]
pub fn ipv6_addresses(&self) -> HashSet<Ipv6Addr> {
self.addresses
.iter()
.filter_map(|addr| match addr {
IpAddr::V4(_) => None,
IpAddr::V6(addr) => Some(addr),
})
.copied()
.collect()
}
}
impl From<Box<ResolvedService>> for MDNSDevice {
@@ -19,3 +57,13 @@ impl From<Box<ResolvedService>> for MDNSDevice {
}
}
}
impl Display for MDNSDevice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "Device fullname: {}", self.fullname)?;
writeln!(f, "IPv4 Addresses: {:?}", self.ipv4_addresses())?;
write!(f, "IPv6 Addresses: {:?}", self.ipv6_addresses())?;
Ok(())
}
}

View File

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

View File

@@ -22,6 +22,7 @@ pub struct ADBServer {
impl ADBServer {
/// Instantiates a new [`ADBServer`]
#[must_use]
pub fn new(address: SocketAddrV4) -> Self {
Self {
transport: None,
@@ -32,6 +33,7 @@ impl ADBServer {
}
/// Instantiates a new [`ADBServer`] with a custom adb path
#[must_use]
pub fn new_from_path(address: SocketAddrV4, adb_path: Option<String>) -> Self {
Self {
transport: None,

View File

@@ -12,6 +12,7 @@ pub struct ADBServerDevice {
impl ADBServerDevice {
/// Instantiates a new [`ADBServerDevice`], knowing its ADB identifier (as returned by `adb devices` command).
#[must_use]
pub fn new(identifier: String, server_addr: Option<SocketAddrV4>) -> Self {
let transport = TCPServerTransport::new_or_default(server_addr);
@@ -22,6 +23,7 @@ impl ADBServerDevice {
}
/// Instantiates a new [`ADBServerDevice`], assuming only one is currently connected.
#[must_use]
pub fn autodetect(server_addr: Option<SocketAddrV4>) -> Self {
let transport = TCPServerTransport::new_or_default(server_addr);

View File

@@ -4,7 +4,7 @@ use crate::{
};
use std::{
convert::TryInto,
io::{BufReader, BufWriter, Read, Write},
io::{self, BufReader, BufWriter, Read, Write},
str::{self, FromStr},
time::SystemTime,
};
@@ -22,7 +22,7 @@ impl<W: Write> ADBSendCommandWriter<W> {
impl<W: Write> Write for ADBSendCommandWriter<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let chunk_len = buf.len() as u32;
let chunk_len = u32::try_from(buf.len()).map_err(io::Error::other)?;
// 8 = "DATA".len() + sizeof(u32)
let mut buffer = Vec::with_capacity(8 + buf.len());

View File

@@ -26,6 +26,7 @@ impl Default for TCPServerTransport {
impl TCPServerTransport {
/// Instantiates a new instance of [`TCPServerTransport`]
#[must_use]
pub fn new(socket_addr: SocketAddrV4) -> Self {
Self {
socket_addr,

19
examples/mdns/Cargo.toml Normal file
View File

@@ -0,0 +1,19 @@
[package]
name = "mdns"
authors.workspace = true
edition.workspace = true
homepage.workspace = true
keywords.workspace = true
license.workspace = true
repository.workspace = true
version.workspace = true
rust-version.workspace = true
[[bin]]
name = "mdns"
path = "main.rs"
[dependencies]
adb_client = { path = "../../adb_client", default-features = false, features = [
"mdns",
] }

19
examples/mdns/main.rs Normal file
View File

@@ -0,0 +1,19 @@
use std::sync::mpsc;
use adb_client::mdns::{MDNSDevice, MDNSDiscoveryService};
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Starting mDNS device discovery...");
// Create a channel to receive discovered devices information
let (sender, receiver) = mpsc::channel::<MDNSDevice>();
// Create and start the discovery service
let mut discovery = MDNSDiscoveryService::new()?;
discovery.start(sender)?;
loop {
let device = receiver.recv()?;
println!("{device}");
}
}

View File

@@ -1,4 +1,4 @@
# pyadb_client
# `pyadb_client`
<p align="center">
<p align="center">Python library to communicate with ADB devices. Built on top of Rust adb_client library.</p>