libadb 0.9.0

Low-level ADB protocol library for direct TCP and USB communication
Documentation
use alloc::sync::Arc;
use core::convert::Infallible;
use core::sync::atomic::{AtomicBool, Ordering};
use embedded_io::ErrorType;
use embedded_io_async::Write;
use event_listener::EventListener;

use alloc::vec::Vec;

use super::shared::Shared;
use crate::base::channel::ChannelId;
use crate::base::incoming::PendingOpen;
use crate::base::protocol::command::Command;
use crate::base::protocol::Packet;
use crate::base::slot::ChannelSlot;
use crate::base::wire::{connection_gone, send_pkt};
use crate::error::Error;

#[cfg(doc)]
use super::{Reader, Writer};

/// A device-initiated channel awaiting a verdict, on a split
/// connection. Owns the request — holding it does not borrow the
/// [`Reader`]. Dropping it undecided puts the request back at the head
/// of the queue.
pub struct SplitIncoming<WH>
where
    WH: Write,
{
    pub(super) shared: Arc<Shared<WH>>,
    pub(super) pending: Option<PendingOpen>,
    pub(super) reserved: Option<ChannelId>,
    pub(super) cancelled: Arc<AtomicBool>,
}

impl<WH> SplitIncoming<WH>
where
    WH: Write,
{
    /// The destination the device asked for, e.g. `tcp:8080\0`.
    pub fn destination(&self) -> &[u8] {
        &self.pending.as_ref().expect("undecided").destination
    }

    /// Take the channel: allocates a slot, answers READY (carrying our
    /// receive credit when delayed ack is on) and returns the channel.
    ///
    /// With every slot in use the request is refused with CLSE and
    /// [`Error::NoFreeChannels`] comes back. A request the device has
    /// withdrawn in the meantime (a CLSE for its OPEN) is not taken: no
    /// READY is sent and [`Error::ChannelClosed`] comes back.
    ///
    /// A READY or CLSE that fails comes back as the error, with the slot
    /// released and the request back in the queue. If the device is gone
    /// the request is consumed instead, and the next
    /// [`IncomingListener::accept`] or [`Reader::accept_incoming`] goes
    /// on to whatever comes after it.
    ///
    /// Dropping this future never loses the request: the reserved slot
    /// is released and the request returns to the queue. A drop after
    /// the READY's write was first polled still
    /// [desynchronizes the connection](crate::split#dropping-a-call).
    pub async fn accept(mut self) -> Result<ChannelId, Error<<WH as ErrorType>::Error>> {
        let pending = self.pending.as_ref().expect("undecided");
        let (remote, credit) = (pending.remote, pending.credit);
        let shared = Arc::clone(&self.shared);

        let reserved = {
            let mut chs = shared.lock_channels();
            if self.cancelled.load(Ordering::Relaxed) {
                self.pending.take();
                return Err(Error::ChannelClosed);
            }
            chs.allocate().ok().inspect(|&ch| {
                chs.insert_accepted(ch, remote, credit);
            })
        };
        let Some(ch) = reserved else {
            self.answer(&Packet::refuse(remote)).await?;
            return Err(Error::NoFreeChannels);
        };
        self.reserved = Some(ch);

        let payload = match shared.negotiated.advertised_credit() {
            Some(credit) => credit.to_le_bytes().to_vec(),
            None => Vec::new(),
        };
        let ready = Packet::new(Command::Ready, ch.local.raw(), remote.raw(), payload);
        let mut wh = shared.lock_write_half().await;
        if shared
            .lock_channels()
            .get(ch)
            .is_none_or(ChannelSlot::is_closed)
        {
            self.pending.take();
            return Err(Error::ChannelClosed);
        }
        self.send(&mut wh, &ready).await?;

        self.reserved = None;
        Ok(ch)
    }

    /// Refuse the channel: answers CLSE and frees nothing, since
    /// nothing was allocated.
    ///
    /// A request the device has withdrawn in the meantime is consumed
    /// silently: it no longer expects an answer.
    ///
    /// A CLSE that fails comes back as the error, with the request back
    /// in the queue. If the device is gone the request is consumed
    /// instead.
    ///
    /// Dropping this future never loses the request: it returns to the
    /// queue. A drop after the CLSE's write was first polled still
    /// [desynchronizes the connection](crate::split#dropping-a-call).
    pub async fn reject(mut self) -> Result<(), Error<<WH as ErrorType>::Error>> {
        if self.cancelled.load(Ordering::Relaxed) {
            self.pending.take();
            return Ok(());
        }
        let remote = self.pending.as_ref().expect("undecided").remote;
        self.answer(&Packet::refuse(remote)).await
    }

    async fn answer(&mut self, verdict: &Packet) -> Result<(), Error<<WH as ErrorType>::Error>> {
        let shared = Arc::clone(&self.shared);
        let mut wh = shared.lock_write_half().await;
        self.send(&mut wh, verdict).await
    }

    async fn send(
        &mut self,
        wh: &mut WH,
        verdict: &Packet,
    ) -> Result<(), Error<<WH as ErrorType>::Error>> {
        let sent = send_pkt(
            wh,
            &self.shared.desync,
            verdict,
            self.shared.negotiated.checksum(),
        )
        .await;
        if sent.as_ref().err().is_none_or(connection_gone) {
            self.pending.take();
        }
        sent
    }
}

impl<WH> Drop for SplitIncoming<WH>
where
    WH: Write,
{
    fn drop(&mut self) {
        if let Some(ch) = self.reserved.take() {
            self.shared.lock_channels().free(ch);
        }
        let mut staged = self.shared.lock_staged();
        let mut incoming = self.shared.lock_incoming();
        staged.retain(|(_, flag)| !Arc::ptr_eq(flag, &self.cancelled));
        if let Some(pending) = self.pending.take() {
            if !self.cancelled.load(Ordering::Relaxed) {
                incoming.push_front(pending);
                self.shared.incoming_signal.notify(usize::MAX);
            }
        }
    }
}

/// Channels the device opens toward the host, taken on a connection
/// whose [`Reader::run`] dispatches packets. Made by
/// [`Writer::listen_incoming`]; while any listener lives, `run` keeps
/// such requests for it — up to the channel table's size, past which
/// they are refused on arrival — and refuses them once none does.
pub struct IncomingListener<WH>
where
    WH: Write,
{
    pub(super) shared: Arc<Shared<WH>>,
}

impl<WH> IncomingListener<WH>
where
    WH: Write,
{
    /// Wait for a device-initiated channel and hand it over for a
    /// verdict, as [`Reader::accept_incoming`] does on a reader-driven
    /// connection. The accepted channel is then worked through the
    /// [`Writer`] like any other.
    ///
    /// Cancellation-safe: a request is only taken once it is returned.
    pub async fn accept(&self) -> Result<SplitIncoming<WH>, Error<<WH as ErrorType>::Error>> {
        let mut listener: Option<EventListener> = None;
        loop {
            if self.shared.desync.check::<Infallible>().is_err() {
                self.shared.check_live()?;
            }
            if let Some(incoming) = self.shared.take_incoming() {
                return Ok(incoming);
            }
            self.shared.check_live()?;
            match listener.take() {
                Some(waiting) => waiting.await,
                None => listener = Some(self.shared.incoming_signal.listen()),
            }
        }
    }
}

impl<WH> Drop for IncomingListener<WH>
where
    WH: Write,
{
    fn drop(&mut self) {
        self.shared.listeners.fetch_sub(1, Ordering::AcqRel);
    }
}