libadb 0.9.0

Low-level ADB protocol library for direct TCP and USB communication
Documentation
//! Android Binder Bridge (ABB) protocol.
//!
//! Available on Android 10+ devices that advertise the `abb` or `abb_exec`
//! feature, ABB lets the host invoke Android service commands (the `cmd`
//! tool) through binder without spawning a shell process.
//!
//! Two channel types with **different wire formats**:
//!
//! | Destination | Wire format | Use case |
//! |---|---|---|
//! | `abb_exec:<arg0>\0<arg1>\0…` | **Raw** — plain stdout bytes | One-shot command |
//! | `abb:<arg0>\0<arg1>\0…` | **shell_v2** framing | Interactive / streaming |
//!
//! Arguments are the tokens you would pass to `cmd` on the device.
//! For example, `cmd package list packages` becomes
//! `&["package", "list", "packages"]`.
//!
//! An empty token fails with
//! [`ProtocolError::InvalidDestination`](crate::ProtocolError::InvalidDestination),
//! as one holding a NUL does. adbd drops empty arguments here, so
//! `&["pm", "", "x"]` would run as `&["pm", "x"]`, a different command.
//! [`cmd`](crate::cmd) sends such a command through the shell instead.
//!
//! # Examples
//!
//! ```ignore
//! // One-shot: list installed packages (raw output)
//! let mut rx = [0u8; 64 * 1024];
//! let output = abb::exec(&mut conn, &["package", "list", "packages"], &mut rx).await?;
//! // output is Vec<u8> of raw stdout
//!
//! // Interactive / streaming (shell_v2 framed)
//! let mut session = abb::open(&mut conn, &["activity", "monitor"], &mut rx).await?;
//! loop {
//!     match session.read_frame().await? {
//!         Frame::Stdout(data) => { /* … */ }
//!         Frame::Exit(code) => break,
//!         _ => {}
//!     }
//! }
//! ```

use alloc::vec::Vec;

use crate::base::channel::{Capped, Channel, ReadToEnd};
use crate::base::destination::build_nul_destination;
use crate::base::protocol::features::Feature;
use crate::base::session::Session;
use crate::error::Error;
use crate::shell::v2::Shell;

/// Open a raw `abb_exec:` channel. The device sends plain stdout bytes
/// (no shell_v2 framing) and closes the channel when the command
/// finishes.
///
/// `args` are the tokens that would follow `cmd` on the device shell.
/// For example, to run `cmd package list packages -3` pass
/// `&["package", "list", "packages", "-3"]`. An empty one fails, as the
/// [module docs](self) say.
pub async fn open_exec<'a, S: Session>(
    session: &'a mut S,
    args: &[&str],
) -> Result<Channel<'a, S>, Error<S::IoError>> {
    session.require_feature(Feature::AbbExec)?;
    let dest = build_nul_destination("abb_exec:", args)?;
    session.open(&dest).await
}

/// Run a one-shot ABB command, returning the raw stdout output.
///
/// Opens an `abb_exec:` channel, reads all output until the device
/// closes the channel, and returns the collected bytes.
///
/// `args` are the tokens that would follow `cmd` on the device shell, and
/// an empty one fails, as the [module docs](self) say.
/// `rx` is used as a temporary read buffer (not retained after return);
/// an empty one fails with [`Error::ReceiveBufferFull`] before anything
/// is sent.
pub async fn exec<S: Session>(
    session: &mut S,
    args: &[&str],
    rx: &mut [u8],
) -> Result<Vec<u8>, Error<S::IoError>> {
    if rx.is_empty() {
        return Err(Error::ReceiveBufferFull);
    }
    open_exec(session, args)
        .await?
        .read_to_vec(rx, usize::MAX)
        .await?
        .map_err(|Capped| Error::ReceiveBufferFull)
}

/// Open an interactive `abb:` channel for streaming or bidirectional
/// communication with an Android service.
///
/// Uses shell_v2 framing — the caller reads frames via
/// [`Shell::read_frame`] / [`Shell::pump`] and writes stdin via
/// [`Shell::write_stdin`].
///
/// `args` are the tokens that would follow `cmd` on the device shell, and
/// an empty one fails, as the [module docs](self) say.
/// `rx` is the caller-owned receive buffer — see [`Shell::new`] for
/// sizing advice.
pub async fn open<'a, 'b, S: Session>(
    session: &'a mut S,
    args: &[&str],
    rx: &'b mut [u8],
) -> Result<Shell<'a, 'b, S>, Error<S::IoError>> {
    session.require_feature(Feature::Abb)?;
    let dest = build_nul_destination("abb:", args)?;
    let channel = session.open(&dest).await?;
    Ok(Shell::new(channel, rx))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::base::mock::{now, okay, one_slot};

    #[test]
    fn destination_abb_exec_multiple_args() {
        let dest = build_nul_destination("abb_exec:", &["package", "list", "packages"]).unwrap();
        assert_eq!(dest, b"abb_exec:package\0list\0packages\0");
    }

    #[test]
    fn destination_abb_single_arg() {
        let dest = build_nul_destination("abb:", &["connectivity"]).unwrap();
        assert_eq!(dest, b"abb:connectivity\0");
    }

    #[test]
    fn destination_no_args() {
        let dest = build_nul_destination("abb_exec:", &[]).unwrap();
        assert_eq!(dest, b"abb_exec:\0");
    }

    #[test]
    fn destination_rejects_nul_in_arg() {
        use crate::error::ProtocolError;
        assert_eq!(
            build_nul_destination("abb_exec:", &["bad\0arg"]),
            Err(ProtocolError::InvalidDestination)
        );
    }

    #[test]
    fn destination_rejects_an_empty_argument() {
        use crate::error::ProtocolError;
        for args in [&["pm", "", "x"][..], &["", "x"], &["pm", ""], &[""]] {
            assert_eq!(
                build_nul_destination("abb:", args),
                Err(ProtocolError::InvalidDestination),
                "{args:?}"
            );
        }
    }

    #[test]
    fn an_empty_argument_opens_nothing() {
        use crate::error::ProtocolError::InvalidDestination;
        let mut conn = one_slot("abb,abb_exec", &[]);
        let mut rx = [0u8; 16];
        let args = ["pm", "", "x"];

        let exec = now(exec(&mut conn, &args, &mut rx));
        assert!(matches!(exec, Err(Error::Protocol(InvalidDestination))));
        let open_exec = now(open_exec(&mut conn, &args)).map(drop);
        assert!(matches!(
            open_exec,
            Err(Error::Protocol(InvalidDestination))
        ));
        let opened = now(open(&mut conn, &args, &mut rx)).map(drop);
        assert!(matches!(opened, Err(Error::Protocol(InvalidDestination))));

        assert_eq!(conn.transport().sent().len(), 1, "the CNXN alone");
    }

    #[test]
    fn exec_with_an_empty_buffer_fails_before_anything_is_sent() {
        let mut conn = one_slot("abb_exec", &[]);
        let err = now(exec(&mut conn, &["package", "list"], &mut [])).unwrap_err();
        assert!(matches!(err, Error::ReceiveBufferFull), "got {err:?}");
        assert_eq!(conn.transport().sent().len(), 1, "the CNXN alone");
    }

    #[test]
    fn exec_frees_its_slot_when_a_read_fails() {
        // Nothing follows the OKAY: the read runs into the end of the
        // transport.
        let mut conn = one_slot("abb_exec", &[]);
        let mut rx = [0u8; 16];
        let err = now(exec(&mut conn, &["package", "list"], &mut rx)).unwrap_err();
        assert!(matches!(err, Error::UnexpectedEof), "got {err:?}");

        conn.transport_mut().feed(&okay(2));
        now(conn.open_channel(b"shell:\0")).expect("the failed exec kept its slot");
    }
}