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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! A transport that can start TLS on itself, for ADB's `STLS`.
//!
//! [`MaybeTls`] sits in the TCP slot of
//! [`Transport`](crate::transport::common::Transport), so a connection
//! keeps the same type whether or not the device asked for TLS. Before
//! [`StartTls::start_tls`] it passes bytes straight through; after it,
//! everything goes through `rustls`.
//!
//! The `rustls` engine is driven by hand over
//! [`embedded_io_async`] rather than through a runtime-specific adapter
//! such as `tokio-rustls`. At the point the upgrade happens all we hold
//! is a generic reader-writer, not a socket, and one hand-driven engine
//! serves every runtime this crate supports.

#[cfg(feature = "tls")]
pub use self::inner::*;

#[cfg(feature = "tls")]
mod inner {
    use alloc::boxed::Box;
    use alloc::sync::Arc;
    use alloc::vec;
    use alloc::vec::Vec;
    use core::future::Future;
    use std::sync::OnceLock;

    use bytes::{Buf, BytesMut};
    use embedded_io::ErrorType;
    use embedded_io_async::{Read, Write};
    use rustls::ClientConnection;

    use crate::tls::TlsClientConfig;
    use crate::transport::common::Transport;
    use crate::transport::{ReadCancelSafety, Splittable};

    /// Landing zone for one socket read. A TLS record tops out a little
    /// over 16 KiB, so one of these swallows a whole record.
    const CHUNK: usize = 16 * 1024 + 512;

    /// Once this many bytes of sealed records wait in the queue, the next
    /// write sends them before it seals its own. Below that, writes only
    /// queue, and the flush that ends a packet sends all of it at once.
    const QUEUE_LIMIT: usize = 64 * 1024;

    /// Why a TLS transport failed.
    #[derive(Debug)]
    #[non_exhaustive]
    pub enum TlsError<E> {
        /// The transport underneath failed.
        Io(E),
        /// The TLS session failed: a handshake, a record, or an alert
        /// the device sent.
        Tls(rustls::Error),
        /// The device closed the connection in the middle of the
        /// handshake. Our certificate only goes out once the handshake
        /// is over on our side, so the device had not seen the key.
        HandshakeClosed,
        /// The transport underneath took none of a write. An
        /// `embedded-io` writer may not do that with bytes on offer, so
        /// the connection is taken as gone, not as a device refusing
        /// anything.
        WriteZero,
        /// What was asked cannot be done on this transport: `start_tls`
        /// on USB or on a transport that is no longer plain, keying
        /// material while still in the clear, or a read, write, flush or
        /// split after a handshake that failed or was dropped part way,
        /// which takes the socket with it.
        NotAvailable,
        /// A write came after `shutdown`. rustls would still seal it and
        /// send it behind the `close_notify`, which the peer takes as the
        /// end of what we have to say.
        Closed,
    }

    impl<E: core::fmt::Display> core::fmt::Display for TlsError<E> {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            match self {
                Self::Io(e) => write!(f, "io: {e}"),
                Self::Tls(e) => write!(f, "tls: {e}"),
                Self::HandshakeClosed => f.write_str("tls: device closed during the handshake"),
                Self::WriteZero => f.write_str("tls: the transport took none of a write"),
                Self::NotAvailable => f.write_str("tls: not available on this transport"),
                Self::Closed => f.write_str("tls: the session was already shut down"),
            }
        }
    }

    impl<E> core::error::Error for TlsError<E>
    where
        E: core::error::Error + 'static,
    {
        fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
            match self {
                Self::Io(e) => Some(e),
                Self::Tls(e) => Some(e),
                Self::HandshakeClosed | Self::WriteZero | Self::NotAvailable | Self::Closed => None,
            }
        }
    }

    impl<E: embedded_io::Error> embedded_io::Error for TlsError<E> {
        fn kind(&self) -> embedded_io::ErrorKind {
            match self {
                Self::Io(e) => e.kind(),
                Self::Tls(_) | Self::HandshakeClosed => embedded_io::ErrorKind::Other,
                Self::WriteZero => embedded_io::ErrorKind::WriteZero,
                Self::NotAvailable => embedded_io::ErrorKind::Unsupported,
                Self::Closed => embedded_io::ErrorKind::BrokenPipe,
            }
        }
    }

    mod sealed {
        pub trait Sealed {}
    }

    /// A transport that can put a TLS session on top of itself.
    ///
    /// It is what [`Connection::connect_tls`](crate::Connection::connect_tls)
    /// asks of its transport: a [`MaybeTls`], or a
    /// [`Transport`](crate::transport::common::Transport) whose TCP side
    /// is one, as
    /// [`tls_ready`](crate::transport::common::Transport::tls_ready)
    /// makes it.
    ///
    /// Sealed: only this crate's transports implement it, so a method
    /// can be added later without breaking anyone.
    pub trait StartTls: Read + Write + sealed::Sealed {
        /// Start TLS 1.3 as the client and carry the handshake through.
        ///
        /// The session starts from the socket as it stands: call this
        /// straight after the `STLS` exchange, with nothing read past it.
        ///
        /// # Errors
        ///
        /// [`TlsError::NotAvailable`] on USB, or on a transport that is
        /// no longer plain, which is left as it was. Otherwise
        /// [`TlsError::HandshakeClosed`] if the device hangs up during
        /// the handshake, [`TlsError::Tls`] if `rustls` fails it or will
        /// not start one, and [`TlsError::Io`] or [`TlsError::WriteZero`]
        /// from the socket. Through a
        /// [`Transport`](crate::transport::common::Transport) each comes
        /// wrapped in `TransportError::Tcp`.
        ///
        /// # Cancellation
        ///
        /// Not cancel-safe. A failure other than `NotAvailable`, or
        /// dropping the future before it completes, takes the socket
        /// with it: every read, write, flush and split after that
        /// returns [`TlsError::NotAvailable`].
        fn start_tls(
            &mut self,
            config: &TlsClientConfig,
        ) -> impl Future<Output = Result<(), Self::Error>>;

        /// Whether `error` is the device refusing the key we offered.
        ///
        /// TLS 1.3 tells a client nothing when the server rejects its
        /// certificate: the handshake finishes locally and the refusal
        /// arrives as an alert on the first read. Without this, that
        /// reads as an ordinary transport failure.
        fn is_key_rejected(error: &Self::Error) -> bool;
    }

    /// Alerts a device sends when it will not have the key.
    ///
    /// adbd refuses from its certificate callback, which BoringSSL
    /// answers with `certificate_unknown`; the rest are the other
    /// certificate alerts a TLS stack might pick instead. Generic ones
    /// such as `handshake_failure` or `decrypt_error` stay out: they
    /// mean the handshake broke for some other reason, and calling that
    /// a refusal would send the user off to pair for nothing. So does
    /// `certificate_required`, which says no certificate arrived at all.
    fn alert_means_rejection(alert: rustls::AlertDescription) -> bool {
        use rustls::AlertDescription as A;
        matches!(
            alert,
            A::BadCertificate
                | A::UnsupportedCertificate
                | A::CertificateRevoked
                | A::CertificateExpired
                | A::CertificateUnknown
                | A::UnknownCA
                | A::AccessDenied
        )
    }

    impl<E> TlsError<E> {
        /// Whether this is the device refusing the key, rather than a
        /// connection that went wrong on its own: an alert over the
        /// certificate, such as the `certificate_unknown` adbd sends.
        ///
        /// A device that refuses by just closing is not caught here.
        /// [`Connection::connect_tls`](crate::Connection::connect_tls)
        /// reports that as
        /// [`AuthError::TlsClosedBeforeConnect`](crate::error::AuthError::TlsClosedBeforeConnect).
        pub fn is_key_rejected(&self) -> bool {
            match self {
                Self::Tls(rustls::Error::AlertReceived(a)) => alert_means_rejection(*a),
                // Not `HandshakeClosed`: the key had not gone out yet. A
                // device that refuses by just closing does so after the
                // handshake, and the connect path names that on its own.
                _ => false,
            }
        }
    }

    /// What a look at the plaintext side turned up.
    enum Plain {
        Got(usize),
        /// The peer's `close_notify` has arrived, and everything before
        /// it has been read.
        Eof,
        /// No plaintext waiting, and no `close_notify` either.
        Blocked,
    }

    /// Somewhere for `write_tls` to put records.
    struct Sink<'a>(&'a mut BytesMut);

    impl std::io::Write for Sink<'_> {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0.extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    /// Move every record rustls has ready into `out`.
    fn harvest(conn: &mut ClientConnection, out: &mut BytesMut) {
        while conn.wants_write() {
            if conn.write_tls(&mut Sink(out)).is_err() {
                break;
            }
        }
    }

    /// Hand rustls the ciphertext in `rx`; returns how much it took.
    ///
    /// rustls buffers incomplete records itself, so it takes all of `rx`
    /// unless the plaintext fills up first, and the callers drain that
    /// before they come here. It takes none only once a `close_notify`
    /// has arrived, which the callers hear of from `take_plaintext`
    /// first: their arms for zero are a safeguard.
    ///
    /// Nothing here writes. A KeyUpdate from the peer may ask for ours,
    /// but rustls keeps the answer until our next record goes out, which
    /// is all RFC 8446 section 4.6.3 asks; only a failure queues an alert.
    fn feed(conn: &mut ClientConnection, rx: &mut BytesMut) -> Result<usize, rustls::Error> {
        let start = rx.len();
        while !rx.is_empty() {
            let taken = match conn.read_tls(&mut &rx[..]) {
                Ok(0) => break,
                Ok(n) => n,
                // Backpressure: the plaintext is full, and the caller
                // drains it and comes back.
                Err(e) if e.kind() == std::io::ErrorKind::Other => break,
                // Anything else is for good. A handshake message too big
                // to buffer is refused this way, and would be refused on
                // every call after.
                Err(e) => return Err(rustls::Error::General(alloc::format!("{e}"))),
            };
            rx.advance(taken);
            conn.process_new_packets()?;
        }
        Ok(start - rx.len())
    }

    /// Take whatever plaintext is decrypted.
    ///
    /// rustls sees the end of the session only as a `close_notify`. The
    /// end of the stream underneath never reaches it: `feed` hands it
    /// ciphertext and nothing else, and the callers watch for that end
    /// themselves.
    fn take_plaintext(conn: &mut ClientConnection, buf: &mut [u8]) -> Plain {
        use std::io::Read as _;
        match conn.reader().read(buf) {
            Ok(0) => Plain::Eof,
            Ok(n) => Plain::Got(n),
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => Plain::Blocked,
            // `UnexpectedEof`, which only a stream end fed to rustls could
            // raise. A broken record fails in `process_new_packets`.
            Err(_) => Plain::Eof,
        }
    }

    /// Ciphertext on its way in, for either kind of session.
    struct Inbound {
        /// Read off the wire and not yet decrypted. A field rather than a
        /// local, so a dropped read loses nothing.
        rx: BytesMut,
        /// Where one socket read lands before it is committed to `rx`.
        scratch: Vec<u8>,
        /// Whether the transport underneath has ended.
        eof: bool,
    }

    impl Inbound {
        fn new() -> Self {
            Self {
                rx: BytesMut::with_capacity(CHUNK),
                scratch: vec![0u8; CHUNK],
                eof: false,
            }
        }

        /// Read one chunk of ciphertext off the wire.
        async fn fill<R: Read>(&mut self, inner: &mut R) -> Result<(), TlsError<R::Error>> {
            // Into `scratch`, not `rx`: a read dropped mid-await must not
            // leave `rx` holding bytes that never arrived.
            let n = inner.read(&mut self.scratch).await.map_err(TlsError::Io)?;
            if n == 0 {
                self.eof = true;
            } else {
                self.rx.extend_from_slice(&self.scratch[..n]);
            }
            Ok(())
        }
    }

    /// Write out `queue`, resuming where a dropped call left off.
    async fn send_queue<W: Write>(
        w: &mut W,
        queue: &mut BytesMut,
    ) -> Result<(), TlsError<W::Error>> {
        while !queue.is_empty() {
            let n = w.write(queue).await.map_err(TlsError::Io)?;
            if n == 0 {
                return Err(TlsError::WriteZero);
            }
            queue.advance(n);
        }
        Ok(())
    }

    /// Hand rustls plaintext to seal; returns how much it took.
    fn write_plain<E>(conn: &mut ClientConnection, buf: &[u8]) -> Result<usize, TlsError<E>> {
        use std::io::Write as _;
        conn.writer()
            .write(buf)
            .map_err(|_| TlsError::Tls(rustls::Error::General("tls writer closed".into())))
    }

    fn engine(config: &TlsClientConfig) -> Result<Box<ClientConnection>, rustls::Error> {
        let conn =
            ClientConnection::new(Arc::clone(config.rustls()), config.server_name().clone())?;
        Ok(Box::new(conn))
    }

    /// A TLS session over one transport, before anyone splits it.
    pub(crate) struct TlsSession<T> {
        inner: T,
        conn: Box<ClientConnection>,
        inbound: Inbound,
        /// Records sealed and not yet written, already advanced past
        /// whatever the socket took, so a dropped call resumes here
        /// instead of leaving half a record behind. They go out on a
        /// flush, or with the next write once they come to `QUEUE_LIMIT`
        /// bytes.
        tx: BytesMut,
        /// The failure the session met, kept so that every later call
        /// reports it too; only a write after `shutdown` reports `Closed`
        /// instead. Set before anything awaits, so a dropped call cannot
        /// take it along.
        failed: Option<rustls::Error>,
        /// Whether `shutdown` has been called. Writes are refused from
        /// then on.
        closed: bool,
    }

    impl<T: Read + Write> TlsSession<T> {
        fn new(inner: T, config: &TlsClientConfig) -> Result<Self, TlsError<T::Error>> {
            let conn = engine(config).map_err(TlsError::Tls)?;
            Ok(Self {
                inner,
                conn,
                inbound: Inbound::new(),
                tx: BytesMut::new(),
                failed: None,
                closed: false,
            })
        }

        /// Write out everything queued and flush the transport, resuming
        /// where a dropped call left off.
        async fn flush_tx(&mut self) -> Result<(), TlsError<T::Error>> {
            send_queue(&mut self.inner, &mut self.tx).await?;
            self.inner.flush().await.map_err(TlsError::Io)
        }

        /// Let rustls decrypt what is in hand; returns how much it took.
        ///
        /// A failure is kept for good. The alert rustls raises for it stays
        /// queued in the engine for the next write, flush or shutdown to
        /// carry: sending it from here would hold the caller up behind the
        /// socket.
        fn advance(&mut self) -> Result<usize, TlsError<T::Error>> {
            feed(&mut self.conn, &mut self.inbound.rx).map_err(|e| {
                self.failed = Some(e.clone());
                TlsError::Tls(e)
            })
        }

        /// Once the session has failed, a write, flush or shutdown reports
        /// that, and the first of them sends the alert for it, if the
        /// socket will take it.
        async fn failure(&mut self) -> Result<(), TlsError<T::Error>> {
            let Some(e) = self.failed.clone() else {
                return Ok(());
            };
            harvest(&mut self.conn, &mut self.tx);
            let _ = self.flush_tx().await;
            Err(TlsError::Tls(e))
        }

        async fn handshake(&mut self) -> Result<(), TlsError<T::Error>> {
            while self.conn.is_handshaking() {
                harvest(&mut self.conn, &mut self.tx);
                self.flush_tx().await?;
                // Ciphertext in hand goes to rustls before the socket is
                // read again. Mid-handshake rustls fails rather than refuse
                // input, so the arm for zero is a safeguard.
                if !self.inbound.rx.is_empty() {
                    match self.advance() {
                        Ok(0) => return Err(TlsError::HandshakeClosed),
                        Ok(_) => continue,
                        // Nothing writes after a failed handshake, so the
                        // alert goes out now.
                        Err(_) => return self.failure().await,
                    }
                }
                if self.inbound.eof {
                    return Err(TlsError::HandshakeClosed);
                }
                self.inbound.fill(&mut self.inner).await?;
            }
            // Our last flight is still inside rustls at this point.
            harvest(&mut self.conn, &mut self.tx);
            self.flush_tx().await
        }

        /// RFC 5705 exporter output for this session.
        fn export_keying_material(
            &self,
            out: &mut [u8],
            label: &[u8],
            context: Option<&[u8]>,
        ) -> Result<(), rustls::Error> {
            self.conn
                .export_keying_material(out, label, context)
                .map(|_| ())
        }

        /// Send `close_notify` and push it out.
        pub async fn shutdown(&mut self) -> Result<(), TlsError<T::Error>> {
            // Up front, as in the split half, so that a write after this is
            // refused however it ends, a failed session included.
            self.closed = true;
            self.failure().await?;
            self.conn.send_close_notify();
            harvest(&mut self.conn, &mut self.tx);
            self.flush_tx().await
        }
    }

    impl<T: Read + Write> ErrorType for TlsSession<T> {
        type Error = TlsError<T::Error>;
    }

    impl<T: Read + Write> Read for TlsSession<T> {
        async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
            if buf.is_empty() {
                return Ok(0);
            }
            loop {
                match take_plaintext(&mut self.conn, buf) {
                    Plain::Got(n) => return Ok(n),
                    Plain::Eof => return Ok(0),
                    Plain::Blocked => {}
                }
                // What decrypted ahead of a failure is read before it.
                if let Some(e) = &self.failed {
                    return Err(TlsError::Tls(e.clone()));
                }

                // Decrypt what is in hand before going back to the socket, or
                // the tail of a closed stream is lost as a clean end of file.
                // Nothing here writes: what is queued is the writer's to send.
                if !self.inbound.rx.is_empty() {
                    match self.advance() {
                        // A safeguard: `take_plaintext` above reports a
                        // `close_notify` first.
                        Ok(0) => return Ok(0),
                        // A failure is kept, and reported once what decrypted
                        // ahead of it has been read.
                        Ok(_) | Err(_) => continue,
                    }
                }
                if self.inbound.eof {
                    return Ok(0);
                }
                self.inbound.fill(&mut self.inner).await?;
            }
        }
    }

    impl<T: Read + Write> Write for TlsSession<T> {
        /// Seals `buf` into the queue; nothing awaits after that, so a
        /// write dropped anywhere has committed nothing it did not report.
        /// What earlier writes queued goes out first once there is
        /// `QUEUE_LIMIT` of it, and otherwise waits for a flush.
        async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
            if buf.is_empty() {
                return Ok(0);
            }
            if self.closed {
                return Err(TlsError::Closed);
            }
            self.failure().await?;
            if self.tx.len() >= QUEUE_LIMIT {
                send_queue(&mut self.inner, &mut self.tx).await?;
            }
            let n = write_plain(&mut self.conn, buf)?;
            harvest(&mut self.conn, &mut self.tx);
            Ok(n)
        }

        async fn flush(&mut self) -> Result<(), Self::Error> {
            self.failure().await?;
            harvest(&mut self.conn, &mut self.tx);
            self.flush_tx().await
        }
    }

    enum State<T: Read + Write> {
        Plain(T),
        Tls(TlsSession<T>),
        /// Held while the upgrade runs, and kept for good if it failed or
        /// was dropped part way: the socket goes with the session.
        Broken,
    }

    /// A transport that is plain now and may be TLS later.
    ///
    /// Wrap the socket with [`plain`](Self::plain) and hand it to
    /// [`Connection::connect_tls`](crate::Connection::connect_tls), which
    /// starts TLS only if the device asks for it; `pairing::pair` takes
    /// one too.
    /// [`Transport::tls_ready`](crate::transport::common::Transport::tls_ready)
    /// does the wrapping for the TCP-or-USB enum.
    ///
    /// Once `rustls` rejects what the device sends in a running session,
    /// every later read, write, flush and shutdown returns that same
    /// [`TlsError::Tls`], except that a write after
    /// [`shutdown`](Self::shutdown) is refused with [`TlsError::Closed`].
    /// What decrypted ahead of the failure is still read first.
    ///
    /// # Cancellation
    ///
    /// Reads lose nothing when dropped, as far as the transport
    /// underneath allows; see
    /// [`ReadCancelSafety`](crate::transport::ReadCancelSafety). Nor do
    /// writes: over TLS, `write` seals what it takes into a queue and
    /// returns without waiting again, so a write dropped part way has
    /// committed nothing it did not report. The queue is what waits on
    /// the socket. It goes out on `flush`, or with a later write once it
    /// has grown to 64 KiB, as with any buffered writer; call `flush`
    /// when a message is done. A dropped `flush` leaves the rest queued
    /// for the next one. After a split nothing else sends it: the read
    /// half never writes, so a reader waiting on the reply waits until
    /// the write half writes or flushes again.
    ///
    /// [`start_tls`](StartTls::start_tls) is the exception: it is not
    /// cancel-safe.
    pub struct MaybeTls<T: Read + Write> {
        state: State<T>,
    }

    impl<T: Read + Write> MaybeTls<T> {
        /// Wrap a transport, starting no TLS.
        pub fn plain(inner: T) -> Self {
            Self {
                state: State::Plain(inner),
            }
        }

        /// Whether a TLS session is running.
        pub fn is_tls(&self) -> bool {
            matches!(self.state, State::Tls(_))
        }

        /// Whether bytes still go out in the clear.
        ///
        /// Both this and [`is_tls`](Self::is_tls) are false once a
        /// handshake that failed or was dropped has taken the socket.
        pub fn is_plain(&self) -> bool {
            matches!(self.state, State::Plain(_))
        }

        /// Key material exported from the running session, as RFC 5705
        /// defines it.
        ///
        /// Pairing needs this: its password is the pairing code with the
        /// exporter's output appended, which is what ties the exchange to
        /// the session it runs in.
        ///
        /// # Errors
        ///
        /// [`TlsError::NotAvailable`] unless a session is running;
        /// [`TlsError::Tls`] if `rustls` refuses the export.
        pub fn export_keying_material(
            &self,
            out: &mut [u8],
            label: &[u8],
            context: Option<&[u8]>,
        ) -> Result<(), TlsError<T::Error>> {
            match &self.state {
                State::Tls(s) => s
                    .export_keying_material(out, label, context)
                    .map_err(TlsError::Tls),
                State::Plain(_) | State::Broken => Err(TlsError::NotAvailable),
            }
        }

        /// Send `close_notify`, if there is a session to close.
        ///
        /// Not required — a device is content with a plain FIN — and
        /// not done on drop, because dropping cannot await. It leaves
        /// the transport underneath open; a write to the session after it
        /// fails with [`TlsError::Closed`]. On a session that has already
        /// failed it sends the alert for that failure instead, if the
        /// socket takes it, and returns the failure.
        pub async fn shutdown(&mut self) -> Result<(), TlsError<T::Error>> {
            match &mut self.state {
                State::Tls(s) => s.shutdown().await,
                State::Plain(_) | State::Broken => Ok(()),
            }
        }
    }

    impl<T: Read + Write> ErrorType for MaybeTls<T> {
        type Error = TlsError<T::Error>;
    }

    impl<T: Read + Write> Read for MaybeTls<T> {
        async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
            match &mut self.state {
                State::Plain(t) => t.read(buf).await.map_err(TlsError::Io),
                State::Tls(s) => s.read(buf).await,
                State::Broken => Err(TlsError::NotAvailable),
            }
        }
    }

    impl<T: Read + Write> Write for MaybeTls<T> {
        async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
            match &mut self.state {
                State::Plain(t) => t.write(buf).await.map_err(TlsError::Io),
                State::Tls(s) => s.write(buf).await,
                State::Broken => Err(TlsError::NotAvailable),
            }
        }

        async fn flush(&mut self) -> Result<(), Self::Error> {
            match &mut self.state {
                State::Plain(t) => t.flush().await.map_err(TlsError::Io),
                State::Tls(s) => s.flush().await,
                State::Broken => Err(TlsError::NotAvailable),
            }
        }
    }

    impl<T: Read + Write> sealed::Sealed for MaybeTls<T> {}

    impl<T: Read + Write> StartTls for MaybeTls<T> {
        async fn start_tls(&mut self, config: &TlsClientConfig) -> Result<(), Self::Error> {
            // `Broken` stands in while the value is out of `&mut self`, and
            // stays if the handshake fails or this future is dropped.
            // Anything else goes back untouched.
            let inner = match core::mem::replace(&mut self.state, State::Broken) {
                State::Plain(inner) => inner,
                other => {
                    self.state = other;
                    return Err(TlsError::NotAvailable);
                }
            };

            let mut session = TlsSession::new(inner, config)?;
            session.handshake().await?;
            self.state = State::Tls(session);
            Ok(())
        }

        fn is_key_rejected(error: &Self::Error) -> bool {
            error.is_key_rejected()
        }
    }

    impl<T> ReadCancelSafety for MaybeTls<T>
    where
        T: Read + Write + ReadCancelSafety,
    {
        /// A dropped TLS read loses nothing of its own: the ciphertext it
        /// took and any failure it met both live in the session, set down
        /// before anything awaits. What is left belongs to the transport
        /// underneath.
        fn read_cancel_safe(&self) -> bool {
            match &self.state {
                State::Plain(t) => t.read_cancel_safe(),
                State::Tls(s) => s.inner.read_cancel_safe(),
                State::Broken => false,
            }
        }
    }

    impl<T, U> sealed::Sealed for Transport<MaybeTls<T>, U>
    where
        T: Read + Write,
        U: Read + Write,
    {
    }

    impl<T, U> StartTls for Transport<MaybeTls<T>, U>
    where
        T: Read + Write,
        U: Read + Write,
    {
        async fn start_tls(&mut self, config: &TlsClientConfig) -> Result<(), Self::Error> {
            match self {
                Self::Tcp(t) => t
                    .start_tls(config)
                    .await
                    .map_err(crate::transport::common::TransportError::Tcp),
                // adbd never offers STLS over USB.
                Self::Usb(_) => Err(crate::transport::common::TransportError::Tcp(
                    TlsError::NotAvailable,
                )),
            }
        }

        fn is_key_rejected(error: &Self::Error) -> bool {
            match error {
                crate::transport::common::TransportError::Tcp(e) => e.is_key_rejected(),
                crate::transport::common::TransportError::Usb(_) => false,
            }
        }
    }

    impl<T: Read + Write, U> Transport<T, U> {
        /// Wrap a TCP transport in [`MaybeTls`] so that it can start TLS
        /// later, starting none now. A USB transport passes through as it
        /// is: adbd never offers TLS there, and `start_tls` on it fails
        /// with [`TlsError::NotAvailable`], wrapped in `TransportError::Tcp`
        /// as every TLS error is.
        pub fn tls_ready(self) -> Transport<MaybeTls<T>, U> {
            match self {
                Self::Tcp(t) => Transport::Tcp(MaybeTls::plain(t)),
                Self::Usb(u) => Transport::Usb(u),
            }
        }
    }

    /// What both halves of a split session share: the engine, and the
    /// failure it met.
    ///
    /// Each half takes `conn` only while rustls works, never across a
    /// wait on the socket, so neither can hold the other up.
    struct TlsShared {
        conn: async_lock::Mutex<Box<ClientConnection>>,
        /// The failure the session met, kept so that every later call
        /// reports it too; only a write after `shutdown` reports `Closed`
        /// instead. The reader sets it under `conn`, where a writer looks
        /// before it hands rustls anything, so none slips past.
        failed: OnceLock<rustls::Error>,
    }

    /// The read half of a TLS session.
    pub struct TlsReadHalf<T: Splittable> {
        inner: T::ReadHalf,
        inbound: Inbound,
        shared: Arc<TlsShared>,
    }

    /// The write half of a TLS session.
    ///
    /// Writes queue and `flush` sends, as for [`MaybeTls`]; see there
    /// under *Cancellation*. Only this half sends: what a dropped `flush`
    /// leaves waits for its next write or flush.
    pub struct TlsWriteHalf<T: Splittable> {
        half: T::WriteHalf,
        /// Records sealed and not yet written, advanced past whatever the
        /// socket took, so a dropped call resumes where it stopped.
        pending: BytesMut,
        /// Whether `shutdown` has been called. Writes are refused from
        /// then on, as the `close_notify` may already be queued.
        closed: bool,
        shared: Arc<TlsShared>,
    }

    impl<T: Splittable> ErrorType for TlsReadHalf<T> {
        type Error = TlsError<T::Error>;
    }

    impl<T: Splittable> ErrorType for TlsWriteHalf<T> {
        type Error = TlsError<T::Error>;
    }

    impl<T: Splittable> Read for TlsReadHalf<T> {
        async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
            if buf.is_empty() {
                return Ok(0);
            }
            loop {
                // Plaintext first.
                {
                    let mut conn = self.shared.conn.lock().await;
                    match take_plaintext(&mut conn, buf) {
                        Plain::Got(n) => return Ok(n),
                        Plain::Eof => return Ok(0),
                        Plain::Blocked => {}
                    }
                }
                // What decrypted ahead of a failure is read before it.
                if let Some(e) = self.shared.failed.get() {
                    return Err(TlsError::Tls(e.clone()));
                }

                // Decrypt what is in hand before going back to the socket, or
                // the tail of a closed stream is lost as a clean end of file.
                if !self.inbound.rx.is_empty() {
                    let fed = {
                        let mut conn = self.shared.conn.lock().await;
                        // Kept under `conn`, where the writer looks. The alert
                        // rustls raises stays queued in the engine for the
                        // writer to carry: nothing on the read side writes.
                        feed(&mut conn, &mut self.inbound.rx).inspect_err(|e| {
                            let _ = self.shared.failed.set(e.clone());
                        })
                    };
                    match fed {
                        // A safeguard: `take_plaintext` above reports a
                        // `close_notify` first.
                        Ok(0) => return Ok(0),
                        // A failure is kept, and reported once what decrypted
                        // ahead of it has been read.
                        Ok(_) | Err(_) => continue,
                    }
                }

                if self.inbound.eof {
                    return Ok(0);
                }
                self.inbound.fill(&mut self.inner).await?;
            }
        }
    }

    impl<T: Splittable> TlsWriteHalf<T> {
        /// Run `f` on the engine and queue every record it, and anything
        /// before it, produced.
        ///
        /// Once the session has failed, `f` does not run: what gets queued
        /// is the alert for the failure, and the failure is the answer.
        async fn queue<R>(
            &mut self,
            f: impl FnOnce(&mut ClientConnection) -> R,
        ) -> Result<R, rustls::Error> {
            let mut conn = self.shared.conn.lock().await;
            let result = match self.shared.failed.get() {
                Some(e) => Err(e.clone()),
                None => Ok(f(&mut conn)),
            };
            harvest(&mut conn, &mut self.pending);
            result
        }

        /// Write out the queue and flush the half underneath, resuming
        /// where a dropped call stopped.
        async fn drain(&mut self) -> Result<(), TlsError<T::Error>> {
            send_queue(&mut self.half, &mut self.pending).await?;
            self.half.flush().await.map_err(TlsError::Io)
        }

        /// [`queue`](Self::queue) what `f` produces and send it all. A
        /// failed session sends the alert for its failure, if the socket
        /// takes it, and answers with the failure either way.
        async fn push_with<R>(
            &mut self,
            f: impl FnOnce(&mut ClientConnection) -> R,
        ) -> Result<R, TlsError<T::Error>> {
            let result = self.queue(f).await;
            let drained = self.drain().await;
            match result {
                Ok(result) => drained.map(|()| result),
                Err(e) => Err(TlsError::Tls(e)),
            }
        }

        /// Send `close_notify` and push it out.
        ///
        /// Not required — a device is content with a plain FIN — and
        /// not done on drop, because dropping cannot await. Without it a
        /// peer cannot tell a connection we closed from one cut short.
        ///
        /// It leaves the transport underneath open, and a write after it
        /// fails with [`TlsError::Closed`]. On a session that has already
        /// failed it sends the alert for that failure instead, if the
        /// socket takes it, and returns the failure.
        pub async fn shutdown(&mut self) -> Result<(), TlsError<T::Error>> {
            // Up front: a shutdown dropped part way may already have
            // queued the `close_notify`, and nothing may follow it.
            self.closed = true;
            self.push_with(|conn| conn.send_close_notify()).await
        }
    }

    impl<T: Splittable> Write for TlsWriteHalf<T> {
        /// Seals `buf` into the queue, as [`MaybeTls`]'s `write` does.
        async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
            if buf.is_empty() {
                return Ok(0);
            }
            if self.closed {
                return Err(TlsError::Closed);
            }
            if self.pending.len() >= QUEUE_LIMIT {
                send_queue(&mut self.half, &mut self.pending).await?;
            }
            match self.queue(|conn| write_plain(conn, buf)).await {
                Ok(written) => written,
                // The alert for the failure is queued; it goes out now, if
                // the socket takes it.
                Err(e) => {
                    let _ = self.drain().await;
                    Err(TlsError::Tls(e))
                }
            }
        }

        async fn flush(&mut self) -> Result<(), Self::Error> {
            self.push_with(|_| ()).await
        }
    }

    impl<T> ReadCancelSafety for TlsReadHalf<T>
    where
        T: Splittable,
        T::ReadHalf: ReadCancelSafety,
    {
        fn read_cancel_safe(&self) -> bool {
            self.inner.read_cancel_safe()
        }
    }

    /// The read half of a [`MaybeTls`], plain or encrypted.
    pub enum MaybeTlsRead<T: Splittable> {
        /// No TLS was started: the plain transport's read half.
        Plain(T::ReadHalf),
        /// The read half of the running TLS session.
        Tls(TlsReadHalf<T>),
    }

    /// The write half of a [`MaybeTls`], plain or encrypted.
    ///
    /// Encrypted, writes queue and `flush` sends; see [`MaybeTls`] under
    /// *Cancellation*.
    pub enum MaybeTlsWrite<T: Splittable> {
        /// No TLS was started: the plain transport's write half.
        Plain(T::WriteHalf),
        /// The write half of the running TLS session.
        Tls(TlsWriteHalf<T>),
    }

    impl<T: Splittable> ErrorType for MaybeTlsRead<T> {
        type Error = TlsError<T::Error>;
    }

    impl<T: Splittable> ErrorType for MaybeTlsWrite<T> {
        type Error = TlsError<T::Error>;
    }

    impl<T: Splittable> Read for MaybeTlsRead<T> {
        async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
            match self {
                Self::Plain(t) => t.read(buf).await.map_err(TlsError::Io),
                Self::Tls(t) => t.read(buf).await,
            }
        }
    }

    impl<T: Splittable> MaybeTlsWrite<T> {
        /// Send `close_notify`, if there is a session to close.
        ///
        /// [`MaybeTls::shutdown`] for a transport that has been split,
        /// and [`TlsWriteHalf::shutdown`] underneath.
        pub async fn shutdown(&mut self) -> Result<(), TlsError<T::Error>> {
            match self {
                Self::Plain(_) => Ok(()),
                Self::Tls(t) => t.shutdown().await,
            }
        }
    }

    impl<T: Splittable> Write for MaybeTlsWrite<T> {
        async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
            match self {
                Self::Plain(t) => t.write(buf).await.map_err(TlsError::Io),
                Self::Tls(t) => t.write(buf).await,
            }
        }

        async fn flush(&mut self) -> Result<(), Self::Error> {
            match self {
                Self::Plain(t) => t.flush().await.map_err(TlsError::Io),
                Self::Tls(t) => t.flush().await,
            }
        }
    }

    impl<T> ReadCancelSafety for MaybeTlsRead<T>
    where
        T: Splittable,
        T::ReadHalf: ReadCancelSafety,
    {
        fn read_cancel_safe(&self) -> bool {
            match self {
                Self::Plain(t) => t.read_cancel_safe(),
                Self::Tls(t) => t.read_cancel_safe(),
            }
        }
    }

    impl<T: Splittable> Splittable for MaybeTls<T> {
        type ReadHalf = MaybeTlsRead<T>;
        type WriteHalf = MaybeTlsWrite<T>;

        fn split(self) -> Result<(Self::ReadHalf, Self::WriteHalf), Self::Error> {
            match self.state {
                State::Plain(t) => {
                    let (r, w) = t.split().map_err(TlsError::Io)?;
                    Ok((MaybeTlsRead::Plain(r), MaybeTlsWrite::Plain(w)))
                }
                State::Tls(session) => {
                    let TlsSession {
                        inner,
                        conn,
                        inbound,
                        tx,
                        failed,
                        closed,
                    } = session;
                    let (r, w) = inner.split().map_err(TlsError::Io)?;
                    let shared = Arc::new(TlsShared {
                        conn: async_lock::Mutex::new(conn),
                        failed: failed.map(OnceLock::from).unwrap_or_default(),
                    });
                    let read = TlsReadHalf {
                        inner: r,
                        inbound,
                        shared: Arc::clone(&shared),
                    };
                    let write = TlsWriteHalf {
                        half: w,
                        pending: tx,
                        closed,
                        shared,
                    };
                    Ok((MaybeTlsRead::Tls(read), MaybeTlsWrite::Tls(write)))
                }
                State::Broken => Err(TlsError::NotAvailable),
            }
        }
    }
}