libadb 0.1.0

Low-level ADB protocol library for direct TCP and USB communication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! Full-duplex Reader/Writer pair for a Connection whose transport is
//! [`Splittable`](crate::Splittable).
//!
//! `Reader` owns the read half and drives packet reception; `Writer`
//! owns a cheap handle to the shared write-half + channel table and can
//! be cloned for use from other threads/tasks. Read-path and write-path
//! never hold the same mutex concurrently, so a thread blocked in
//! [`Reader::read_channel`] does not prevent another thread from calling
//! [`Writer::write_channel`] or [`Writer::close_channel`].
//!
//! Available under the `split` feature (implied by every runtime
//! feature: `tokio`, `smol`, `nusb`, `rusb`). Pulls `std` into the
//! build for its sync primitives; a pure `no_std` variant would need a
//! no_std Mutex implementation and is not yet provided.
//!
//! # Close ↔ read coordination
//!
//! Because only the `Reader` drives packet reception, calling
//! [`Writer::close_channel`] does not by itself wake a concurrent
//! [`Reader::read_channel`] parked on the same channel: the reader
//! unblocks only once it receives the device's echoed `CLSE` packet.
//! If the device is slow or non-conformant and never echoes the close,
//! an in-flight `read_channel` can remain blocked until the transport
//! itself fails. Drop the `Reader` (or fail the transport) to unblock
//! such a reader unconditionally.

#![cfg(feature = "split")]

use alloc::sync::Arc;
use async_lock::Mutex as AsyncMutex;
use bytes::BytesMut;
use core::sync::atomic::{AtomicU32, Ordering};
use embedded_io::ErrorType;
use embedded_io_async::{Read, Write};
use event_listener::{Event, EventListener};
use std::sync::Mutex;

use crate::base::channel::{
    channel_ids_of, dispatch_packet, slot_for_mut, ChannelId, ChannelSlot, DispatchOutcome,
};
use crate::base::connection::{DEFAULT_MAX_CHANNELS, DEFAULT_MAX_FEATURES, DEFAULT_MAX_PROPERTIES};
use crate::base::error::Error;
use crate::base::protocol::command::Command;
use crate::base::protocol::features;
use crate::base::protocol::packet::Packet;
use crate::base::wire::{recv_pkt, send_okay_to, send_pkt, send_raw};
use crate::device_banner::DeviceBanner;

pub(crate) struct FlowSignal {
    event: Event,
}

impl FlowSignal {
    pub(crate) const fn new() -> Self {
        Self {
            event: Event::new(),
        }
    }

    fn listen(&self) -> EventListener {
        self.event.listen()
    }

    fn wake(&self) {
        self.event.notify(usize::MAX);
    }
}

pub(crate) struct Shared<WH, const MC: usize, const MP: usize, const MF: usize> {
    pub(crate) write_half: AsyncMutex<WH>,
    pub(crate) channels: Mutex<[Option<ChannelSlot>; MC]>,
    pub(crate) signals: [FlowSignal; MC],
    pub(crate) max_payload: u32,
    pub(crate) delayed_ack: bool,
    pub(crate) device_banner: Option<DeviceBanner<MP, MF>>,
    pub(crate) local_id_counter: AtomicU32,
}

impl<WH, const MC: usize, const MP: usize, const MF: usize> Shared<WH, MC, MP, MF> {
    fn next_local_id(&self) -> u32 {
        loop {
            let id = self.local_id_counter.fetch_add(1, Ordering::Relaxed);
            if id != 0 {
                return id;
            }
        }
    }

    fn lock_channels(&self) -> std::sync::MutexGuard<'_, [Option<ChannelSlot>; MC]> {
        self.channels.lock().unwrap_or_else(|p| p.into_inner())
    }
}

struct SlotGuard<WH, const MC: usize, const MP: usize, const MF: usize> {
    shared: Arc<Shared<WH, MC, MP, MF>>,
    idx: usize,
    armed: bool,
}

impl<WH, const MC: usize, const MP: usize, const MF: usize> SlotGuard<WH, MC, MP, MF> {
    fn new(shared: Arc<Shared<WH, MC, MP, MF>>, idx: usize) -> Self {
        Self {
            shared,
            idx,
            armed: true,
        }
    }

    fn disarm(&mut self) {
        self.armed = false;
    }
}

impl<WH, const MC: usize, const MP: usize, const MF: usize> Drop for SlotGuard<WH, MC, MP, MF> {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        let mut chs = self.shared.lock_channels();
        if self.idx < chs.len() {
            chs[self.idx] = None;
        }
    }
}

struct CreditGuard<'a, WH, const MC: usize, const MP: usize, const MF: usize> {
    shared: &'a Shared<WH, MC, MP, MF>,
    ch: ChannelId,
    n: usize,
    committed: bool,
}

impl<'a, WH, const MC: usize, const MP: usize, const MF: usize> CreditGuard<'a, WH, MC, MP, MF> {
    fn new(shared: &'a Shared<WH, MC, MP, MF>, ch: ChannelId, n: usize) -> Self {
        Self {
            shared,
            ch,
            n,
            committed: false,
        }
    }

    fn commit(&mut self) {
        self.committed = true;
    }
}

impl<WH, const MC: usize, const MP: usize, const MF: usize> Drop
    for CreditGuard<'_, WH, MC, MP, MF>
{
    fn drop(&mut self) {
        if self.committed {
            return;
        }
        {
            let mut chs = self.shared.lock_channels();
            if let Some(slot) = slot_for_mut(&mut *chs, self.ch) {
                slot.refund(self.n, self.shared.delayed_ack);
            }
        }
        if let Some(signal) = self.shared.signals.get(self.ch.slot) {
            signal.wake();
        }
    }
}

/// Read half of a split [`Connection`](crate::Connection).
///
/// Drives packet reception, dispatching OKAY/CLSE/WRTE packets for all
/// channels. Only one Reader exists per connection.
pub struct Reader<
    RH,
    WH,
    const MAX_CHANNELS: usize = DEFAULT_MAX_CHANNELS,
    const MAX_PROPERTIES: usize = DEFAULT_MAX_PROPERTIES,
    const MAX_FEATURES: usize = DEFAULT_MAX_FEATURES,
> where
    RH: Read,
    WH: Write<Error = <RH as ErrorType>::Error>,
{
    read_half: RH,
    recv_buf: BytesMut,
    shared: Arc<Shared<WH, MAX_CHANNELS, MAX_PROPERTIES, MAX_FEATURES>>,
}

impl<RH, WH, const MC: usize, const MP: usize, const MF: usize> Reader<RH, WH, MC, MP, MF>
where
    RH: Read,
    WH: Write<Error = <RH as ErrorType>::Error>,
{
    pub(crate) fn new(
        read_half: RH,
        recv_buf: BytesMut,
        shared: Arc<Shared<WH, MC, MP, MF>>,
    ) -> Self {
        Self {
            read_half,
            recv_buf,
            shared,
        }
    }

    /// Negotiated max payload (bytes).
    pub fn max_payload(&self) -> u32 {
        self.shared.max_payload
    }

    /// Whether delayed-ACK flow control was negotiated.
    pub fn delayed_ack(&self) -> bool {
        self.shared.delayed_ack
    }

    /// Raw device banner bytes from the CNXN handshake.
    pub fn device_banner(&self) -> Option<&[u8]> {
        self.shared.device_banner.as_ref().map(|b| b.raw())
    }

    /// Parsed device banner from the CNXN handshake.
    pub fn device_banner_parsed(&self) -> Option<&DeviceBanner<MP, MF>> {
        self.shared.device_banner.as_ref()
    }

    /// Fail with [`Error::MissingFeature`] if the device banner was
    /// parsed and does not list `feature`. Permissive when no banner
    /// is available.
    pub fn require_feature(
        &self,
        feature: crate::protocol::features::Feature,
    ) -> Result<(), Error<<RH as ErrorType>::Error>> {
        match &self.shared.device_banner {
            Some(b) if b.has_feature(&feature) => Ok(()),
            Some(_) => Err(Error::MissingFeature(feature)),
            None => Ok(()),
        }
    }

    /// Open a channel to `destination`.
    ///
    /// Sends OPEN and waits for the matching OKAY (while dispatching any
    /// unrelated packets that arrive in the meantime).
    ///
    /// **Not cancellation-safe.** Dropping the future after the OPEN
    /// packet has been sent leaves the device-side channel half-open
    /// until the connection is closed — async Drop cannot send the
    /// matching CLSE. If the call returns `Err`, a best-effort CLSE is
    /// sent before the error propagates.
    pub async fn open_channel(
        &mut self,
        destination: &[u8],
    ) -> Result<ChannelId, Error<<RH as ErrorType>::Error>> {
        let (slot_idx, local_id) = {
            let mut chs = self.shared.lock_channels();
            let idx = chs
                .iter()
                .position(|s| s.is_none())
                .ok_or(Error::NoFreeChannels)?;
            let id = self.shared.next_local_id();
            chs[idx] = Some(ChannelSlot::new(id));
            (idx, id)
        };
        let mut guard = SlotGuard::new(Arc::clone(&self.shared), slot_idx);

        let open_arg1 = if self.shared.delayed_ack {
            features::INITIAL_DELAYED_ACK_BYTES
        } else {
            0
        };
        let pkt = Packet::new(Command::Open, local_id, open_arg1, destination.to_vec());
        {
            let mut wh = self.shared.write_half.lock().await;
            send_pkt(&mut *wh, &pkt).await?;
        }

        let result = self.await_open_ack(local_id, slot_idx, &mut guard).await;
        if let Err(ref e) = result {
            if !matches!(e, Error::ChannelClosed) {
                let mut wh = self.shared.write_half.lock().await;
                let _ = send_raw(&mut *wh, Command::Close, local_id, 0, &[]).await;
            }
        }
        result
    }

    async fn await_open_ack(
        &mut self,
        local_id: u32,
        slot_idx: usize,
        guard: &mut SlotGuard<WH, MC, MP, MF>,
    ) -> Result<ChannelId, Error<<RH as ErrorType>::Error>> {
        loop {
            let pkt = recv_pkt(&mut self.read_half, &mut self.recv_buf).await?;
            match pkt.command {
                Command::Ready if pkt.arg1 == local_id => {
                    {
                        let mut chs = self.shared.lock_channels();
                        if let Some(slot) = chs[slot_idx].as_mut() {
                            slot.accept_open_ready(pkt.arg0, &pkt.data, self.shared.delayed_ack)?;
                        }
                    }
                    guard.disarm();
                    return Ok(ChannelId {
                        slot: slot_idx,
                        local_id,
                    });
                }
                Command::Close if pkt.arg1 == local_id => {
                    return Err(Error::ChannelClosed);
                }
                _ => self.dispatch(pkt).await?,
            }
        }
    }

    /// Read from channel `ch` into `buf`. Returns the number of bytes read.
    ///
    /// Returns immediately if data is already buffered; otherwise blocks
    /// reading packets until a WRTE for `ch` arrives (dispatching packets
    /// for other channels in the meantime).
    ///
    /// A concurrent [`Writer::close_channel`] on the same channel does
    /// not wake this call directly — see the module-level note on
    /// close ↔ read coordination.
    pub async fn read_channel(
        &mut self,
        ch: ChannelId,
        buf: &mut [u8],
    ) -> Result<usize, Error<<RH as ErrorType>::Error>> {
        {
            let mut chs = self.shared.lock_channels();
            let slot = slot_for_mut(&mut *chs, ch).ok_or(Error::ChannelClosed)?;
            if !slot.rx_buf.is_empty() {
                let n = buf.len().min(slot.rx_buf.len());
                buf[..n].copy_from_slice(&slot.rx_buf[..n]);
                let _ = slot.rx_buf.split_to(n);
                return Ok(n);
            }
            if slot.is_closed() {
                return Err(Error::ChannelClosed);
            }
        }

        let (local_id, remote_id) = self.channel_ids(ch)?;

        loop {
            let pkt = recv_pkt(&mut self.read_half, &mut self.recv_buf).await?;
            match pkt.command {
                Command::Write if pkt.arg1 == local_id => {
                    let payload_len = pkt.data.len();
                    {
                        let mut wh = self.shared.write_half.lock().await;
                        send_okay_to(
                            &mut *wh,
                            self.shared.delayed_ack,
                            local_id,
                            remote_id,
                            payload_len,
                        )
                        .await?;
                    }

                    let n = buf.len().min(pkt.data.len());
                    buf[..n].copy_from_slice(&pkt.data[..n]);
                    if n < pkt.data.len() {
                        let mut chs = self.shared.lock_channels();
                        if let Some(slot) = slot_for_mut(&mut *chs, ch) {
                            slot.rx_buf.extend_from_slice(&pkt.data[n..]);
                        }
                    }
                    return Ok(n);
                }
                Command::Close if pkt.arg1 == local_id => {
                    {
                        let mut chs = self.shared.lock_channels();
                        if let Some(slot) = slot_for_mut(&mut *chs, ch) {
                            slot.apply_close();
                        }
                    }
                    if let Some(signal) = self.shared.signals.get(ch.slot) {
                        signal.wake();
                    }
                    return Err(Error::ChannelClosed);
                }
                _ => self.dispatch(pkt).await?,
            }
        }
    }

    fn channel_ids(&self, ch: ChannelId) -> Result<(u32, u32), Error<<RH as ErrorType>::Error>> {
        let chs = self.shared.lock_channels();
        channel_ids_of(&*chs, ch)
    }

    async fn dispatch(&mut self, pkt: Packet) -> Result<(), Error<<RH as ErrorType>::Error>> {
        let outcome = {
            let mut chs = self.shared.lock_channels();
            dispatch_packet(&mut *chs, &pkt, self.shared.delayed_ack)?
        };

        match outcome {
            DispatchOutcome::AckWrite {
                local_id,
                remote_id,
                len,
            } => {
                let mut wh = self.shared.write_half.lock().await;
                send_okay_to(&mut *wh, self.shared.delayed_ack, local_id, remote_id, len).await?;
            }
            DispatchOutcome::SlotUpdated { idx } => {
                self.shared.signals[idx].wake();
            }
            DispatchOutcome::Unmatched => {}
        }
        Ok(())
    }
}

/// Write half of a split [`Connection`](crate::Connection).
///
/// Cheaply cloneable (an `Arc` bump). Methods take `&self`, so a single
/// `Writer` can be shared across threads with no additional wrapping.
pub struct Writer<
    WH,
    const MAX_CHANNELS: usize = DEFAULT_MAX_CHANNELS,
    const MAX_PROPERTIES: usize = DEFAULT_MAX_PROPERTIES,
    const MAX_FEATURES: usize = DEFAULT_MAX_FEATURES,
> where
    WH: Write,
{
    shared: Arc<Shared<WH, MAX_CHANNELS, MAX_PROPERTIES, MAX_FEATURES>>,
}

impl<WH, const MC: usize, const MP: usize, const MF: usize> Clone for Writer<WH, MC, MP, MF>
where
    WH: Write,
{
    fn clone(&self) -> Self {
        Self {
            shared: Arc::clone(&self.shared),
        }
    }
}

impl<WH, const MC: usize, const MP: usize, const MF: usize> Writer<WH, MC, MP, MF>
where
    WH: Write,
{
    pub(crate) fn new(shared: Arc<Shared<WH, MC, MP, MF>>) -> Self {
        Self { shared }
    }

    /// Negotiated max payload (bytes).
    pub fn max_payload(&self) -> u32 {
        self.shared.max_payload
    }

    /// Whether delayed-ACK flow control was negotiated.
    pub fn delayed_ack(&self) -> bool {
        self.shared.delayed_ack
    }

    /// Raw device banner bytes from the CNXN handshake.
    ///
    /// Lock-free connection metadata — available even while the
    /// [`Reader`] is blocked in a read on another thread.
    pub fn device_banner(&self) -> Option<&[u8]> {
        self.shared.device_banner.as_ref().map(|b| b.raw())
    }

    /// Parsed device banner from the CNXN handshake.
    ///
    /// Lock-free connection metadata — available even while the
    /// [`Reader`] is blocked in a read on another thread.
    pub fn device_banner_parsed(&self) -> Option<&DeviceBanner<MP, MF>> {
        self.shared.device_banner.as_ref()
    }

    /// Write `data` to the given channel.
    ///
    /// Splits `data` into chunks bounded by `max_payload` and the
    /// currently-granted send budget. Cancellation-safe: if the future
    /// is dropped, any reserved-but-unsent credit is refunded.
    /// Concurrent writers on the same channel never consume the same
    /// credit.
    pub async fn write_channel(
        &self,
        ch: ChannelId,
        data: &[u8],
    ) -> Result<(), Error<<WH as ErrorType>::Error>> {
        if data.is_empty() {
            return Ok(());
        }
        let max = (self.shared.max_payload as usize).max(1);

        let mut offset = 0;
        while offset < data.len() {
            let want = (data.len() - offset).min(max);
            let n = self.acquire_credit(ch, want).await?;
            let mut guard = CreditGuard::new(&self.shared, ch, n);

            let (local_id, remote_id) = self.channel_ids(ch)?;
            let chunk = &data[offset..offset + n];

            {
                let mut wh = self.shared.write_half.lock().await;
                send_raw(&mut *wh, Command::Write, local_id, remote_id, chunk).await?;
            }
            guard.commit();
            offset += n;
        }
        Ok(())
    }

    /// Send CLSE and release the channel slot. Any cloned `Writer`
    /// parked on this channel observes `ChannelClosed` and unblocks.
    ///
    /// A concurrent [`Reader::read_channel`] on the same channel is
    /// not woken directly — see the module-level note on close ↔ read
    /// coordination.
    pub async fn close_channel(
        &self,
        ch: ChannelId,
    ) -> Result<(), Error<<WH as ErrorType>::Error>> {
        let (local_id, remote_id) = self.channel_ids(ch)?;
        {
            let mut wh = self.shared.write_half.lock().await;
            send_pkt(&mut *wh, &Packet::close(local_id, remote_id)).await?;
        }
        {
            let mut chs = self.shared.lock_channels();
            if let Some(slot) = chs.get_mut(ch.slot) {
                if slot.as_ref().is_some_and(|s| s.local_id == ch.local_id) {
                    *slot = None;
                }
            }
        }
        if let Some(signal) = self.shared.signals.get(ch.slot) {
            signal.wake();
        }
        Ok(())
    }

    fn channel_ids(&self, ch: ChannelId) -> Result<(u32, u32), Error<<WH as ErrorType>::Error>> {
        let chs = self.shared.lock_channels();
        channel_ids_of(&*chs, ch)
    }

    async fn acquire_credit(
        &self,
        ch: ChannelId,
        want: usize,
    ) -> Result<usize, Error<<WH as ErrorType>::Error>> {
        let Some(signal) = self.shared.signals.get(ch.slot) else {
            return Err(Error::ChannelClosed);
        };

        loop {
            let listener = signal.listen();
            if let Some(result) = self.try_reserve(ch, want) {
                return result;
            }
            listener.await;
        }
    }

    fn try_reserve(
        &self,
        ch: ChannelId,
        want: usize,
    ) -> Option<Result<usize, Error<<WH as ErrorType>::Error>>> {
        let mut chs = self.shared.lock_channels();
        let Some(slot) = slot_for_mut(&mut *chs, ch) else {
            return Some(Err(Error::ChannelClosed));
        };
        if slot.is_closed() {
            return Some(Err(Error::ChannelClosed));
        }
        slot.try_reserve_send(want, self.shared.delayed_ack).map(Ok)
    }
}