libadb 0.8.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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! What a dropped write leaves behind on the wire.

use alloc::vec;
use core::future::Future;
use core::task::Poll;

use super::*;
use crate::base::error::{AuthError, ProtocolError};
use crate::base::mock::{
    abandon, cnxn, connected_for_select, connected_with_channel, now, stls, two_channels_classic,
    two_channels_delayed_ack, wrte, Mock, NoAuth, Signs, Withholds,
};
use crate::base::protocol::command::{Command, AUTH_RSAPUBLICKEY, AUTH_SIGNATURE, AUTH_TOKEN};
use crate::base::protocol::Packet;

#[test]
fn a_write_cancelled_between_header_and_payload_desyncs_the_connection() {
    // Index 1: the header lands, the payload write is the one that hangs.
    let (mut conn, ch) = connected_with_channel(Some(1));
    abandon(conn.write_channel(ch, b"payload-that-never-made-it"));

    let err = now(conn.write_channel(ch, b"more")).unwrap_err();
    assert!(
        matches!(err, Error::Desynchronized),
        "expected Desynchronized, got {err:?}"
    );
}

#[test]
fn a_desynchronized_connection_refuses_every_operation() {
    let (mut conn, ch) = connected_with_channel(Some(1));
    abandon(conn.write_channel(ch, b"payload-that-never-made-it"));

    assert!(matches!(
        now(conn.open_channel(b"shell:\0")),
        Err(Error::Desynchronized)
    ));
    let mut buf = [0u8; 16];
    assert!(matches!(
        now(conn.read_channel(ch, &mut buf)),
        Err(Error::Desynchronized)
    ));
    assert!(matches!(
        now(conn.close_channel(ch)),
        Err(Error::Desynchronized)
    ));
    assert!(matches!(
        now(conn.select_channel(ch, &mut buf, core::future::pending::<()>())),
        Err(Error::Desynchronized)
    ));
}

#[test]
fn a_write_that_completes_leaves_the_connection_usable() {
    let (mut conn, ch) = connected_with_channel(None);
    now(conn.write_channel(ch, b"payload")).unwrap();
    now(conn.write_channel(ch, b"another")).unwrap();
}

#[test]
fn a_write_cancelled_before_the_header_is_treated_as_broken_too() {
    // Index 0: the write was polled but never returned, so we cannot
    // tell whether the transport already took bytes from us. The
    // connection is written off rather than guessed about.
    let (mut conn, ch) = connected_with_channel(Some(0));
    abandon(conn.write_channel(ch, b"payload"));

    let err = now(conn.write_channel(ch, b"more")).unwrap_err();
    assert!(
        matches!(err, Error::Desynchronized),
        "expected Desynchronized, got {err:?}"
    );
}

/// An interrupt that only becomes ready on its `n`-th poll, so it can
/// win the race with a read that is already in flight.
fn ready_on_poll(n: usize) -> impl Future<Output = &'static str> {
    let mut polls = 0;
    core::future::poll_fn(move |cx| {
        polls += 1;
        if polls >= n {
            Poll::Ready("interrupted")
        } else {
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    })
}

#[test]
fn a_transport_that_loses_cancelled_reads_finishes_the_read_first() {
    let (mut conn, ch) = connected_for_select(|m| {
        m.loses_cancelled_reads().slow_reads(1);
    });

    // The interrupt comes due while the read is in flight. Dropping the
    // read here would cost us the bytes the device already sent, so the
    // read has to finish and the data comes back instead.
    let out = now(conn.select_channel(ch, &mut [0u8; 32], ready_on_poll(2))).unwrap();
    assert!(
        matches!(out, SelectResult::Data(5)),
        "expected the payload, got {out:?}"
    );
}

#[test]
fn a_transport_that_keeps_cancelled_reads_lets_the_interrupt_win() {
    let (mut conn, ch) = connected_for_select(|m| {
        m.slow_reads(1);
    });

    let out = now(conn.select_channel(ch, &mut [0u8; 32], ready_on_poll(2))).unwrap();
    assert!(
        matches!(out, SelectResult::Interrupted("interrupted")),
        "expected the interrupt, got {out:?}"
    );
}

#[test]
fn an_interrupt_that_is_already_due_wins_on_either_transport() {
    for lossy in [false, true] {
        let (mut conn, ch) = connected_for_select(|m| {
            if lossy {
                m.loses_cancelled_reads();
            }
        });
        let out = now(conn.select_channel(ch, &mut [0u8; 32], ready_on_poll(1))).unwrap();
        assert!(
            matches!(out, SelectResult::Interrupted("interrupted")),
            "lossy={lossy}: expected the interrupt, got {out:?}"
        );
    }
}

// ---------------------------------------------------------------------------
// Acknowledging what was consumed, not what arrived
// ---------------------------------------------------------------------------

#[test]
fn a_write_nobody_has_read_is_not_acknowledged() {
    // The device writes to channel B, then to A. Reading A dispatches
    // B's packet into its buffer along the way.
    let (mut conn, a, _b) =
        two_channels_delayed_ack(64 * 1024, &[wrte(2, b"for-b"), wrte(1, b"for-a")]);

    let mut buf = [0u8; 32];
    let n = now(conn.read_channel(a, &mut buf)).unwrap();
    assert_eq!(&buf[..n], b"for-a");

    assert_eq!(
        conn.transport().acks_for(1),
        vec![5],
        "the channel that was read is acknowledged"
    );
    assert!(
        conn.transport().acks_for(2).is_empty(),
        "the channel nobody read must not have its credit returned"
    );
}

#[test]
fn reading_a_buffered_write_acknowledges_it() {
    let (mut conn, a, b) =
        two_channels_delayed_ack(64 * 1024, &[wrte(2, b"for-b"), wrte(1, b"for-a")]);

    let mut buf = [0u8; 32];
    now(conn.read_channel(a, &mut buf)).unwrap();
    let n = now(conn.read_channel(b, &mut buf)).unwrap();
    assert_eq!(&buf[..n], b"for-b");

    assert_eq!(
        conn.transport().acks_for(2),
        vec![5],
        "credit is returned once the application takes the bytes"
    );
}

#[test]
fn a_partial_read_acknowledges_only_what_was_taken() {
    let (mut conn, a, _b) = two_channels_delayed_ack(64 * 1024, &[wrte(1, b"0123456789")]);

    let mut buf = [0u8; 4];
    let n = now(conn.read_channel(a, &mut buf)).unwrap();
    assert_eq!(n, 4);
    assert_eq!(conn.transport().acks_for(1), vec![4]);

    let n = now(conn.read_channel(a, &mut buf)).unwrap();
    assert_eq!(n, 4);
    assert_eq!(conn.transport().acks_for(1), vec![4, 4]);
}

#[test]
fn a_classic_channel_is_acknowledged_until_the_watermark() {
    // Watermark lands at 1 KiB: max_payload and the advertised budget
    // are both 1 KiB, and the hard cap is above both.
    let config = ConnectionConfig::new()
        .with_max_payload(1024)
        .with_initial_ack_bytes(1024)
        .with_max_rx_per_channel(8 * 1024);
    assert_eq!(config.rx_watermark(), 1024);

    let (mut conn, a, _b) = two_channels_classic(
        config,
        &[
            wrte(2, &[b'x'; 700]),
            wrte(2, &[b'y'; 700]),
            wrte(1, b"done"),
        ],
    );

    let mut buf = [0u8; 16];
    now(conn.read_channel(a, &mut buf)).unwrap();

    assert_eq!(
        conn.transport().acks_for(2).len(),
        1,
        "the first write fits under the watermark and is acknowledged; \
         the second takes the channel over it and waits for a reader"
    );
}

#[test]
fn reading_past_the_watermark_releases_the_held_ack() {
    let config = ConnectionConfig::new()
        .with_max_payload(1024)
        .with_initial_ack_bytes(1024)
        .with_max_rx_per_channel(8 * 1024);
    let (mut conn, a, b) = two_channels_classic(
        config,
        &[
            wrte(2, &[b'x'; 700]),
            wrte(2, &[b'y'; 700]),
            wrte(1, b"done"),
        ],
    );

    let mut buf = [0u8; 16];
    now(conn.read_channel(a, &mut buf)).unwrap();
    let mut big = [0u8; 1400];
    now(conn.read_channel(b, &mut big)).unwrap();

    assert_eq!(
        conn.transport().acks_for(2).len(),
        2,
        "draining the channel lets the held acknowledgement out"
    );
}

mod incoming {
    use super::*;
    use crate::base::mock::{cnxn_with, now, wrte, Mock, NoAuth};

    fn connected(host: &'static [u8], device: &str) -> Connection<Mock> {
        let mut mock = Mock::new();
        mock.feed(&cnxn_with(device));
        now(Connection::<_>::connect_with_raw_banner(mock, NoAuth, host)).unwrap()
    }

    fn open_pkt(remote_id: u32, credit: u32, dest: &[u8]) -> Packet {
        Packet::new(Command::Open, remote_id, credit, dest.to_vec())
    }

    #[test]
    fn a_device_open_is_queued_accepted_and_serves_data() {
        let mut conn = connected(
            b"host::features=shell_v2,delayed_ack",
            "shell_v2,delayed_ack",
        );
        conn.transport.feed(&open_pkt(77, 4096, b"tcp:9090\0"));

        let incoming = now(conn.accept_incoming()).unwrap();
        assert_eq!(incoming.destination(), b"tcp:9090\0");
        let ch = now(incoming.accept()).unwrap();

        // READY named our id and carried our receive credit.
        let (cmd, local, remote, payload) = conn.transport.sent().last().unwrap().clone();
        assert_eq!(cmd, Command::Ready);
        assert_eq!(remote, 77);
        assert_ne!(local, 0);
        assert_eq!(payload.len(), 4);

        // Their WRTE reaches the accepted channel...
        conn.transport.feed(&wrte(local, b"ping"));
        let mut buf = [0u8; 16];
        let n = now(conn.read_channel(ch, &mut buf)).unwrap();
        assert_eq!(&buf[..n], b"ping");

        // ...and our write spends the budget the OPEN granted.
        now(conn.write_channel(ch, b"pong")).unwrap();
        let (cmd, l, r, payload) = conn.transport.sent().last().unwrap().clone();
        assert_eq!(cmd, Command::Write);
        assert_eq!((l, r), (local, 77));
        assert_eq!(payload, b"pong");
    }

    #[test]
    fn a_rejected_open_answers_clse_with_no_local_id() {
        let mut conn = connected(b"host::features=shell_v2", "shell_v2");
        conn.transport.feed(&open_pkt(88, 0, b"tcp:1\0"));

        let incoming = now(conn.accept_incoming()).unwrap();
        now(incoming.reject()).unwrap();

        let (cmd, local, remote, _) = conn.transport.sent().last().unwrap().clone();
        assert_eq!(cmd, Command::Close);
        assert_eq!((local, remote), (0, 88));
    }

    #[test]
    fn a_dropped_verdict_returns_the_request_to_the_queue() {
        let mut conn = connected(b"host::features=shell_v2", "shell_v2");
        conn.transport.feed(&open_pkt(99, 0, b"tcp:2\0"));

        let incoming = now(conn.accept_incoming()).unwrap();
        drop(incoming);

        let incoming = conn.try_accept_incoming().expect("request lost on drop");
        assert_eq!(incoming.destination(), b"tcp:2\0");
    }

    #[test]
    fn a_full_queue_refuses_new_opens_on_arrival() {
        let mut mock = Mock::new();
        mock.feed(&cnxn_with("shell_v2"));
        let mut conn = now(Connection::<_, 2, 64, 24>::connect_with_raw_banner(
            mock,
            NoAuth,
            b"host::features=shell_v2",
        ))
        .unwrap();

        now(conn.dispatch(open_pkt(1, 0, b"tcp:1\0"))).unwrap();
        now(conn.dispatch(open_pkt(2, 0, b"tcp:2\0"))).unwrap();
        now(conn.dispatch(open_pkt(3, 0, b"tcp:3\0"))).unwrap();

        let (cmd, local, remote, _) = conn.transport.sent().last().unwrap().clone();
        assert_eq!(cmd, Command::Close, "the third OPEN must be refused");
        assert_eq!((local, remote), (0, 3));

        // Undecided handles bounce back on drop, so resolve them.
        now(conn.try_accept_incoming().unwrap().reject()).unwrap();
        now(conn.try_accept_incoming().unwrap().reject()).unwrap();
        assert!(conn.try_accept_incoming().is_none());
    }

    #[test]
    fn a_device_cancel_removes_the_pending_request() {
        let mut conn = connected(b"host::features=shell_v2", "shell_v2");
        now(conn.dispatch(open_pkt(55, 0, b"tcp:5\0"))).unwrap();
        now(conn.dispatch(Packet::close(55, 0))).unwrap();
        assert!(conn.try_accept_incoming().is_none());
    }

    #[test]
    fn a_withdrawal_racing_the_accept_closes_the_slot() {
        // The zero-local-id CLSE was buffered behind the OPEN: by the
        // time it is dispatched, the request is an accepted slot, not
        // a queued one — it must close like any remote CLSE.
        let mut conn = connected(b"host::features=shell_v2", "shell_v2");
        now(conn.dispatch(open_pkt(90, 0, b"tcp:9\0"))).unwrap();
        let ch = now(conn.try_accept_incoming().unwrap().accept()).unwrap();

        now(conn.dispatch(Packet::close(90, 0))).unwrap();

        let mut buf = [0u8; 8];
        let err = now(conn.read_channel(ch, &mut buf)).unwrap_err();
        assert!(
            matches!(err, Error::ChannelClosed),
            "expected ChannelClosed, got {err:?}"
        );
    }

    #[test]
    fn a_cancelled_accept_frees_the_slot_and_requeues() {
        use core::task::{Context, Poll, Waker};

        // A transport whose write parks forever: accept reserves a slot,
        // sends READY, and hangs — the exact window a cancel lands in.
        let mut mock = Mock::new();
        mock.feed(&cnxn_with("shell_v2"));
        // CNXN writes header+payload (two calls); the empty-payload READY
        // that accept sends is the very next write.
        mock.stall_write(2);
        let mut conn = now(Connection::<_>::connect_with_raw_banner(
            mock,
            NoAuth,
            b"host::features=shell_v2",
        ))
        .unwrap();

        now(conn.dispatch(open_pkt(66, 0, b"tcp:6\0"))).unwrap();
        {
            let incoming = conn.try_accept_incoming().unwrap();
            let mut fut = core::pin::pin!(incoming.accept());
            let mut cx = Context::from_waker(Waker::noop());
            // Poll once: the slot is reserved, the READY write stalls.
            assert!(matches!(fut.as_mut().poll(&mut cx), Poll::Pending));
            // Drop mid-flight — cancellation.
        }

        // The reserved slot came back: the table is empty again.
        assert!(
            conn.channels.iter().all(Option::is_none),
            "the reserved slot leaked past the cancel"
        );
        // The request came back too: it is acceptable again.
        let again = conn.try_accept_incoming().expect("request lost on cancel");
        assert_eq!(again.destination(), b"tcp:6\0");
    }

    #[test]
    fn the_ready_credit_is_clamped_to_the_receive_cap() {
        let mut mock = Mock::new();
        mock.feed(&cnxn_with("shell_v2,delayed_ack"));
        let config = ConnectionConfig::new()
            .with_initial_ack_bytes(32 * 1024 * 1024)
            .with_max_rx_per_channel(1024 * 1024);
        let mut conn = now(Connection::<_>::connect_with_raw_banner_and_config(
            mock,
            NoAuth,
            b"host::features=shell_v2,delayed_ack",
            config,
        ))
        .unwrap();

        now(conn.dispatch(open_pkt(7, 0, b"tcp:7\0"))).unwrap();
        let incoming = conn.try_accept_incoming().unwrap();
        now(incoming.accept()).unwrap();

        let (cmd, _, _, payload) = conn.transport.sent().last().unwrap().clone();
        assert_eq!(cmd, Command::Ready);
        assert_eq!(payload, (1024u32 * 1024).to_le_bytes());
    }

    #[test]
    fn accept_with_no_free_slot_refuses_and_reports() {
        let mut mock = Mock::new();
        mock.feed(&cnxn_with("shell_v2"));
        mock.feed(&crate::base::mock::okay(1));
        let mut conn = now(Connection::<_, 1, 64, 24>::connect_with_raw_banner(
            mock,
            NoAuth,
            b"host::features=shell_v2",
        ))
        .unwrap();
        let _busy = now(conn.open_channel(b"shell:\0")).unwrap();

        now(conn.dispatch(open_pkt(9, 0, b"tcp:9\0"))).unwrap();
        let incoming = conn.try_accept_incoming().unwrap();
        let err = now(incoming.accept()).unwrap_err();
        assert!(matches!(err, Error::NoFreeChannels), "got {err:?}");

        let (cmd, local, remote, _) = conn.transport.sent().last().unwrap().clone();
        assert_eq!(cmd, Command::Close);
        assert_eq!((local, remote), (0, 9));
    }
}

#[test]
fn a_device_that_answers_the_handshake_with_stls_says_it_wants_tls() {
    let mut mock = Mock::new();
    mock.feed(&stls());

    let Err(err) = now(Connection::<_>::connect(mock, NoAuth, &[])) else {
        panic!("expected the handshake to refuse a TLS-only device");
    };

    assert!(
        matches!(err, Error::Protocol(ProtocolError::TlsRequired)),
        "expected TlsRequired, got {err:?}"
    );
}

#[test]
fn an_auth_that_is_not_a_token_after_our_signature_is_a_rejection() {
    // The device answered the signature with AUTH again, but not with a
    // token. That is not a CNXN and must not be assembled into one: a
    // connection built from it would carry an AUTH payload as its
    // banner and believe itself authenticated.
    let mut mock = Mock::new();
    mock.feed(&Packet::new(Command::Auth, AUTH_TOKEN, 0, vec![0x5a; 20]));
    mock.feed(&Packet::new(Command::Auth, AUTH_SIGNATURE, 0, vec![]));

    let Err(err) = now(Connection::<_>::connect(mock, Signs, &[])) else {
        panic!("a stray AUTH must not become a connection");
    };

    assert!(
        matches!(err, Error::Auth(AuthError::Rejected)),
        "expected Rejected, got {err:?}"
    );
}

#[test]
fn a_withheld_key_ends_the_handshake_untrusted_before_it_reaches_the_device() {
    // The second token asks for the key. Sending it is what raises the
    // dialog on the device, so an authenticator that withholds it must
    // leave the signature as the last thing on the wire.
    let mut mock = Mock::new();
    mock.feed(&Packet::new(Command::Auth, AUTH_TOKEN, 0, vec![0x5a; 20]));
    mock.feed(&Packet::new(Command::Auth, AUTH_TOKEN, 0, vec![0x6b; 20]));

    let Err(err) = now(Connection::<_>::connect(&mut mock, Withholds, &[])) else {
        panic!("an untrusted key must not become a connection");
    };

    assert!(
        matches!(err, Error::Auth(AuthError::KeyNotTrusted)),
        "expected KeyNotTrusted, got {err:?}"
    );
    let sent = mock.sent();
    assert!(
        !sent
            .iter()
            .any(|(c, arg0, ..)| *c == Command::Auth && *arg0 == AUTH_RSAPUBLICKEY),
        "the key must not be offered, sent {sent:?}"
    );
    assert_eq!(
        sent.last().map(|(c, arg0, ..)| (*c, *arg0)),
        Some((Command::Auth, AUTH_SIGNATURE)),
        "the handshake must end on our signature"
    );
}

#[test]
fn a_trusted_key_connects_without_being_offered() {
    let mut mock = Mock::new();
    mock.feed(&Packet::new(Command::Auth, AUTH_TOKEN, 0, vec![0x5a; 20]));
    mock.feed(&cnxn());

    now(Connection::<_>::connect(mock, Withholds, &[]))
        .expect("a device that accepts the signature never asks for the key");
}

#[test]
fn a_borrowed_authenticator_withholds_its_key_as_the_owned_one_does() {
    let mut mock = Mock::new();
    mock.feed(&Packet::new(Command::Auth, AUTH_TOKEN, 0, vec![0x5a; 20]));
    mock.feed(&Packet::new(Command::Auth, AUTH_TOKEN, 0, vec![0x6b; 20]));
    let mut auth = Withholds;

    let Err(err) = now(Connection::<_>::connect(mock, &mut auth, &[])) else {
        panic!("an untrusted key must not become a connection");
    };

    assert!(
        matches!(err, Error::Auth(AuthError::KeyNotTrusted)),
        "expected KeyNotTrusted, got {err:?}"
    );
}

#[test]
fn a_large_packet_is_zeroed_once_while_select_reads_it() {
    // The read loop stages its own buffer, apart from `recv_pkt` (whose
    // twin test in wire.rs covers the handshake), and must zero it once
    // per packet, not again for each 16 KiB read that TLS hands over.
    // The bound allows the header and the MIN_READ that a first read is
    // padded to.
    let big = vec![0x5a; 256 * 1024];
    let (mut conn, ch) = connected_for_select(|mock| {
        mock.feed(&wrte(1, &big)).drips(16 * 1024);
    });
    let mut buf = vec![0u8; big.len()];
    let first = now(conn.select_channel(ch, &mut buf, core::future::pending::<()>())).unwrap();
    assert!(
        matches!(first, SelectResult::Data(5)),
        "the small WRTE first"
    );

    crate::base::wire::ZEROED.with(|zeroed| zeroed.set(0));
    let mut got = 0;
    while got < big.len() {
        match now(conn.select_channel(ch, &mut buf[got..], core::future::pending::<()>())).unwrap()
        {
            SelectResult::Data(n) => got += n,
            SelectResult::Interrupted(()) => unreachable!("the interrupt never fires"),
        }
    }

    assert_eq!(buf, big);
    let zeroed = crate::base::wire::ZEROED.with(|zeroed| zeroed.get());
    assert!(
        zeroed <= big.len() + 24 + crate::base::wire::MIN_READ,
        "zeroed {zeroed} bytes for a {}-byte payload",
        big.len()
    );
}

#[test]
fn a_handshake_packet_after_the_handshake_is_dropped_and_the_session_goes_on() {
    // Out of turn, so dropped like any packet nobody claims, with a line
    // in the log; the channel read behind it is none the worse.
    let (mut conn, ch) = connected_with_channel(None);
    conn.transport_mut()
        .feed(&Packet::new(
            Command::StartTls,
            crate::base::protocol::constant::STLS_VERSION,
            0,
            vec![],
        ))
        .feed(&Packet::new(
            Command::Connect,
            crate::base::protocol::command::ADB_VERSION,
            4096,
            b"device::".to_vec(),
        ))
        .feed(&Packet::new(Command::Auth, AUTH_TOKEN, 0, vec![0x5a; 20]))
        .feed(&wrte(1, b"after"));

    let mut buf = [0u8; 16];
    let n = now(conn.read_channel(ch, &mut buf)).unwrap();

    assert_eq!(&buf[..n], b"after");
}