libadb-ffi 0.9.0

C ABI for libadb
Documentation
use alloc::ffi::CString;
use alloc::format;
use core::cell::RefCell;
use core::ffi::c_char;

use libadb::base::error::{Error, ProtocolError, ReverseError};
#[cfg(feature = "pairing")]
use libadb::pairing::PairingError;

use crate::transport::FfiConnectError;

/// Status code returned by most FFI entry points.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AdbStatus {
    /// Success.
    Ok = 0,
    /// An argument the call cannot take, such as a null pointer, a zero
    /// `buf_len` for a read, or a channel id that names no slot of the
    /// connection.
    InvalidArg = 1,
    /// The URI does not parse, or names a transport the call does not
    /// take, as `usb://` for `adb_pair`.
    InvalidUri = 2,
    /// The transport the URI names could not be opened, as when nothing
    /// answers at the address.
    Connect = 3,
    /// An I/O error, such as a connection that broke or a read that
    /// timed out.
    Io = 4,
    /// Authentication failed or the key cannot be used: the device does
    /// not trust it, the sign callback failed, or the key does not parse.
    Auth = 5,
    /// What came in breaks the protocol, or a request cannot be sent as
    /// given, such as a NUL in a shell command.
    Protocol = 6,
    /// The channel is closed, by either end, or its id is stale.
    ChannelClosed = 7,
    /// Every channel slot of the connection is in use.
    NoFreeChannels = 8,
    /// A write was abandoned mid-packet, by a write timeout for one, so
    /// every later channel operation fails with this; reads first hand
    /// over what had already arrived.
    Desynchronized = 9,
    /// The device's reverse rule service refused the request; the
    /// device's own message is in [`adb_last_error`].
    Reverse = 10,
    /// The device answered the handshake with `STLS` (Android 11+
    /// wireless debugging) and this call cannot start TLS: the library
    /// was built without the `tls` feature, or the key sits behind an
    /// [`adb_authenticator_t`](crate::adb_authenticator_t). The message
    /// says which.
    TlsRequired = 11,
    /// `adb_pair`: the device did not take the key. The code did not
    /// match, or the device ended the exchange itself (dialog
    /// dismissed, attempts used up); [`adb_last_error`] says which.
    Pairing = 12,
    /// The connection has ended and nothing more will arrive from the
    /// device. The call that saw this returned [`AdbStatus::Io`] or
    /// [`AdbStatus::Protocol`]; every later call that waits on the
    /// device gets this status, a read only after handing over what had
    /// already arrived. A read timeout never leads here. Open a new
    /// connection.
    Disconnected = 13,
    /// A failure no other status describes, such as a key no
    /// certificate can be built for.
    Internal = 255,
}

#[cfg(not(feature = "tls"))]
const TLS_REQUIRED: &str = "device requires TLS (Android 11+ wireless debugging): \
    build libadb-ffi with the `tls` feature, connect over USB, \
    or switch the device to plain TCP with `adb tcpip 5555`";
#[cfg(feature = "tls")]
const TLS_REQUIRED: &str = "device requires TLS (Android 11+ wireless debugging), \
    which only adb_connect with the private key can start: \
    adb_connect_with_authenticator stays in the clear";

std::thread_local! {
    static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
}

fn set(msg: impl core::fmt::Display) {
    let s = format!("{msg}").replace('\0', " ");
    let c = CString::new(s).unwrap_or_else(|_| CString::new("<error>").unwrap());
    LAST_ERROR.with(|l| *l.borrow_mut() = Some(c));
}

pub(crate) fn clear_last_error() {
    LAST_ERROR.with(|l| *l.borrow_mut() = None);
}

pub(crate) fn fail_invalid_arg(msg: impl core::fmt::Display) -> AdbStatus {
    set(msg);
    AdbStatus::InvalidArg
}

pub(crate) fn fail_io(msg: impl core::fmt::Display) -> AdbStatus {
    set(msg);
    AdbStatus::Io
}

pub(crate) fn fail_auth(msg: impl core::fmt::Display) -> AdbStatus {
    set(msg);
    AdbStatus::Auth
}

pub(crate) fn fail_internal(msg: impl core::fmt::Display) -> AdbStatus {
    set(msg);
    AdbStatus::Internal
}

#[cfg(feature = "pairing")]
pub(crate) fn fail_invalid_uri(msg: impl core::fmt::Display) -> AdbStatus {
    set(msg);
    AdbStatus::InvalidUri
}

#[cfg(feature = "pairing")]
pub(crate) fn fail_pairing(e: PairingError<std::io::Error>) -> AdbStatus {
    let status = match &e {
        PairingError::WrongCode => AdbStatus::Pairing,
        PairingError::Closed => AdbStatus::Pairing,
        PairingError::Transport(_) => AdbStatus::Io,
        PairingError::Frame(_) | PairingError::Spake2(_) | PairingError::PeerInfo(_) => {
            AdbStatus::Protocol
        }
        _ => AdbStatus::Internal,
    };
    set(e);
    status
}

pub(crate) fn fail_ffi_connect(e: FfiConnectError) -> AdbStatus {
    let status = match &e {
        FfiConnectError::Uri(_) => AdbStatus::InvalidUri,
        _ => AdbStatus::Connect,
    };
    set(e);
    status
}

pub(crate) fn fail_error<E: core::fmt::Display>(e: Error<E>) -> AdbStatus {
    let status = match &e {
        Error::Protocol(ProtocolError::TlsRequired) => {
            set(TLS_REQUIRED);
            return AdbStatus::TlsRequired;
        }
        Error::Io(_) | Error::UnexpectedEof => AdbStatus::Io,
        Error::Auth(_) => AdbStatus::Auth,
        Error::Protocol(_) => AdbStatus::Protocol,
        Error::ChannelClosed => AdbStatus::ChannelClosed,
        Error::NoFreeChannels => AdbStatus::NoFreeChannels,
        Error::Desynchronized => AdbStatus::Desynchronized,
        Error::Disconnected => AdbStatus::Disconnected,
        Error::Reverse(ReverseError::Failed(_)) => AdbStatus::Reverse,
        Error::Reverse(ReverseError::UnexpectedReply) => AdbStatus::Protocol,
        _ => AdbStatus::Internal,
    };
    set(e);
    status
}

/// Return a pointer to a C string describing the last error that
/// occurred on this thread, or NULL if no error is set.
///
/// The pointer is valid until the next FFI call on this thread.
#[unsafe(no_mangle)]
pub extern "C" fn adb_last_error() -> *const c_char {
    LAST_ERROR.with(|l| match &*l.borrow() {
        Some(c) => c.as_ptr(),
        None => core::ptr::null(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn disconnected_reaches_c_as_its_own_status() {
        let status = fail_error(Error::<core::convert::Infallible>::Disconnected);
        assert_eq!(status, AdbStatus::Disconnected);
        assert_eq!(
            status as i32, 13,
            "must match ADB_ERR_DISCONNECTED in libadb.h"
        );
    }
}