Skip to main content

netio/tls/
mod.rs

1// tls -- TLS 1.3 servers and clients, and TLS 1.2 towards public servers (RFC 8446, 5246)
2//
3//   Both sides: TLS 1.3 · ChaCha20-Poly1305, AES-128-GCM, AES-256-GCM · X25519MLKEM768
4//   (post-quantum hybrid), X25519, P-256, P-384 · certificates and keys of Ed25519, ECDSA
5//   (P-256 / P-384) and RSA (the web PKI or a CA of one's own) · mutual authentication ·
6//   HelloRetryRequest · KeyUpdate · resumption with session tickets (psk_dhe_ke) · 0-RTT with
7//   replay protection (opt-in) · OCSP stapling (status_request, RFC 6066 8 / RFC 8446 4.4.2.1).
8//   Public servers (client side, Trust::System / Custom): also TLS 1.2 with ECDHE and AEAD suites.
9//   Not here: external PSKs, psk_ke, TLS 1.2 resumption, renegotiation, OCSP or CRLs fetched by
10//   the client itself.
11//
12//   connect(stream, ClientConfig) -> TlsStream     accept(stream, ServerConfig) -> TlsStream
13//   TlsStream implements Stream (HTTP runs over it unchanged); peer_certs() after the handshake
14//   Resumption: ServerConfig::tickets (Tickets: keys, lifetime), ClientConfig::sessions
15//   (Sessions: a client's tickets per server); TlsStream::resumed()
16//   0-RTT: ServerConfig::early_data (bytes; 0 = none), connect_early(stream, cfg, data) ->
17//   (TlsStream, bytes taken), TlsStream::read_early (a server: data that may be a replay)
18//   OCSP: ServerConfig::ocsp (Staples: the responses to staple, netio::ocsp::refresh fetches
19//   them); ClientConfig::revocation (Revocation::Stapled by default: a stapled response is
20//   checked, a revoked certificate refused); TlsStream::ocsp_response
21//   Identity::new(chain, key) / Identity::from_pem(certs, key): a chain and its key (PrivateKey:
22//   Ed25519, ECDSA, RSA; PKCS #8, SEC 1, PKCS #1)
23//   Trust::Anchors(CAs) / Pinned(SHA-256 of the leaf) / Any (trust on first use: the caller
24//   shows the fingerprint and pins it) / System(extra CAs) (the operating system's check, the
25//   extra CAs under its policy) / Dane(TLSA records) (RFC 6698, 7671: crate::dane)
26//
27// conn.rs is the I/O-free core (feed bytes, take bytes); this file drives it over a Stream.
28
29pub mod conn;
30pub mod keysched;
31pub mod kx;
32pub mod record;
33pub mod session;
34pub mod staple;
35
36use alloc::boxed::Box;
37use alloc::sync::Arc;
38use alloc::format;
39use alloc::string::String;
40use alloc::vec::Vec;
41
42use plat::net::{NetError, NetErrorKind, NetResult};
43use plat::sync::Mutex;
44
45use crate::x509::{Cert, PrivateKey};
46use crate::Stream;
47
48pub use conn::Conn;
49pub use session::{ReplayCheck, Sessions, Tickets};
50pub use staple::Staples;
51
52/// a certificate chain (DER, leaf first) and the leaf's private key (Ed25519, ECDSA, RSA)
53#[derive(Clone)]
54pub struct Identity {
55    pub chain: Vec<Vec<u8>>,
56    pub key: PrivateKey,
57}
58
59impl Identity {
60    /// a chain (DER, leaf first) and its key (an ed25519::Keypair or an x509::PrivateKey)
61    pub fn new(chain: Vec<Vec<u8>>, key: impl Into<PrivateKey>) -> Identity {
62        Identity { chain, key: key.into() }
63    }
64
65    /// from PEM: the certificates (leaf first, as a CA hands them out) and the key ("PRIVATE
66    /// KEY", "EC PRIVATE KEY" or "RSA PRIVATE KEY"; not an encrypted one); the key must be the
67    /// leaf's
68    pub fn from_pem(certs: &str, key: &str) -> Result<Identity, String> {
69        let chain = crate::pem::decode_all(certs, "CERTIFICATE");
70        let leaf = chain.first().and_then(|c| Cert::parse(c)).ok_or_else(|| String::from("no certificate"))?;
71        let der = ["PRIVATE KEY", "EC PRIVATE KEY", "RSA PRIVATE KEY"].iter().find_map(|l| crate::pem::decode(key, l));
72        let Some(mut der) = der else {
73            return Err(String::from(if key.contains("ENCRYPTED") { "an encrypted key (decrypt it first)" } else { "no private key" }));
74        };
75        let k = PrivateKey::from_der(&der);
76        crypto::zeroize(&mut der);
77        let k = k.ok_or_else(|| String::from("a private key of a kind not taken here"))?;
78        if k.public_key() != leaf.key {
79            return Err(String::from("the key is not the certificate's"));
80        }
81        Ok(Identity { chain, key: k })
82    }
83}
84
85#[derive(Clone)]
86#[non_exhaustive]
87pub enum Trust {
88    /// certificates issued by one of these CAs
89    Anchors(Vec<Cert>),
90    /// exactly these leaf certificates (SHA-256 of the DER)
91    Pinned(Vec<[u8; 32]>),
92    /// anything (only to read the fingerprint for a trust decision)
93    Any,
94    /// the operating system's certificate authorities, and these as well (a company CA): the
95    /// system checks the chain (Windows CryptoAPI, Apple's Security framework with the stapled
96    /// OCSP response; on Linux the distribution's bundle: crate::roots), these under its own
97    /// policy (Windows with them as its roots where its own give no path, Apple as anchors
98    /// beside its own; Linux where the bundle gives no path); the alert follows its reason
99    /// (expired, revoked, another name or usage, unknown CA).  Allows TLS 1.2 and the public
100    /// suites
101    System(Vec<Cert>),
102    /// a check the program brings (a PKI of its own, keys pinned by their SPKI, Certificate
103    /// Transparency, the platform's verifier, a test peer); a client offers with it what it
104    /// offers with System (TLS 1.2, the public suites)
105    Custom(Verifier),
106    /// DANE: the server's TLSA records, from a lookup DNSSEC found secure (crate::dane::lookup,
107    /// dane::trust): DANE-EE the server's key itself, DANE-TA a CA of its chain, PKIX-TA /
108    /// PKIX-EE with the system's check (crate::dane::check, RFC 7671); without a usable record
109    /// the system's check alone.  Revocation and the stapled response count where the system's
110    /// check decides, as with System, not for DANE-EE and DANE-TA.  Allows TLS 1.2 and the
111    /// public suites, as System
112    Dane(Vec<crate::dane::Tlsa>),
113}
114
115/// the check of Trust::Custom: the certificates the peer sent that could be read (leaf first),
116/// the name the client asked for ("" for a client's certificate) and the time (Unix seconds) ->
117/// Ok, or why they are refused (the handshake ends with bad_certificate)
118pub type Verifier = Arc<dyn Fn(&[Cert], &str, i64) -> Result<(), String> + Send + Sync>;
119
120/// a client's side: `ClientConfig { identity: Some(id), ..ClientConfig::new(trust, "host") }`
121#[derive(Clone)]
122pub struct ClientConfig {
123    pub trust: Trust,
124    pub identity: Option<Identity>,
125    /// the name the certificate must carry (DNS name or IP address); may be empty only with
126    /// Trust::Pinned / Trust::Any, which do not check it
127    pub server_name: String,
128    /// the application protocols to offer (ALPN, RFC 7301: "h2", "http/1.1", "acme-tls/1"),
129    /// in order of preference; the server's choice is TlsStream::alpn.  An empty name or one
130    /// over 255 bytes is left out, and the names after the first 8 KiB of them; none left: no
131    /// ALPN offered
132    pub alpn: Vec<String>,
133    /// session tickets to resume with (TLS 1.3): the connection offers one of this server and
134    /// keeps the ones it gets.  Several configs may share a cache: it keeps the tickets by
135    /// server name, trust and client identity.  None: no resumption
136    pub sessions: Option<Arc<Sessions>>,
137    /// what a stapled OCSP response decides (with Trust::Anchors, System and Custom; a pinned
138    /// certificate or Trust::Any asks for none)
139    pub revocation: Revocation,
140}
141
142impl ClientConfig {
143    /// this trust and server name; no client certificate, no ALPN, no resumption; stapled OCSP
144    /// responses checked (Revocation::Stapled)
145    pub fn new(trust: Trust, server_name: &str) -> ClientConfig {
146        ClientConfig { trust, identity: None, server_name: String::from(server_name), alpn: Vec::new(), sessions: None, revocation: Revocation::Stapled }
147    }
148}
149
150/// the OCSP response a client asks the server to staple (status_request): a usable one is
151/// signed by the issuer of the server's certificate (in the chain or an anchor) or a responder
152/// it named, about that certificate, and current (RFC 6960; x509::ocsp::check)
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154#[non_exhaustive]
155pub enum Revocation {
156    /// none asked for
157    Off,
158    /// asked for and checked: a certificate a usable response calls revoked is refused
159    /// (certificate_revoked); without a usable response the handshake goes on, unless the
160    /// certificate must be stapled (RFC 7633, Cert::must_staple)
161    Stapled,
162    /// a usable response that says good is required (bad_certificate_status_response without one)
163    Required,
164}
165
166/// what a ClientHello asks for: the program's ServerConfig::select picks the identity by it
167#[derive(Clone, Debug)]
168pub struct Hello {
169    /// the name of server_name (SNI), lower case; empty: none
170    pub server_name: String,
171    /// the application protocols offered (ALPN), as the client sent them: byte strings
172    /// (RFC 7301 3.1), b"h2", b"http/1.1"
173    pub alpn: Vec<Vec<u8>>,
174    /// the signature schemes the client takes (TLS code points)
175    pub sig_algs: Vec<u16>,
176}
177
178/// ServerConfig::select: the identity for a ClientHello, or None for the configured ones
179pub type Select = Arc<dyn Fn(&Hello) -> Option<Identity> + Send + Sync>;
180
181/// a server's side: `ServerConfig { client_auth: Some(trust), ..ServerConfig::new(identity) }`
182#[derive(Clone)]
183pub struct ServerConfig {
184    pub identity: Identity,
185    /// more certificates (SNI: other names; or other key types for the same name, as an ECDSA
186    /// and an RSA certificate): the server shows the first of these and then `identity` that
187    /// names the server_name the client asked for and whose key makes a signature the client
188    /// takes; without such one `identity`, or the first whose key fits when its key does not
189    pub identities: Vec<Identity>,
190    /// a choice of the program's own, asked before the lists (certificates renewed while the
191    /// server runs, ACME's tls-alpn-01 challenge); None from it: the lists decide
192    pub select: Option<Select>,
193    /// ask for a client certificate trusted like this
194    pub client_auth: Option<Trust>,
195    /// a client without a certificate is accepted too (one that sends one must pass the
196    /// check); for a port that consoles and agents share
197    pub client_auth_optional: bool,
198    /// the application protocols the server speaks (ALPN), in its order of preference; a
199    /// client that offers protocols, none of them these, is refused (no_application_protocol,
200    /// RFC 7301 3.2).  Empty: ALPN is not answered.  "acme-tls/1" (RFC 8737, acme::TlsAlpn01)
201    /// counts only for a client that offers it alone
202    pub alpn: Vec<String>,
203    /// session tickets (TLS 1.3 resumption): sent after each handshake and taken back for a
204    /// handshake without certificates.  A resumed connection keeps the client certificates of
205    /// its first handshake (peer_certs) for up to 7 days, while the same client_auth trust asks
206    /// for them and takes them again (each resumption checks them).  None: no tickets
207    pub tickets: Option<Arc<Tickets>>,
208    /// 0-RTT (needs tickets): the most bytes of early data a client may send with a ticket; 0
209    /// (the default): none.  A ticket that allows more than the server takes now is resumed
210    /// without 0-RTT.  Early data can be replayed by an attacker (RFC 8446 8, E.5): the
211    /// server takes it only from a ClientHello within 10 seconds of the ticket's age and the
212    /// first time it comes (Tickets::replay_check), keeps it apart (TlsStream::read_early) and
213    /// hands it to read() only once the handshake is done.  With 0-RTT taken, accept returns
214    /// after the server's flight, before the client's Finished
215    pub early_data: u32,
216    /// the OCSP responses to staple for the certificates shown, to clients that ask for one
217    /// (netio::ocsp::refresh keeps them current).  None: no stapling
218    pub ocsp: Option<Arc<Staples>>,
219}
220
221impl ServerConfig {
222    /// this identity; no client certificates, no ALPN, no tickets
223    pub fn new(identity: Identity) -> ServerConfig {
224        ServerConfig {
225            identity,
226            identities: Vec::new(),
227            select: None,
228            client_auth: None,
229            client_auth_optional: false,
230            alpn: Vec::new(),
231            tickets: None,
232            early_data: 0,
233            ocsp: None,
234        }
235    }
236}
237
238#[derive(Clone, Copy, Debug, PartialEq, Eq)]
239#[non_exhaustive]
240pub enum TlsError {
241    /// we ended the connection with this alert
242    Alert(u8, &'static str),
243    /// the peer ended it with this alert
244    PeerAlert(u8),
245    Net(NetError),
246    Closed,
247}
248
249impl core::fmt::Display for TlsError {
250    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
251        match self {
252            TlsError::Alert(a, why) => write!(f, "{} (alert {})", why, a),
253            TlsError::PeerAlert(a) => write!(f, "{} (von der Gegenseite)", alert_name(*a)),
254            TlsError::Net(e) => write!(f, "{}", e),
255            TlsError::Closed => f.write_str("Verbindung geschlossen"),
256        }
257    }
258}
259
260pub fn alert_name(a: u8) -> String {
261    String::from(match a {
262        conn::AL_HANDSHAKE_FAILURE => "Handshake abgelehnt",
263        conn::AL_BAD_CERTIFICATE => "Zertifikat abgelehnt",
264        conn::AL_UNKNOWN_CA => "unbekannte Zertifizierungsstelle",
265        conn::AL_CERTIFICATE_EXPIRED => "Zertifikat abgelaufen",
266        conn::AL_CERTIFICATE_REQUIRED => "Client-Zertifikat erforderlich",
267        conn::AL_DECRYPT_ERROR => "Prüfsumme falsch",
268        conn::AL_PROTOCOL_VERSION => "TLS-Version nicht unterstützt",
269        conn::AL_NO_APPLICATION_PROTOCOL => "kein gemeinsames Anwendungsprotokoll (ALPN)",
270        _ => return format!("TLS-Alert {}", a),
271    })
272}
273
274fn to_net(e: TlsError) -> NetError {
275    match e {
276        TlsError::Net(n) => n,
277        _ => NetError::new(NetErrorKind::Reset, 0),
278    }
279}
280
281/// TLS over a stream
282pub struct TlsStream {
283    inner: Box<dyn Stream>,
284    conn: Mutex<Conn>,
285    /// keeps whole records together when two threads write
286    wlock: Mutex<()>,
287    last_error: Mutex<Option<TlsError>>,
288    /// the read timeout of set_timeouts (u32::MAX: none): records that carry no data (empty
289    /// ones, KeyUpdates) end a read with TimedOut after it, as silence would
290    read_ms: core::sync::atomic::AtomicU32,
291    /// the write timeout of set_timeouts (u32::MAX: none), kept when a read shortens inner's
292    /// read timeout
293    write_ms: core::sync::atomic::AtomicU32,
294    /// the read timeout inner has now (u32::MAX: none)
295    inner_read_ms: core::sync::atomic::AtomicU32,
296}
297
298impl TlsStream {
299    fn new(inner: Box<dyn Stream>, conn: Conn) -> TlsStream {
300        let none = || core::sync::atomic::AtomicU32::new(u32::MAX);
301        TlsStream { inner, conn: Mutex::new(conn), wlock: Mutex::new(()), last_error: Mutex::new(None), read_ms: none(), write_ms: none(), inner_read_ms: none() }
302    }
303
304    /// Before the next read of inner in a read with a timeout (read_ms, begun at t0): past it,
305    /// TimedOut; otherwise the time it has left, as long as the wait for bytes and as inner's read
306    /// timeout (for a stream whose wait_readable does not wait).  Records without data, or a
307    /// record that comes in pieces, then do not keep a read going past its timeout
308    fn before_inner_read(&self, t0: u64, read_ms: u32) -> NetResult<()> {
309        use core::sync::atomic::Ordering::Relaxed;
310        if read_ms == u32::MAX {
311            return Ok(());
312        }
313        let spent = plat::time_us().saturating_sub(t0) / 1000;
314        if spent >= read_ms as u64 {
315            return Err(NetError::new(NetErrorKind::TimedOut, 0));
316        }
317        let rest = (read_ms as u64 - spent) as u32;
318        if self.inner_read_ms.swap(rest, Relaxed) != rest {
319            let w = self.write_ms.load(Relaxed);
320            self.inner.set_timeouts(Some(rest), (w != u32::MAX).then_some(w));
321        }
322        if !self.inner.wait_readable(rest) {
323            return Err(NetError::new(NetErrorKind::TimedOut, 0));
324        }
325        Ok(())
326    }
327
328    /// (tests) send an application data record without data
329    #[doc(hidden)]
330    pub fn test_send_empty_record(&self) -> NetResult<()> {
331        self.conn.lock().write_empty().map_err(to_net)?;
332        self.flush().map_err(to_net)
333    }
334
335    /// sends what the connection has sealed; taking it and writing it happen under wlock, so
336    /// records leave in the order of their sequence numbers
337    fn flush(&self) -> Result<(), TlsError> {
338        let _g = self.wlock.lock();
339        let out = self.conn.lock().take_out();
340        if out.is_empty() {
341            return Ok(());
342        }
343        self.inner.write_all(&out).map_err(TlsError::Net)
344    }
345
346    /// run until the handshake is done
347    fn handshake(&self) -> Result<(), TlsError> {
348        let mut buf = alloc::vec![0u8; 16 * 1024 + 512];
349        // the stream's timeout counts each read: a peer sending a byte at a time must not hold
350        // the connection (a server worker) forever
351        let deadline = plat::time_us() + 60_000_000;
352        loop {
353            self.flush()?;
354            {
355                let c = self.conn.lock();
356                if c.ready() {
357                    return Ok(());
358                }
359                if c.closed() {
360                    return Err(TlsError::Closed);
361                }
362            }
363            if plat::time_us() > deadline {
364                return Err(TlsError::Net(NetError::new(NetErrorKind::TimedOut, 0)));
365            }
366            let n = self.inner.read(&mut buf).map_err(TlsError::Net)?;
367            if n == 0 {
368                return Err(TlsError::Closed);
369            }
370            let r = self.conn.lock().feed(&buf[..n]);
371            if let Err(e) = r {
372                let _ = self.flush();
373                return Err(e);
374            }
375        }
376    }
377
378    /// the peer's certificate chain (leaf first)
379    pub fn peer_certs(&self) -> Vec<Cert> {
380        Vec::from(self.conn.lock().peer_certs())
381    }
382
383    pub fn last_error(&self) -> Option<TlsError> {
384        *self.last_error.lock()
385    }
386
387    /// "TLS 1.3" / "TLS 1.2" and the cipher suite number
388    pub fn version(&self) -> (&'static str, u16) {
389        let c = self.conn.lock();
390        (c.version(), c.suite())
391    }
392
393    /// the key exchange group (kx: X25519_MLKEM768, X25519, SECP256R1 ...)
394    pub fn group(&self) -> u16 {
395        self.conn.lock().group()
396    }
397
398    /// the application protocol both sides agreed on (ALPN), if any
399    pub fn alpn(&self) -> Option<String> {
400        self.conn.lock().alpn().map(String::from)
401    }
402
403    /// a server: the name the client asked for (SNI, lower case; empty: none)
404    pub fn server_name(&self) -> String {
405        String::from(self.conn.lock().server_name())
406    }
407
408    /// the handshake resumed a session (a ticket instead of certificates)
409    pub fn resumed(&self) -> bool {
410        self.conn.lock().resumed()
411    }
412
413    /// a client: the OCSP response the server stapled for its certificate (DER), when it sent
414    /// one; whether it was usable decided ClientConfig::revocation
415    pub fn ocsp_response(&self) -> Option<Vec<u8>> {
416        self.conn.lock().ocsp_response().map(Vec::from)
417    }
418
419    /// a server that took 0-RTT: the client's early data as it comes, before the handshake is
420    /// done; Ok(0) at its end (or when none was taken).  An attacker may have replayed it
421    /// (RFC 8446 8): act on it only where twice does no harm (RFC 8470).  What is not read here
422    /// comes first from read() once the handshake is done
423    pub fn read_early(&self, buf: &mut [u8]) -> NetResult<usize> {
424        let mut raw = alloc::vec![0u8; 16 * 1024 + 512];
425        let t0 = plat::time_us();
426        let read_ms = self.read_ms.load(core::sync::atomic::Ordering::Relaxed);
427        loop {
428            {
429                let mut c = self.conn.lock();
430                if c.has_early() {
431                    return Ok(c.read_early(buf));
432                }
433                if !c.in_early() || c.closed() {
434                    return Ok(0);
435                }
436            }
437            // records without data (empty ones) do not keep it going past the timeout, as read
438            self.before_inner_read(t0, read_ms)?;
439            let n = self.inner.read(&mut raw)?;
440            if n == 0 {
441                return Ok(0);
442            }
443            let r = self.conn.lock().feed(&raw[..n]);
444            let _ = self.flush();
445            if let Err(e) = r {
446                *self.last_error.lock() = Some(e);
447                return Err(to_net(e));
448            }
449        }
450    }
451}
452
453/// client side: handshake over `inner`
454pub fn connect(inner: Box<dyn Stream>, cfg: ClientConfig) -> Result<TlsStream, TlsError> {
455    let s = TlsStream::new(inner, Conn::client(cfg));
456    s.handshake()?;
457    Ok(s)
458}
459
460/// client side with 0-RTT: `early` goes right after the ClientHello when a ticket of
461/// cfg.sessions allows early data (as much as the ticket takes).  -> the stream and the bytes of
462/// `early` the server took: 0 when none went (no such ticket) or the server refused them; the
463/// caller sends the rest with write_all, if it still applies (TlsStream::alpn may differ: RFC
464/// 8446 4.2.10).  Early data can be replayed by an attacker: only for requests that do no harm
465/// twice
466pub fn connect_early(inner: Box<dyn Stream>, cfg: ClientConfig, early: &[u8]) -> Result<(TlsStream, usize), TlsError> {
467    let s = TlsStream::new(inner, Conn::client_early(cfg, early));
468    s.handshake()?;
469    let n = s.conn.lock().early_taken();
470    Ok((s, n))
471}
472
473/// server side: handshake over `inner`
474pub fn accept(inner: Box<dyn Stream>, cfg: ServerConfig) -> Result<TlsStream, TlsError> {
475    let s = TlsStream::new(inner, Conn::server(cfg));
476    s.handshake()?;
477    Ok(s)
478}
479
480impl Stream for TlsStream {
481    fn read(&self, buf: &mut [u8]) -> NetResult<usize> {
482        let mut raw = alloc::vec![0u8; 16 * 1024 + 512];
483        let t0 = plat::time_us();
484        let read_ms = self.read_ms.load(core::sync::atomic::Ordering::Relaxed);
485        loop {
486            {
487                let mut c = self.conn.lock();
488                if c.has_plain() {
489                    return Ok(c.read_plain(buf));
490                }
491                if c.closed() {
492                    return Ok(0);
493                }
494            }
495            // records without data, or a record that comes in pieces, do not keep a read going
496            // past the timeout: the next bytes are waited for only as long as it has left
497            self.before_inner_read(t0, read_ms)?;
498            let n = self.inner.read(&mut raw)?;
499            if n == 0 {
500                return Ok(0);
501            }
502            let r = self.conn.lock().feed(&raw[..n]);
503            let _ = self.flush(); // KeyUpdate answers, alerts
504            if let Err(e) = r {
505                *self.last_error.lock() = Some(e);
506                return Err(to_net(e));
507            }
508        }
509    }
510
511    fn write_all(&self, data: &[u8]) -> NetResult<()> {
512        self.conn.lock().write_plain(data).map_err(to_net)?;
513        self.flush().map_err(to_net)
514    }
515
516    fn set_timeouts(&self, read_ms: Option<u32>, write_ms: Option<u32>) {
517        use core::sync::atomic::Ordering::Relaxed;
518        self.read_ms.store(read_ms.unwrap_or(u32::MAX), Relaxed);
519        self.write_ms.store(write_ms.unwrap_or(u32::MAX), Relaxed);
520        self.inner_read_ms.store(read_ms.unwrap_or(u32::MAX), Relaxed);
521        self.inner.set_timeouts(read_ms, write_ms);
522    }
523
524    fn shutdown(&self) {
525        self.conn.lock().close();
526        let _ = self.flush();
527        self.inner.shutdown();
528    }
529
530    fn end_is_clean(&self) -> bool {
531        self.conn.lock().peer_closed()
532    }
533
534    fn wait_readable(&self, ms: u32) -> bool {
535        if self.conn.lock().has_plain() {
536            return true;
537        }
538        self.inner.wait_readable(ms)
539    }
540}