libadb 0.7.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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
use alloc::vec::Vec;
use core::fmt::{self};

use super::protocol::features::Feature;
use super::protocol::Command;

pub use super::protobuf::DecodeError;

/// ADB protocol error, parameterized over the transport IO error type.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error<E> {
    /// Transport IO error.
    Io(E),
    /// ADB protocol violation.
    Protocol(ProtocolError),
    /// Authentication failed.
    Auth(AuthError),
    /// Sync protocol error.
    Sync(SyncError),
    /// Reverse-forward service error.
    Reverse(ReverseError),
    /// Operation on a closed channel.
    ChannelClosed,
    /// All channel slots are occupied.
    NoFreeChannels,
    /// Transport closed unexpectedly (EOF during read).
    UnexpectedEof,
    /// A caller-provided receive buffer is too small to hold the next
    /// frame and cannot be grown. Returned by [`shell::v2::Shell`] when
    /// the buffer passed to [`shell::v2::Shell::new`] cannot fit either
    /// the next inbound frame or any further bytes from the channel
    /// after compaction.
    ///
    /// [`shell::v2::Shell`]: crate::shell::v2::Shell
    /// [`shell::v2::Shell::new`]: crate::shell::v2::Shell::new
    ReceiveBufferFull,
    /// A channel buffered more unread data than
    /// [`ConnectionConfig::max_rx_per_channel`] allows.
    ///
    /// The last line of defence, not the usual brake: unread data now
    /// holds back acknowledgements, so a device that respects flow
    /// control stops on its own well before this. Reaching it means the
    /// peer kept writing without its window being re-opened. The
    /// connection is left intact but the offending packet was dropped
    /// unacknowledged, so that channel now has a gap in its byte stream
    /// — treat it as fatal for that channel.
    ///
    /// [`ConnectionConfig::max_rx_per_channel`]: crate::ConnectionConfig::max_rx_per_channel
    ChannelRxOverflow,
    /// Logcat binary entry parsing error.
    Logcat(crate::logcat::LogcatError),
    /// Hex-framed protobuf decode error (track-app, app-info).
    Decode(DecodeError),
    /// Device does not advertise a feature required by the attempted operation.
    MissingFeature(Feature),
    /// A packet may have been left half-written, so the byte stream can
    /// no longer be trusted to line up with what the device expects.
    ///
    /// Raised by every later operation on the connection. A packet
    /// reaches the wire as a header write followed by a payload write;
    /// dropping that future in between leaves the device reading the
    /// next bytes we send as the rest of the abandoned packet.
    ///
    /// The judgement is deliberately conservative: it also covers a
    /// write that was polled and then dropped or failed before any byte
    /// was acknowledged, because a transport that took bytes and then
    /// returned `Pending` or an error is indistinguishable from one
    /// that took none. Nothing can recover the framing from this side —
    /// close the connection and open a new one.
    Desynchronized,
    /// The read half of a split connection is gone: its `Reader::run`
    /// ended or the `Reader` was dropped, so nothing more will arrive
    /// from the device. Waiting on such a connection would never end;
    /// open a new one.
    Disconnected,
}

/// What stopped the exchange at the protocol level: something from the
/// device that breaks the ADB protocol, something of ours it cannot
/// carry, or a handshake this connection does not follow.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProtocolError {
    /// Invalid command code.
    InvalidCommand(u32),
    /// Message magic field does not match command.
    InvalidMagic,
    /// Data checksum mismatch.
    InvalidChecksum,
    /// Payload exceeds negotiated max_payload.
    PayloadTooLarge,
    /// Received an unexpected command for the current state.
    UnexpectedCommand(Command),
    /// Delayed-ACK READY packet payload is shorter than 4 bytes.
    ShortReadyPayload,
    /// AUTH token is not the 20-byte SHA-1 prehash the handshake signs.
    /// Carries the length that arrived.
    InvalidAuthToken(usize),
    /// Shell v2 EXIT frame received with empty payload (expected 1-byte exit code).
    ShortExitPayload,
    /// Service destination string contains an embedded NUL byte.
    InvalidDestination,
    /// Received an unknown feature from a device.
    UnknownFeature,
    /// Failed to convert the device banner to UTF-8.
    InvalidBannerUtf8,
    /// Device banner lacks a `<state>:<serial>:` prefix.
    InvalidBannerPrefix,
    /// Invalid key-value pair in the device banner.
    InvalidBannerKeyValue,
    /// Too many properties in the device banner.
    TooManyBannerProperties,
    /// Too many features in the device banner.
    TooManyBannerFeatures,
    /// The device answered the handshake with `STLS`: it speaks nothing
    /// but TLS from here on.
    ///
    /// This is how Android 11+ wireless debugging answers on the address
    /// and port its "Wireless debugging" screen shows. The pairing port
    /// is another thing: it speaks TLS from the first byte, and is for
    /// `pairing::pair`. The legacy port `adb tcpip` opens is plain text,
    /// and so is USB; neither is affected.
    ///
    /// With the `tls` feature, `Connection::connect_tls` takes the offer
    /// up.
    TlsRequired,
    /// More arrived in the clear behind the device's `STLS`.
    ///
    /// A TLS 1.3 server says nothing before the client's hello, so
    /// whatever follows `STLS` before the session starts is another
    /// plaintext packet, not the beginning of TLS.
    ///
    /// Returned by `Connection::connect_tls`. Only what arrived along
    /// with the `STLS` is caught here; plaintext sent later reaches the
    /// session and fails the handshake as a broken record.
    DataAfterStls,
}

/// Why the host did not get past authentication: the device refused it
/// or closed on it, or the authenticator would not sign or would not
/// offer its key.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthError {
    /// Device rejected all authentication attempts.
    Rejected,
    /// The authenticator would not sign the token. Carries what it
    /// said, since that is the only account of the failure there is.
    SignFailed(alloc::string::String),
    /// The device did not accept the signature, and the authenticator
    /// chose not to offer the public key in its place.
    ///
    /// The device does not trust this key yet, and nothing has asked
    /// the user to: see
    /// [`Authenticator::offer_public_key`](crate::auth::Authenticator::offer_public_key).
    KeyNotTrusted,
    /// The device refused the certificate we offered: it does not have
    /// the key inside it.
    ///
    /// TLS 1.3 tells a client nothing when the server rejects its
    /// certificate: the certificate goes out in the client's last
    /// flight, so the handshake is over on our side before the device
    /// judges it, and the refusal arrives as an alert on the first
    /// read. adbd sends `certificate_unknown`; the other alerts a TLS
    /// stack may send over a certificate count too, `access_denied`
    /// among them. Authorise the key over USB, or run `adb pair`.
    TlsKeyNotTrusted,
    /// The device finished the TLS handshake and closed the session
    /// before any of its CNXN arrived.
    ///
    /// A device that refuses the key by closing looks like this, but so
    /// does one that took the key and then went away: adbd restarting,
    /// wireless debugging switched off, a reboot. If it keeps happening
    /// and the key was never paired or authorised, run `adb pair` or
    /// authorise it over USB.
    TlsClosedBeforeConnect,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SyncError {
    /// Device returned a `FAIL` response. The message is truncated to
    /// the session buffer when the device sent more than it holds.
    Failed(Vec<u8>),
    /// Unexpected sync response command ID.
    UnexpectedId([u8; 4]),
    /// `STA2` / `LIS2` reported a non-zero error code (device errno).
    RemoteErrno(u32),
}

impl fmt::Display for ProtocolError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidMagic => f.write_str("invalid message magic"),
            Self::InvalidChecksum => f.write_str("data checksum mismatch"),
            Self::InvalidCommand(c) => f.write_fmt(format_args!("invalid command {}", c)),
            Self::PayloadTooLarge => f.write_str("payload exceeds max_payload"),
            // No word of `connect_tls`: a build without `tls` has none
            // to offer, and libadb-ffi words its own advice for C.
            Self::TlsRequired => f.write_str(
                "device requires a TLS handshake (Android 11+ wireless debugging) \
                 that this connection does not do; connect over USB, \
                 or switch the device to plain TCP with `adb tcpip 5555`",
            ),
            Self::DataAfterStls => {
                f.write_str("device sent more in the clear after STLS, where only TLS may follow")
            }
            Self::UnexpectedCommand(c) => f.write_fmt(format_args!("unexpected command {:?}", c)),
            Self::ShortReadyPayload => {
                f.write_str("delayed-ack READY payload shorter than 4 bytes")
            }
            Self::InvalidAuthToken(len) => f.write_fmt(format_args!(
                "AUTH token is {len} bytes, not the 20-byte SHA-1 prehash"
            )),
            Self::ShortExitPayload => f.write_str("shell v2 EXIT frame payload empty"),
            Self::InvalidDestination => f.write_str("service destination contains a NUL byte"),
            Self::UnknownFeature => f.write_str("unknown feature"),
            Self::InvalidBannerUtf8 => f.write_str("failed to convert the device banner to UTF-8"),
            Self::InvalidBannerPrefix => f.write_str("invalid device banner prefix"),
            Self::InvalidBannerKeyValue => {
                f.write_str("invalid key-value pair in the device banner")
            }
            Self::TooManyBannerProperties => {
                f.write_str("too many properties in the device banner")
            }
            Self::TooManyBannerFeatures => f.write_str("too many features in the device banner"),
        }
    }
}

impl fmt::Display for AuthError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Rejected => f.write_str("authentication rejected"),
            Self::SignFailed(why) => f.write_fmt(format_args!("authenticator sign failed: {why}")),
            Self::KeyNotTrusted => f.write_str(
                "device does not trust this key, and the key was not offered for approval",
            ),
            Self::TlsKeyNotTrusted => f.write_str(
                "device does not trust this key over TLS; authorise it over USB or run `adb pair`",
            ),
            Self::TlsClosedBeforeConnect => f.write_str(
                "device closed the TLS session right after the handshake, before its CNXN; \
                 if this key was never paired or authorised, run `adb pair` or authorise it over USB",
            ),
        }
    }
}

impl fmt::Display for SyncError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Failed(msg) => {
                let s = core::str::from_utf8(msg).unwrap_or("<non-utf8>");
                write!(f, "sync: device error: {s}")
            }
            Self::UnexpectedId(id) => {
                let s = core::str::from_utf8(id).unwrap_or("????");
                write!(f, "sync: unexpected response: {s}")
            }
            Self::RemoteErrno(e) => write!(f, "sync: remote errno {e}"),
        }
    }
}

impl<E: fmt::Display> fmt::Display for Error<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(e) => write!(f, "io: {e}"),
            Self::Protocol(e) => write!(f, "protocol: {e}"),
            Self::Auth(e) => write!(f, "auth: {e}"),
            Self::Sync(e) => write!(f, "{e}"),
            Self::Reverse(e) => write!(f, "{e}"),
            Self::ChannelClosed => f.write_str("channel closed"),
            Self::NoFreeChannels => f.write_str("no free channel slots"),
            Self::UnexpectedEof => f.write_str("unexpected eof"),
            Self::ReceiveBufferFull => f.write_str("receive buffer full"),
            Self::ChannelRxOverflow => {
                f.write_str("channel buffered more unread data than max_rx_per_channel allows")
            }
            Self::Logcat(e) => write!(f, "{e}"),
            Self::Decode(e) => write!(f, "{e}"),
            Self::MissingFeature(feature) => {
                write!(
                    f,
                    "device does not advertise feature {:?} ({})",
                    feature,
                    feature.wire_name()
                )
            }
            Self::Desynchronized => f.write_str("connection desynchronized by an unfinished write"),
            Self::Disconnected => f.write_str("connection no longer read"),
        }
    }
}

impl core::error::Error for ProtocolError {}

impl core::error::Error for AuthError {}

impl core::error::Error for SyncError {}

impl<E> core::error::Error for Error<E>
where
    E: core::error::Error + 'static,
{
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            Self::Protocol(e) => Some(e),
            Self::Auth(e) => Some(e),
            Self::Sync(e) => Some(e),
            Self::Reverse(e) => Some(e),
            Self::Logcat(e) => Some(e),
            Self::Decode(e) => Some(e),
            Self::ChannelClosed
            | Self::NoFreeChannels
            | Self::UnexpectedEof
            | Self::ReceiveBufferFull
            | Self::ChannelRxOverflow
            | Self::Desynchronized
            | Self::Disconnected
            | Self::MissingFeature(_) => None,
        }
    }
}

impl<E> From<ProtocolError> for Error<E> {
    fn from(e: ProtocolError) -> Self {
        Self::Protocol(e)
    }
}

/// A channel's receive buffer hit its configured cap. Internal marker
/// turned into [`Error::ChannelRxOverflow`] at the call sites that know
/// the transport error type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RxOverflow;

impl<E> From<RxOverflow> for Error<E> {
    fn from(_: RxOverflow) -> Self {
        Self::ChannelRxOverflow
    }
}

impl<E> From<AuthError> for Error<E> {
    fn from(e: AuthError) -> Self {
        Self::Auth(e)
    }
}

impl<E> From<SyncError> for Error<E> {
    fn from(e: SyncError) -> Self {
        Self::Sync(e)
    }
}

impl<E> From<ReverseError> for Error<E> {
    fn from(e: ReverseError) -> Self {
        Self::Reverse(e)
    }
}

/// What the `reverse:` rule service answered.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReverseError {
    /// The device returned `FAIL`. The message is adbd's own text,
    /// e.g. `bad forward: …` or `listener '…' not found`.
    Failed(Vec<u8>),
    /// The reply matched neither `OKAY` nor `FAIL`, or a *successful*
    /// reply's length prefix disagreed with what arrived. A `FAIL` is
    /// reported as [`Failed`](Self::Failed) even when its own length
    /// prefix is mangled — the device's message matters more than its
    /// framing.
    UnexpectedReply,
}

impl fmt::Display for ReverseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Failed(msg) => {
                write!(f, "reverse service failed: ")?;
                match core::str::from_utf8(msg) {
                    Ok(m) => f.write_str(m),
                    Err(_) => write!(f, "{msg:?}"),
                }
            }
            Self::UnexpectedReply => f.write_str("unexpected reverse service reply"),
        }
    }
}

impl core::error::Error for ReverseError {}

impl<E> From<crate::logcat::LogcatError> for Error<E> {
    fn from(e: crate::logcat::LogcatError) -> Self {
        Self::Logcat(e)
    }
}

impl<E> From<DecodeError> for Error<E> {
    fn from(e: DecodeError) -> Self {
        Self::Decode(e)
    }
}

#[cfg(test)]
mod tests {
    use super::{AuthError, DecodeError, Error, ProtocolError, SyncError};
    use crate::base::protocol::features::Feature;
    use crate::base::protocol::Command;
    use crate::logcat::LogcatError;
    use alloc::format;
    use alloc::vec;
    use core::fmt;

    #[derive(Debug)]
    struct IoStub;

    impl fmt::Display for IoStub {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("io-stub")
        }
    }

    impl core::error::Error for IoStub {}

    fn show<E: fmt::Display>(e: &E) -> alloc::string::String {
        format!("{}", e)
    }

    #[test]
    fn protocol_display_invalid_magic() {
        assert_eq!(show(&ProtocolError::InvalidMagic), "invalid message magic");
    }

    #[test]
    fn protocol_display_invalid_checksum() {
        assert_eq!(
            show(&ProtocolError::InvalidChecksum),
            "data checksum mismatch"
        );
    }

    #[test]
    fn protocol_display_tls_required_names_a_way_out() {
        assert_eq!(
            show(&ProtocolError::TlsRequired),
            "device requires a TLS handshake (Android 11+ wireless debugging) \
             that this connection does not do; connect over USB, \
             or switch the device to plain TCP with `adb tcpip 5555`"
        );
    }

    #[test]
    fn protocol_display_data_after_stls() {
        assert_eq!(
            show(&ProtocolError::DataAfterStls),
            "device sent more in the clear after STLS, where only TLS may follow"
        );
    }

    #[test]
    fn auth_display_tls_key_not_trusted_points_at_pairing() {
        assert_eq!(
            show(&AuthError::TlsKeyNotTrusted),
            "device does not trust this key over TLS; authorise it over USB or run `adb pair`"
        );
    }

    #[test]
    fn auth_display_tls_closed_before_connect_points_at_pairing_only_if_it_applies() {
        assert_eq!(
            show(&AuthError::TlsClosedBeforeConnect),
            "device closed the TLS session right after the handshake, before its CNXN; \
             if this key was never paired or authorised, run `adb pair` or authorise it over USB"
        );
    }

    #[test]
    fn protocol_display_invalid_command_embeds_raw_code() {
        assert_eq!(
            show(&ProtocolError::InvalidCommand(0xDEAD_BEEF)),
            format!("invalid command {}", 0xDEAD_BEEFu32)
        );
    }

    #[test]
    fn protocol_display_payload_too_large() {
        assert_eq!(
            show(&ProtocolError::PayloadTooLarge),
            "payload exceeds max_payload"
        );
    }

    #[test]
    fn protocol_display_unexpected_command_uses_debug_of_command() {
        assert_eq!(
            show(&ProtocolError::UnexpectedCommand(Command::Write)),
            "unexpected command Write"
        );
    }

    #[test]
    fn protocol_display_unknown_feature() {
        assert_eq!(show(&ProtocolError::UnknownFeature), "unknown feature");
    }

    #[test]
    fn protocol_display_banner_variants() {
        assert_eq!(
            show(&ProtocolError::InvalidBannerUtf8),
            "failed to convert the device banner to UTF-8"
        );
        assert_eq!(
            show(&ProtocolError::InvalidBannerPrefix),
            "invalid device banner prefix"
        );
        assert_eq!(
            show(&ProtocolError::InvalidBannerKeyValue),
            "invalid key-value pair in the device banner"
        );
        assert_eq!(
            show(&ProtocolError::TooManyBannerProperties),
            "too many properties in the device banner"
        );
        assert_eq!(
            show(&ProtocolError::TooManyBannerFeatures),
            "too many features in the device banner"
        );
    }

    #[test]
    fn auth_display_rejected_and_sign_failed() {
        assert_eq!(show(&AuthError::Rejected), "authentication rejected");
        assert_eq!(
            show(&AuthError::SignFailed(alloc::string::String::from(
                "no key"
            ))),
            "authenticator sign failed: no key"
        );
    }

    #[test]
    fn sync_display_failed_utf8_message() {
        assert_eq!(
            show(&SyncError::Failed(b"no such file".to_vec())),
            "sync: device error: no such file"
        );
    }

    #[test]
    fn sync_display_failed_non_utf8_message_falls_back_to_placeholder() {
        assert_eq!(
            show(&SyncError::Failed(vec![0xff, 0xfe, 0xfd])),
            "sync: device error: <non-utf8>"
        );
    }

    #[test]
    fn sync_display_unexpected_id_ascii() {
        assert_eq!(
            show(&SyncError::UnexpectedId(*b"FAIL")),
            "sync: unexpected response: FAIL"
        );
    }

    #[test]
    fn sync_display_unexpected_id_non_utf8_falls_back_to_question_marks() {
        assert_eq!(
            show(&SyncError::UnexpectedId([0xff, 0xfe, 0xfd, 0xfc])),
            "sync: unexpected response: ????"
        );
    }

    #[test]
    fn sync_display_remote_errno() {
        assert_eq!(show(&SyncError::RemoteErrno(2)), "sync: remote errno 2");
    }

    #[test]
    fn error_display_io_uses_inner() {
        let e: Error<IoStub> = Error::Io(IoStub);
        assert_eq!(show(&e), "io: io-stub");
    }

    #[test]
    fn error_display_protocol_is_prefixed() {
        let e: Error<IoStub> = Error::Protocol(ProtocolError::InvalidMagic);
        assert_eq!(show(&e), "protocol: invalid message magic");
    }

    #[test]
    fn error_display_auth_is_prefixed() {
        let e: Error<IoStub> = Error::Auth(AuthError::Rejected);
        assert_eq!(show(&e), "auth: authentication rejected");
    }

    #[test]
    fn error_display_sync_keeps_inner_prefix_only() {
        let e: Error<IoStub> = Error::Sync(SyncError::RemoteErrno(13));
        assert_eq!(show(&e), "sync: remote errno 13");
    }

    #[test]
    fn error_display_channel_closed() {
        let e: Error<IoStub> = Error::ChannelClosed;
        assert_eq!(show(&e), "channel closed");
    }

    #[test]
    fn error_display_no_free_channels() {
        let e: Error<IoStub> = Error::NoFreeChannels;
        assert_eq!(show(&e), "no free channel slots");
    }

    #[test]
    fn error_display_unexpected_eof() {
        let e: Error<IoStub> = Error::UnexpectedEof;
        assert_eq!(show(&e), "unexpected eof");
    }

    #[test]
    fn error_display_receive_buffer_full() {
        let e: Error<IoStub> = Error::ReceiveBufferFull;
        assert_eq!(show(&e), "receive buffer full");
    }

    #[test]
    fn error_display_logcat_uses_inner_unprefixed() {
        let e: Error<IoStub> = Error::Logcat(LogcatError::InvalidHeader);
        assert_eq!(show(&e), "logcat: invalid logger_entry header");
    }

    #[test]
    fn error_display_decode_uses_inner_unprefixed() {
        let e: Error<IoStub> = Error::Decode(DecodeError::InvalidProtobuf);
        assert_eq!(show(&e), "invalid protobuf");
    }

    #[test]
    fn error_display_missing_feature_lists_debug_and_wire_name() {
        let e: Error<IoStub> = Error::MissingFeature(Feature::ShellV2);
        assert_eq!(
            show(&e),
            "device does not advertise feature ShellV2 (shell_v2)"
        );
    }

    #[test]
    fn error_and_inner_enums_implement_core_error() {
        fn assert_core_error<E: core::error::Error>(_: &E) {}

        assert_core_error(&Error::<IoStub>::ChannelClosed);
        assert_core_error(&ProtocolError::InvalidMagic);
        assert_core_error(&AuthError::Rejected);
        assert_core_error(&SyncError::RemoteErrno(1));
        assert_core_error(&LogcatError::InvalidHeader);
        assert_core_error(&DecodeError::InvalidProtobuf);
    }

    #[test]
    fn error_source_exposes_inner_error() {
        let e: Error<IoStub> = Error::Protocol(ProtocolError::InvalidMagic);
        let source = core::error::Error::source(&e).expect("protocol source");
        assert_eq!(format!("{source}"), "invalid message magic");

        let io: Error<IoStub> = Error::Io(IoStub);
        let source = core::error::Error::source(&io).expect("io source");
        assert_eq!(format!("{source}"), "io-stub");
    }

    #[test]
    fn error_source_is_none_for_leaf_variants() {
        assert!(core::error::Error::source(&Error::<IoStub>::ChannelClosed).is_none());
        assert!(core::error::Error::source(&Error::<IoStub>::UnexpectedEof).is_none());
    }

    #[test]
    fn error_from_protocol_wraps_into_protocol_variant() {
        let e: Error<IoStub> = ProtocolError::InvalidMagic.into();
        assert!(matches!(e, Error::Protocol(ProtocolError::InvalidMagic)));
    }

    #[test]
    fn error_from_auth_wraps_into_auth_variant() {
        let e: Error<IoStub> = AuthError::Rejected.into();
        assert!(matches!(e, Error::Auth(AuthError::Rejected)));
    }

    #[test]
    fn error_from_sync_wraps_into_sync_variant() {
        let e: Error<IoStub> = SyncError::RemoteErrno(5).into();
        assert!(matches!(e, Error::Sync(SyncError::RemoteErrno(5))));
    }

    #[test]
    fn error_from_logcat_wraps_into_logcat_variant() {
        let e: Error<IoStub> = LogcatError::InvalidHeader.into();
        assert!(matches!(e, Error::Logcat(LogcatError::InvalidHeader)));
    }

    #[test]
    fn error_from_decode_wraps_into_decode_variant() {
        let e: Error<IoStub> = DecodeError::InvalidUtf8.into();
        assert!(matches!(e, Error::Decode(DecodeError::InvalidUtf8)));
    }
}