net-io 0.8.0

Network IO substrate for Rust: TCP, UDP and local-socket listeners, connection lifecycle, limits, graceful drain, PROXY protocol, and a TLS seam. Protocol-free and dependency-free.
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
//! The TLS seam: traits a TLS engine implements in its own crate.
//!
//! net-io carries no TLS code. The seam is in place and sans-IO: ciphertext is
//! decrypted inside the connection's own read buffer and plaintext is encrypted
//! straight into net-io's output buffer. The server integration arrives in
//! `0.4.0` behind the `tls` feature; the traits exist in every build.

use std::fmt;

use crate::info::ConnectionInfo;

/// Creates one [`TlsSession`] per admitted connection.
///
/// # Examples
///
/// ```
/// use net_io::{ConnectionInfo, NoTls, TlsAcceptor};
/// let info = ConnectionInfo::for_testing("127.0.0.1:1".parse().unwrap());
/// assert!(NoTls.session(&info).is_err());
/// ```
pub trait TlsAcceptor: Send + Sync + 'static {
    /// The per-connection session type.
    type Session: TlsSession;

    /// Called once per admitted connection, after PROXY and readmission, before any TLS byte is read.
    ///
    /// # Errors
    ///
    /// A [`TlsError`] refuses the connection (for example an acceptor at capacity).
    fn session(&self, info: &ConnectionInfo) -> Result<Self::Session, TlsError>;
}

/// One connection's TLS state machine. Never blocks, never does IO.
///
/// See `docs/API.md` (TLS seam) for how the server drives it.
pub trait TlsSession: Send + 'static {
    /// Ciphertext is in `input`; free space for records to send is `output`.
    ///
    /// # Errors
    ///
    /// A [`TlsError`]; `TlsFailure::HelloRefused` closes the connection with
    /// `CloseReason::HelloRefused`, anything else with `TlsFailed`.
    fn step<'i>(
        &mut self,
        input: &'i mut [u8],
        output: &mut [u8],
    ) -> Result<TlsProgress<'i>, TlsError>;

    /// Encrypts `plaintext` into `output`: all records or none.
    ///
    /// # Errors
    ///
    /// `TlsFailure::OutputFull` when `output` cannot hold every record.
    fn encrypt(&mut self, plaintext: &[u8], output: &mut [u8]) -> Result<usize, TlsError>;

    /// Writes `close_notify` into `output`.
    ///
    /// # Errors
    ///
    /// `TlsFailure::OutputFull` or `TlsFailure::State`.
    fn close(&mut self, output: &mut [u8]) -> Result<usize, TlsError>;

    /// The peer's transport closed: was the TLS stream ended cleanly?
    fn on_transport_closed(&mut self) -> TlsCloseKind;

    /// SNI, ALPN, version, and cipher suite; `Some` after the handshake.
    fn info(&self) -> Option<TlsInfo>;

    /// The smallest input buffer the session needs now.
    fn input_capacity_required(&self) -> usize;
}

/// What one [`TlsSession::step`] did.
#[must_use]
#[derive(Debug)]
pub struct TlsProgress<'i> {
    /// Input bytes the engine consumed.
    pub consumed: usize,
    /// Bytes the engine wrote at the start of `output`.
    pub written: usize,
    /// What the caller does next.
    pub event: TlsEvent<'i>,
}

/// The next thing the driver does after a step.
#[non_exhaustive]
#[derive(Debug)]
pub enum TlsEvent<'i> {
    /// Read more ciphertext, append it after the unconsumed bytes, call `step` again.
    NeedInput,
    /// Send the `written` bytes at the start of `output`, all of them.
    Transmit,
    /// The handshake finished; `info()` is now `Some`.
    HandshakeComplete,
    /// Plaintext decrypted in place; call `step` again for more.
    Data(&'i [u8]),
    /// Not enough room in `output`; flush and call again.
    OutputFull,
    /// `close_notify` was received.
    PeerClosed,
    /// Both directions are closed.
    Closed,
}

/// Whether a TLS stream ended with `close_notify`.
///
/// ```
/// assert_ne!(net_io::TlsCloseKind::Clean, net_io::TlsCloseKind::Unclean);
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TlsCloseKind {
    /// `close_notify` was seen.
    Clean,
    /// The transport closed without it.
    Unclean,
}

/// What failed in a TLS engine.
///
/// ```
/// assert_ne!(net_io::TlsFailure::Handshake, net_io::TlsFailure::HelloRefused);
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TlsFailure {
    /// The handshake failed.
    Handshake,
    /// The engine's hello hook refused the ClientHello.
    HelloRefused,
    /// The acceptor is at capacity.
    Capacity,
    /// The peer broke the protocol.
    Protocol,
    /// The output buffer is too small.
    OutputFull,
    /// The call is not valid in the session's state.
    State,
}

/// A TLS engine error: codes only, never secret material.
///
/// ```
/// use net_io::{TlsError, TlsFailure};
/// let e = TlsError::new(TlsFailure::HelloRefused, 3, None);
/// assert_eq!(e.kind, TlsFailure::HelloRefused);
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TlsError {
    /// What failed.
    pub kind: TlsFailure,
    /// The engine's own code.
    pub code: u16,
    /// The TLS alert sent or received, if any.
    pub alert: Option<u8>,
}

impl TlsError {
    /// Builds an error.
    #[must_use]
    pub const fn new(kind: TlsFailure, code: u16, alert: Option<u8>) -> TlsError {
        TlsError { kind, code, alert }
    }
}

impl fmt::Display for TlsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?} (engine code {}", self.kind, self.code)?;
        if let Some(alert) = self.alert {
            write!(f, ", alert {alert}")?;
        }
        f.write_str(")")
    }
}

impl std::error::Error for TlsError {}

/// TLS facts after the handshake, in fixed arrays.
///
/// ```
/// let info = net_io::TlsInfo::new(Some("example.com"), Some(b"h2"), 0x0304, 0x1301).unwrap();
/// assert_eq!(info.sni(), Some("example.com"));
/// assert!(net_io::TlsInfo::new(Some(&"a".repeat(256)), None, 0, 0).is_none());
/// assert_eq!(info.peer_spki_sha256(), None);
/// let mutual = info.with_peer_spki_sha256([7; 32]);
/// assert_eq!(mutual.peer_spki_sha256(), Some(&[7; 32]));
/// ```
#[non_exhaustive]
#[derive(Clone, Copy)]
pub struct TlsInfo {
    sni: [u8; 255],
    sni_len: u8,
    alpn: [u8; 32],
    alpn_len: u8,
    version: u16,
    cipher_suite: u16,
    peer_spki: Option<[u8; 32]>,
}

impl TlsInfo {
    /// Builds the facts; `None` if the SNI is longer than 255 bytes or the ALPN longer than 32.
    #[must_use]
    pub fn new(
        sni: Option<&str>,
        alpn: Option<&[u8]>,
        version: u16,
        cipher_suite: u16,
    ) -> Option<TlsInfo> {
        let sni = sni.unwrap_or("").as_bytes();
        let alpn = alpn.unwrap_or(&[]);
        if sni.len() > 255 || alpn.len() > 32 {
            return None;
        }
        let mut info = TlsInfo {
            sni: [0; 255],
            sni_len: u8::try_from(sni.len()).ok()?,
            alpn: [0; 32],
            alpn_len: u8::try_from(alpn.len()).ok()?,
            version,
            cipher_suite,
            peer_spki: None,
        };
        info.sni[..sni.len()].copy_from_slice(sni);
        info.alpn[..alpn.len()].copy_from_slice(alpn);
        Some(info)
    }

    /// The server name the client asked for.
    #[must_use]
    pub fn sni(&self) -> Option<&str> {
        if self.sni_len == 0 {
            return None;
        }
        std::str::from_utf8(&self.sni[..usize::from(self.sni_len)]).ok()
    }

    /// The negotiated application protocol.
    #[must_use]
    pub fn alpn(&self) -> Option<&[u8]> {
        (self.alpn_len > 0).then(|| &self.alpn[..usize::from(self.alpn_len)])
    }

    /// The protocol version code (for example `0x0304` for TLS 1.3).
    #[must_use]
    pub fn version(&self) -> u16 {
        self.version
    }

    /// The cipher suite code.
    #[must_use]
    pub fn cipher_suite(&self) -> u16 {
        self.cipher_suite
    }

    /// The facts with the SHA-256 of the client certificate's public key
    /// (its DER `SubjectPublicKeyInfo`). The engine sets it only for a client
    /// certificate it verified (the chain, or a pin), never from unverified bytes.
    #[must_use]
    pub fn with_peer_spki_sha256(mut self, hash: [u8; 32]) -> TlsInfo {
        self.peer_spki = Some(hash);
        self
    }

    /// The SHA-256 of the verified client certificate's public key, for mapping a
    /// mutual-TLS peer to a principal; `None` without a client certificate. It
    /// stays the same when the certificate is reissued with the same key.
    #[must_use]
    pub fn peer_spki_sha256(&self) -> Option<&[u8; 32]> {
        self.peer_spki.as_ref()
    }
}

impl fmt::Debug for TlsInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TlsInfo")
            .field("sni", &self.sni())
            .field("alpn", &self.alpn().map(String::from_utf8_lossy))
            .field("version", &format_args!("{:#06x}", self.version))
            .field("cipher_suite", &format_args!("{:#06x}", self.cipher_suite))
            .field("peer_spki_sha256", &self.peer_spki.map(Hex))
            .finish()
    }
}

/// Bytes printed as lowercase hex.
struct Hex([u8; 32]);

impl fmt::Debug for Hex {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.iter().try_for_each(|b| write!(f, "{b:02x}"))
    }
}

/// The builder's default acceptor: no listener may enable TLS with it.
///
/// ```
/// use net_io::{ConnectionInfo, NoTls, TlsAcceptor};
/// let info = ConnectionInfo::for_testing("127.0.0.1:1".parse().unwrap());
/// assert!(NoTls.session(&info).is_err());
/// ```
#[derive(Clone, Copy, Debug, Default)]
pub struct NoTls;

/// An acceptor behind a pointer: sessions come back boxed.
#[cfg_attr(not(feature = "tls"), allow(dead_code))]
pub(crate) trait ErasedAcceptor: Send + Sync {
    fn session_boxed(&self, info: &ConnectionInfo) -> Result<Box<dyn TlsSession>, TlsError>;
}

impl<A: TlsAcceptor> ErasedAcceptor for A {
    fn session_boxed(&self, info: &ConnectionInfo) -> Result<Box<dyn TlsSession>, TlsError> {
        match crate::gate::guarded(|| self.session(info)) {
            Some(Ok(s)) => Ok(Box::new(Guarded {
                inner: Box::new(s),
                poisoned: false,
            })),
            Some(Err(e)) => Err(e),
            None => Err(PANICKED),
        }
    }
}

/// The error a panicking engine call becomes.
const PANICKED: TlsError = TlsError::new(TlsFailure::State, u16::MAX, None);

/// An engine behind a panic boundary: a panic in any call becomes [`PANICKED`] and
/// every later call fails the same way, so the connection closes `TlsFailed` through
/// the normal close path and its worker, slots, and ticket survive. The engine parses
/// the most hostile bytes a connection carries; this keeps one engine bug from
/// taking a worker with it. No cost unless a panic unwinds.
struct Guarded {
    inner: Box<dyn TlsSession>,
    poisoned: bool,
}

impl Guarded {
    fn call<R>(
        &mut self,
        f: impl FnOnce(&mut dyn TlsSession) -> Result<R, TlsError>,
    ) -> Result<R, TlsError> {
        if self.poisoned {
            return Err(PANICKED);
        }
        let inner = &mut *self.inner;
        match crate::gate::guarded(|| f(inner)) {
            Some(r) => r,
            None => {
                self.poisoned = true;
                Err(PANICKED)
            }
        }
    }
}

impl TlsSession for Guarded {
    fn step<'i>(
        &mut self,
        input: &'i mut [u8],
        output: &mut [u8],
    ) -> Result<TlsProgress<'i>, TlsError> {
        if self.poisoned {
            return Err(PANICKED);
        }
        let inner = &mut *self.inner;
        match crate::gate::guarded(move || inner.step(input, output)) {
            Some(r) => r,
            None => {
                self.poisoned = true;
                Err(PANICKED)
            }
        }
    }

    fn encrypt(&mut self, plaintext: &[u8], output: &mut [u8]) -> Result<usize, TlsError> {
        self.call(|s| s.encrypt(plaintext, output))
    }

    fn close(&mut self, output: &mut [u8]) -> Result<usize, TlsError> {
        self.call(|s| s.close(output))
    }

    fn on_transport_closed(&mut self) -> TlsCloseKind {
        self.call(|s| Ok(s.on_transport_closed()))
            .unwrap_or(TlsCloseKind::Unclean)
    }

    fn info(&self) -> Option<TlsInfo> {
        if self.poisoned {
            return None;
        }
        crate::gate::guarded(|| self.inner.info()).flatten()
    }

    fn input_capacity_required(&self) -> usize {
        if self.poisoned {
            return 0;
        }
        crate::gate::guarded(|| self.inner.input_capacity_required()).unwrap_or(0)
    }
}

/// The session type of [`NoTls`]; it has no values.
#[derive(Debug)]
pub enum NoTlsSession {}

impl TlsAcceptor for NoTls {
    type Session = NoTlsSession;
    fn session(&self, _info: &ConnectionInfo) -> Result<NoTlsSession, TlsError> {
        Err(TlsError::new(TlsFailure::State, 0, None))
    }
}

impl TlsSession for NoTlsSession {
    fn step<'i>(
        &mut self,
        _input: &'i mut [u8],
        _output: &mut [u8],
    ) -> Result<TlsProgress<'i>, TlsError> {
        match *self {}
    }
    fn encrypt(&mut self, _plaintext: &[u8], _output: &mut [u8]) -> Result<usize, TlsError> {
        match *self {}
    }
    fn close(&mut self, _output: &mut [u8]) -> Result<usize, TlsError> {
        match *self {}
    }
    fn on_transport_closed(&mut self) -> TlsCloseKind {
        match *self {}
    }
    fn info(&self) -> Option<TlsInfo> {
        match *self {}
    }
    fn input_capacity_required(&self) -> usize {
        match *self {}
    }
}