libadb 0.2.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
//! A transport that answers synchronously, so a future can be driven by
//! hand and dropped at an exact point — which a socket-backed test
//! cannot do.

use alloc::collections::VecDeque;
use alloc::vec::Vec;
use core::future::Future;
use core::pin::pin;
use core::task::{Context, Poll, Waker};

use bytes::BytesMut;

use crate::base::channel::ChannelId;
use crate::base::connection::Connection;
use crate::base::protocol::command::Command;
use crate::base::protocol::Packet;
use crate::base::protocol::{command, Checksum};

#[derive(Debug, PartialEq, Eq)]
pub struct MockError;

impl core::fmt::Display for MockError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("mock transport error")
    }
}

impl embedded_io::Error for MockError {
    fn kind(&self) -> embedded_io::ErrorKind {
        embedded_io::ErrorKind::Other
    }
}

/// A transport whose every operation completes at once, except for one
/// write that never does.
pub(crate) struct Mock {
    inbound: VecDeque<u8>,
    writes: Vec<Vec<u8>>,
    stall_write: Option<usize>,
    /// Reads that report `Pending` before any data comes back.
    slow_reads: usize,
    cancel_safe: bool,
}

impl Mock {
    pub(crate) fn new() -> Self {
        Self {
            inbound: VecDeque::new(),
            writes: Vec::new(),
            stall_write: None,
            slow_reads: 0,
            cancel_safe: true,
        }
    }

    pub(crate) fn feed(&mut self, pkt: &Packet) -> &mut Self {
        let mut buf = BytesMut::new();
        pkt.encode(&mut buf, Checksum::Compute).unwrap();
        self.inbound.extend(buf.iter().copied());
        self
    }

    /// Park the next `n` reads once each before answering, so an
    /// interrupt can become ready while a read is in flight.
    pub(crate) fn slow_reads(&mut self, n: usize) -> &mut Self {
        self.slow_reads = n;
        self
    }

    /// Claim that dropping a read loses whatever the peer already sent,
    /// the way a USB bulk transfer does.
    pub(crate) fn loses_cancelled_reads(&mut self) -> &mut Self {
        self.cancel_safe = false;
        self
    }

    /// Stall the write with this index, counting from the first one the
    /// transport ever sees.
    pub(crate) fn stall_write(&mut self, index: usize) -> &mut Self {
        self.stall_write = Some(index);
        self
    }
}

impl embedded_io::ErrorType for Mock {
    type Error = MockError;
}

impl Mock {
    fn pull(&mut self, buf: &mut [u8]) -> usize {
        let n = buf.len().min(self.inbound.len());
        for slot in buf.iter_mut().take(n) {
            *slot = self.inbound.pop_front().unwrap();
        }
        n
    }

    fn stalls_now(&self) -> bool {
        self.stall_write == Some(self.writes.len())
    }

    fn push(&mut self, buf: &[u8]) -> usize {
        self.writes.push(buf.to_vec());
        buf.len()
    }
}

impl embedded_io_async::Read for Mock {
    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, MockError> {
        if self.slow_reads > 0 {
            self.slow_reads -= 1;
            park_once().await;
        }
        Ok(self.pull(buf))
    }
}

impl crate::transport::ReadCancelSafety for Mock {
    fn read_cancel_safe(&self) -> bool {
        self.cancel_safe
    }
}

/// Report `Pending` once, waking immediately, then complete.
async fn park_once() {
    let mut done = false;
    core::future::poll_fn(move |cx| {
        if done {
            core::task::Poll::Ready(())
        } else {
            done = true;
            cx.waker().wake_by_ref();
            core::task::Poll::Pending
        }
    })
    .await
}

impl embedded_io_async::Write for Mock {
    async fn write(&mut self, buf: &[u8]) -> Result<usize, MockError> {
        if self.stalls_now() {
            core::future::pending::<()>().await;
        }
        Ok(self.push(buf))
    }

    async fn flush(&mut self) -> Result<(), MockError> {
        Ok(())
    }
}

/// The same mock behind a shared handle, so both halves of a split
/// connection talk to one transport.
#[cfg(feature = "split")]
#[derive(Clone)]
pub(crate) struct SharedMock(alloc::sync::Arc<std::sync::Mutex<Mock>>);

#[cfg(feature = "split")]
impl SharedMock {
    /// Acknowledgements the split halves sent for `local_id`.
    pub(crate) fn acks_for(&self, local_id: u32) -> Vec<u32> {
        self.lock().acks_for(local_id)
    }

    /// Everything the split halves sent, in wire order.
    pub(crate) fn sent(&self) -> Vec<(Command, u32, u32, Vec<u8>)> {
        self.lock().sent()
    }

    fn new(mock: Mock) -> Self {
        Self(alloc::sync::Arc::new(std::sync::Mutex::new(mock)))
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, Mock> {
        self.0.lock().unwrap_or_else(|p| p.into_inner())
    }
}

#[cfg(feature = "split")]
impl embedded_io::ErrorType for SharedMock {
    type Error = MockError;
}

#[cfg(feature = "split")]
impl embedded_io_async::Read for SharedMock {
    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, MockError> {
        Ok(self.lock().pull(buf))
    }
}

#[cfg(feature = "split")]
impl embedded_io_async::Write for SharedMock {
    async fn write(&mut self, buf: &[u8]) -> Result<usize, MockError> {
        // The lock is released before the await: a stalled write must
        // not hold the other half out.
        if self.lock().stalls_now() {
            core::future::pending::<()>().await;
        }
        Ok(self.lock().push(buf))
    }

    async fn flush(&mut self) -> Result<(), MockError> {
        Ok(())
    }
}

#[cfg(feature = "split")]
impl crate::transport::Splittable for SharedMock {
    type ReadHalf = SharedMock;
    type WriteHalf = SharedMock;

    fn split(self) -> Result<(Self::ReadHalf, Self::WriteHalf), MockError> {
        Ok((self.clone(), self))
    }
}

impl Mock {
    /// Packets handed to the transport, rejoined from the header and
    /// payload writes each one takes.
    pub(crate) fn sent(&self) -> Vec<(Command, u32, u32, Vec<u8>)> {
        let mut stream: Vec<u8> = Vec::new();
        for w in &self.writes {
            stream.extend_from_slice(w);
        }
        let mut out = Vec::new();
        let mut pos = 0;
        while pos + 24 <= stream.len() {
            let word = |at: usize| {
                u32::from_le_bytes([stream[at], stream[at + 1], stream[at + 2], stream[at + 3]])
            };
            let command = Command::try_from(word(pos)).expect("valid command");
            let (arg0, arg1) = (word(pos + 4), word(pos + 8));
            let len = word(pos + 12) as usize;
            pos += 24;
            let payload = stream[pos..pos + len].to_vec();
            pos += len;
            out.push((command, arg0, arg1, payload));
        }
        out
    }

    /// Acknowledgements sent for `local_id`, as byte counts (zero for a
    /// plain OKAY).
    pub(crate) fn acks_for(&self, local_id: u32) -> Vec<u32> {
        self.sent()
            .into_iter()
            .filter(|(cmd, arg0, _, _)| *cmd == Command::Ready && *arg0 == local_id)
            .map(|(_, _, _, payload)| {
                if payload.len() >= 4 {
                    u32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]])
                } else {
                    0
                }
            })
            .collect()
    }
}

/// Drive a future that only ever awaits the mock, and panic if it parks.
pub(crate) fn now<F: Future>(fut: F) -> F::Output {
    let mut fut = pin!(fut);
    let mut cx = Context::from_waker(Waker::noop());
    for _ in 0..64 {
        if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
            return v;
        }
    }
    panic!("future never finished against the mock transport");
}

/// Poll `fut` a few times, then drop it where it stands.
pub(crate) fn abandon<F: Future>(fut: F) {
    let mut fut = pin!(fut);
    let mut cx = Context::from_waker(Waker::noop());
    for _ in 0..8 {
        if fut.as_mut().poll(&mut cx).is_ready() {
            panic!("future finished; it was supposed to stall");
        }
    }
}

pub(crate) struct NoAuth;

impl crate::auth::Authenticator for NoAuth {
    type Error = ();

    async fn sign(&mut self, _token: &[u8]) -> Result<Vec<u8>, ()> {
        Err(())
    }

    fn public_key(&self) -> &[u8] {
        b"\0"
    }
}

pub(crate) fn cnxn() -> Packet {
    Packet::new(
        Command::Connect,
        command::ADB_VERSION,
        256 * 1024,
        b"device::features=shell_v2".to_vec(),
    )
}

pub(crate) fn okay(local_id: u32) -> Packet {
    Packet::new(Command::Ready, 42, local_id, Vec::new())
}

/// A connected `Connection` with one open channel, over a mock that
/// stalls on the write with the given index (counted after the two
/// writes the handshake and OPEN each take).
pub(crate) fn connected_with_channel(stall: Option<usize>) -> (Connection<Mock>, ChannelId) {
    let mut mock = Mock::new();
    mock.feed(&cnxn())
        .feed(&okay(1))
        .feed(&okay(1))
        .feed(&okay(1));
    // Handshake writes the CNXN header and banner; OPEN writes its own
    // header and destination.
    if let Some(index) = stall {
        mock.stall_write(4 + index);
    }
    let mut conn = now(Connection::<_>::connect(mock, NoAuth, &[])).unwrap();
    let ch = now(conn.open_channel(b"shell:\0")).unwrap();
    (conn, ch)
}

/// A split connection with one open channel, over a mock that stalls on
/// the write with the given index (counted from the first write after
/// the handshake and OPEN).
#[cfg(feature = "split")]
#[allow(clippy::type_complexity)]
pub(crate) fn split_with_channel(
    stall: Option<usize>,
) -> (
    crate::split::Reader<SharedMock, SharedMock>,
    crate::split::Writer<SharedMock>,
    ChannelId,
) {
    let mut mock = Mock::new();
    mock.feed(&cnxn()).feed(&okay(1)).feed(&okay(1));
    if let Some(index) = stall {
        mock.stall_write(4 + index);
    }
    let conn = now(Connection::<_>::connect(SharedMock::new(mock), NoAuth, &[])).unwrap();
    let (mut reader, writer) = conn.split().unwrap();
    let ch = now(reader.open_channel(b"shell:\0")).unwrap();
    (reader, writer, ch)
}

/// A split connection with delayed-ack on, one channel whose OPEN
/// grants `budget` bytes, and `extra` packets queued behind it — the
/// grants the reader dispatches when polled.
#[cfg(feature = "split")]
#[allow(clippy::type_complexity)]
pub(crate) fn split_one_channel_delayed_ack(
    budget: u32,
    extra: &[Packet],
) -> (
    crate::split::Reader<SharedMock, SharedMock>,
    crate::split::Writer<SharedMock>,
    ChannelId,
    SharedMock,
) {
    let mut mock = Mock::new();
    mock.feed(&cnxn_with("shell_v2,delayed_ack"))
        .feed(&okay_with_budget(1, budget));
    for pkt in extra {
        mock.feed(pkt);
    }
    let transport = SharedMock::new(mock);
    let seen = transport.clone();
    let conn = now(Connection::<_>::connect_with_raw_banner(
        transport,
        NoAuth,
        b"host::features=shell_v2,delayed_ack",
    ))
    .unwrap();
    let (mut reader, writer) = conn.split().unwrap();
    let ch = now(reader.open_channel(b"shell:\0")).unwrap();
    (reader, writer, ch, seen)
}

pub(crate) fn cnxn_with(features: &str) -> Packet {
    Packet::new(
        Command::Connect,
        command::ADB_VERSION,
        256 * 1024,
        alloc::format!("device::features={features}").into_bytes(),
    )
}

/// OKAY answering an OPEN, carrying the initial send budget the device
/// grants us when delayed-ack is on.
pub(crate) fn okay_with_budget(local_id: u32, budget: u32) -> Packet {
    Packet::new(Command::Ready, 42, local_id, budget.to_le_bytes().to_vec())
}

pub(crate) fn wrte(local_id: u32, payload: &[u8]) -> Packet {
    Packet::new(Command::Write, 42, local_id, payload.to_vec())
}

/// A connection with one open channel and one WRTE waiting to be read,
/// with the transport configured after the handshake so that its
/// slowness only affects the read under test.
pub(crate) fn connected_for_select(
    configure: impl FnOnce(&mut Mock),
) -> (Connection<Mock>, ChannelId) {
    let mut mock = Mock::new();
    mock.feed(&cnxn()).feed(&okay(1));
    let mut conn = now(Connection::<_>::connect(mock, NoAuth, &[])).unwrap();
    let ch = now(conn.open_channel(b"shell:\0")).unwrap();
    let transport = conn.transport_mut();
    transport.feed(&wrte(1, b"hello"));
    configure(transport);
    (conn, ch)
}

/// A delayed-ack connection with two open channels, the second of which
/// nobody has read yet. `pushes` are queued for the transport to hand
/// over in order.
pub(crate) fn two_channels_delayed_ack(
    budget: u32,
    pushes: &[Packet],
) -> (Connection<Mock>, ChannelId, ChannelId) {
    let mut mock = Mock::new();
    mock.feed(&cnxn_with("shell_v2,delayed_ack"))
        .feed(&okay_with_budget(1, budget))
        .feed(&okay_with_budget(2, budget));
    for pkt in pushes {
        mock.feed(pkt);
    }
    let mut conn = now(Connection::<_>::connect_with_raw_banner(
        mock,
        NoAuth,
        b"host::features=shell_v2,delayed_ack",
    ))
    .unwrap();
    let a = now(conn.open_channel(b"shell:a\0")).unwrap();
    let b = now(conn.open_channel(b"shell:b\0")).unwrap();
    (conn, a, b)
}

/// A connection without delayed-ack, two open channels, and a config
/// whose watermark the caller picks.
pub(crate) fn two_channels_classic(
    config: crate::base::connection::ConnectionConfig,
    pushes: &[Packet],
) -> (Connection<Mock>, ChannelId, ChannelId) {
    let mut mock = Mock::new();
    mock.feed(&cnxn_with("shell_v2"))
        .feed(&okay(1))
        .feed(&okay(2));
    for pkt in pushes {
        mock.feed(pkt);
    }
    let mut conn = now(Connection::<_>::connect_with_raw_banner_and_config(
        mock,
        NoAuth,
        b"host::features=shell_v2",
        config,
    ))
    .unwrap();
    let a = now(conn.open_channel(b"shell:a\0")).unwrap();
    let b = now(conn.open_channel(b"shell:b\0")).unwrap();
    (conn, a, b)
}

/// A split, delayed-ack connection with two channels; the returned
/// handle sees everything the halves write.
#[cfg(feature = "split")]
#[allow(clippy::type_complexity)]
pub(crate) fn split_two_channels_delayed_ack(
    pushes: &[Packet],
) -> (
    crate::split::Reader<SharedMock, SharedMock>,
    ChannelId,
    ChannelId,
    SharedMock,
) {
    let mut mock = Mock::new();
    mock.feed(&cnxn_with("shell_v2,delayed_ack"))
        .feed(&okay_with_budget(1, 64 * 1024))
        .feed(&okay_with_budget(2, 64 * 1024));
    for pkt in pushes {
        mock.feed(pkt);
    }
    let transport = SharedMock::new(mock);
    let seen = transport.clone();
    let conn = now(Connection::<_>::connect_with_raw_banner(
        transport,
        NoAuth,
        b"host::features=shell_v2,delayed_ack",
    ))
    .unwrap();
    let (mut reader, _writer) = conn.split().unwrap();
    let a = now(reader.open_channel(b"shell:a\0")).unwrap();
    let b = now(reader.open_channel(b"shell:b\0")).unwrap();
    (reader, a, b, seen)
}