Skip to main content

rtci_shared/
stream.rs

1//! Stream transports (TCP, and TLS over TCP) for a sans-I/O engine.
2//!
3//! A datagram engine is driven with one call per received datagram and one per datagram to
4//! send. A stream has more to it: it is opened (connect, or accept on a listener), it carries
5//! bytes in whatever pieces the network delivers, it can only take so much at a time, and it
6//! ends, cleanly or not. This module puts all of that behind ids, so the engine keeps every
7//! decision and the application (the *driver*) keeps only the sockets:
8//!
9//! | Direction | What | Type |
10//! |---|---|---|
11//! | engine → driver | listen on / stop listening on an address; connect to an address from a local one; close; reset | [`StreamCommand`] |
12//! | driver → engine | listening (with the bound address); connected (with the local address); failed; written; closed by the peer; reset | [`StreamEvent`] |
13//! | driver → engine | a connection accepted on a listener: the engine gives it an id | [`StreamTable::accept`] |
14//! | driver → engine | bytes read from a connection, in any segmentation | [`StreamTable::read`] |
15//! | engine → driver | bytes to write on a connection, in order | [`StreamTransmit`] |
16//!
17//! [`StreamTable`] is the engine's half: it allocates the ids, frames outgoing messages
18//! ([`Framing::Rfc4571`] for ICE-TCP, RFC 4571 / RFC 6544; [`Framing::Turn`] for TURN over TCP,
19//! RFC 8656 §12.5, whose messages delimit themselves), splits incoming bytes back into
20//! messages whatever the read sizes, optionally runs a [`StreamLayer`] (TLS) between the two,
21//! and applies back-pressure.
22//!
23//! # Back-pressure
24//!
25//! The driver reports with [`StreamEvent::Written`] how many bytes of a connection have left
26//! for the socket. The table hands out at most [`StreamConfig::window`] bytes a connection
27//! that are not yet reported written (one transmit is always allowed, so progress never
28//! stops), and keeps what does not fit queued, up to [`StreamConfig::max_queued`] bytes.
29//! Beyond that a message is dropped whole, before framing or encryption, exactly as a
30//! congested datagram path would lose it: a byte stream is never cut inside a frame or a TLS
31//! record. [`StreamTable::send`] says which happened.
32//!
33//! # Order of commands and transmits
34//!
35//! A [`StreamCommand::Close`] is issued only after the last [`StreamTransmit`] of its
36//! connection has been handed out, so a driver that writes each transmit as it takes it closes
37//! after the last byte. [`StreamCommand::Reset`] discards whatever the driver still holds.
38//!
39//! # Example: one framed message each way over a connection the engine asked for
40//!
41//! ```
42//! use rtci_shared::stream::*;
43//!
44//! let mut engine = StreamTable::new(StreamConfig::default());
45//! let local = "10.0.0.1:0".parse().unwrap();
46//! let remote = "10.0.0.2:5000".parse().unwrap();
47//! let id = engine.connect(local, remote, Framing::Rfc4571, 0, false, None).unwrap();
48//! assert_eq!(
49//!     engine.poll_command(),
50//!     Some(StreamCommand::Connect { id, local, remote, reuse_address: false })
51//! );
52//! // The engine may queue data before the connection is up.
53//! assert!(engine.send(id, b"hello").unwrap());
54//! assert!(engine.poll_transmit().is_none());
55//!
56//! // The driver connected from an ephemeral port.
57//! let bound = "10.0.0.1:40001".parse().unwrap();
58//! engine.handle_event(StreamEvent::Connected { id, local: bound }).unwrap();
59//! let transmit = engine.poll_transmit().unwrap();
60//! assert_eq!(transmit.data, b"\x00\x05hello");
61//! engine.handle_event(StreamEvent::Written { id, bytes: transmit.data.len() }).unwrap();
62//!
63//! // The answer arrives one byte at a time.
64//! let mut messages = vec![];
65//! for byte in b"\x00\x03bye" {
66//!     messages.extend(engine.read(id, &[*byte]).unwrap());
67//! }
68//! assert_eq!(messages, vec![b"bye".to_vec()]);
69//! ```
70
71use crate::error::{Error, Result};
72use crate::tcp_framing::{FRAMING_HEADER_LEN, MAX_FRAMED_PACKET_SIZE, TcpFrameDecoder};
73use crate::turn_framing::TurnStreamDecoder;
74use std::collections::{BTreeMap, VecDeque};
75use std::fmt;
76use std::net::SocketAddr;
77use std::ops::Bound;
78
79/// A connection, as the engine names it. Every id is allocated by the engine: for a connection
80/// it asks for in [`StreamCommand::Connect`], and for one the driver accepted, by
81/// [`StreamTable::accept`]. Ids are never reused.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
83pub struct StreamId(pub u64);
84
85impl fmt::Display for StreamId {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        write!(f, "stream#{}", self.0)
88    }
89}
90
91/// A listening socket, as the engine names it in [`StreamCommand::Listen`].
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
93pub struct ListenerId(pub u64);
94
95impl fmt::Display for ListenerId {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        write!(f, "listener#{}", self.0)
98    }
99}
100
101/// What the engine asks the driver to do with its sockets.
102#[derive(Debug, Clone, PartialEq, Eq)]
103#[non_exhaustive]
104pub enum StreamCommand {
105    /// Listen for TCP connections on `local` (port 0: any free port) and accept them, each
106    /// reported with [`StreamTable::accept`]. Answer with [`StreamEvent::Listening`], naming
107    /// the bound address, or [`StreamEvent::ListenFailed`].
108    Listen {
109        /// The listener's id.
110        listener: ListenerId,
111        /// The address to bind.
112        local: SocketAddr,
113        /// Bind with `SO_REUSEADDR` (and `SO_REUSEPORT` where it exists): the engine will also
114        /// connect from this address (an RFC 6544 simultaneous-open candidate).
115        reuse_address: bool,
116    },
117    /// Close the listener. Connections it accepted stay open.
118    StopListening {
119        /// The listener's id.
120        listener: ListenerId,
121    },
122    /// Open a TCP connection from `local` (port 0: an ephemeral port on that address) to
123    /// `remote`. Answer with [`StreamEvent::Connected`], naming the local address the
124    /// connection got, or [`StreamEvent::ConnectFailed`].
125    Connect {
126        /// The connection's id.
127        id: StreamId,
128        /// The address to bind before connecting.
129        local: SocketAddr,
130        /// Where to connect.
131        remote: SocketAddr,
132        /// Bind with `SO_REUSEADDR` (and `SO_REUSEPORT` where it exists): a listener is on
133        /// `local` too (RFC 6544 simultaneous open).
134        reuse_address: bool,
135    },
136    /// Write what was handed out for the connection, then close it (FIN). Report
137    /// [`StreamEvent::Closed`] when it is closed.
138    Close {
139        /// The connection's id.
140        id: StreamId,
141    },
142    /// Abort the connection now (RST), discarding what was not written. The engine has
143    /// forgotten the id: nothing needs to be reported.
144    Reset {
145        /// The connection's id.
146        id: StreamId,
147    },
148    /// Resolve `host` (a server's name, both IPv6 and IPv4 at once, RFC 8305 section 3) and
149    /// answer with [`StreamEvent::Resolved`], `port` on every address.
150    Resolve {
151        /// The query's id.
152        query: u64,
153        /// The name.
154        host: String,
155        /// The port the addresses get.
156        port: u16,
157    },
158    /// Look up the `kind` records of `name` (SRV, RFC 2782; NAPTR, RFC 3403) and answer with
159    /// [`StreamEvent::ResolvedRecords`], an empty list when there are none or the driver
160    /// cannot look them up. Used to find a STUN or TURN server whose URI gives no port (RFC
161    /// 5928 section 3, RFC 8489 section 8); an answer that does not come within
162    /// [`RECORDS_TIMEOUT`] counts as empty.
163    ResolveRecords {
164        /// The query's id.
165        query: u64,
166        /// The name (for SRV, the whole `_service._proto.name`).
167        name: String,
168        /// The record type.
169        kind: RecordKind,
170    },
171}
172
173/// How long the engine waits for a [`StreamCommand::ResolveRecords`] answer before it takes
174/// the name's addresses instead (a driver that does not look records up).
175pub const RECORDS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
176
177/// A DNS record type the engine asks for ([`StreamCommand::ResolveRecords`]).
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
179#[non_exhaustive]
180pub enum RecordKind {
181    /// SRV (RFC 2782).
182    Srv,
183    /// NAPTR (RFC 3403), for S-NAPTR (RFC 3958).
184    Naptr,
185}
186
187/// A DNS record, as the driver reports it ([`StreamEvent::ResolvedRecords`]).
188#[derive(Debug, Clone, PartialEq, Eq)]
189#[non_exhaustive]
190pub enum DnsRecord {
191    /// An SRV record (RFC 2782).
192    Srv {
193        /// Lower is tried first.
194        priority: u16,
195        /// Among equal priorities, the share of selections.
196        weight: u16,
197        /// The server's port.
198        port: u16,
199        /// The server's name ("." for "no service here").
200        target: String,
201    },
202    /// A NAPTR record (RFC 3403).
203    Naptr {
204        /// Lower is used first.
205        order: u16,
206        /// Among equal orders, lower is used first.
207        preference: u16,
208        /// `S` (the replacement is an SRV name), `A` (an address name), ...
209        flags: String,
210        /// The service field, `RELAY:turn.tcp` and the like for TURN (RFC 5928 section 4).
211        services: String,
212        /// The regular expression (unused by S-NAPTR).
213        regexp: String,
214        /// The next name to look up.
215        replacement: String,
216    },
217}
218
219/// What the driver tells the engine about its sockets.
220#[derive(Debug, Clone, PartialEq, Eq)]
221#[non_exhaustive]
222pub enum StreamEvent {
223    /// The listener is bound to `local`.
224    Listening {
225        /// The listener's id.
226        listener: ListenerId,
227        /// The address it is bound to (the port chosen when the command asked for port 0).
228        local: SocketAddr,
229    },
230    /// The listener could not be bound.
231    ListenFailed {
232        /// The listener's id.
233        listener: ListenerId,
234    },
235    /// The connection is established from `local`.
236    Connected {
237        /// The connection's id.
238        id: StreamId,
239        /// Its local address (with the ephemeral port it got).
240        local: SocketAddr,
241    },
242    /// The connection could not be established (refused, unreachable, timed out).
243    ConnectFailed {
244        /// The connection's id.
245        id: StreamId,
246    },
247    /// `bytes` more of the connection's transmits have been written to the socket.
248    Written {
249        /// The connection's id.
250        id: StreamId,
251        /// How many bytes.
252        bytes: usize,
253    },
254    /// The connection is closed: the peer finished it (end of stream), or a close the engine
255    /// asked for is done.
256    Closed {
257        /// The connection's id.
258        id: StreamId,
259    },
260    /// The connection broke (reset by the peer, or an I/O error).
261    Reset {
262        /// The connection's id.
263        id: StreamId,
264    },
265    /// A [`StreamCommand::Resolve`] is answered: the addresses, empty when the name did not
266    /// resolve.
267    Resolved {
268        /// The query's id.
269        query: u64,
270        /// The addresses, with the query's port.
271        addresses: Vec<SocketAddr>,
272    },
273    /// A [`StreamCommand::ResolveRecords`] is answered (an empty list: none).
274    ResolvedRecords {
275        /// The query's id.
276        query: u64,
277        /// The records.
278        records: Vec<DnsRecord>,
279    },
280    /// One family of a [`StreamCommand::Resolve`] is answered (AAAA with `ipv6`, A without),
281    /// as it arrives: the engine starts on the first answer (RFC 8305 section 3). A driver
282    /// answers each family once, an empty list when it has none; or answers the whole query
283    /// once with [`StreamEvent::Resolved`].
284    ResolvedFamily {
285        /// The query's id.
286        query: u64,
287        /// Whether these are the IPv6 (AAAA) addresses.
288        ipv6: bool,
289        /// The addresses of that family, with the query's port.
290        addresses: Vec<SocketAddr>,
291    },
292}
293
294/// Bytes to write on a connection, after every earlier transmit of the same connection.
295#[derive(Debug, Clone, PartialEq, Eq)]
296pub struct StreamTransmit {
297    /// The connection.
298    pub id: StreamId,
299    /// The bytes, framed (and encrypted, over TLS).
300    pub data: Vec<u8>,
301    /// The Differentiated Services codepoint to send the connection's packets with (the upper
302    /// six bits of `IP_TOS` / `IPV6_TCLASS`): every packet on one TCP connection carries the
303    /// same one (RFC 8837 section 5, RFC 8835 section 4.2), that of the highest-priority flow
304    /// the engine has. The driver sets it on the connection's socket when it changes.
305    pub dscp: u8,
306}
307
308/// How messages are delimited on a connection.
309#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
310#[non_exhaustive]
311pub enum Framing {
312    /// RFC 4571: a two-byte length before each message (ICE-TCP, RFC 6544 section 3).
313    Rfc4571,
314    /// TURN over TCP / TLS (RFC 8656 section 12.5): STUN and ChannelData messages back to
315    /// back, each delimited by its own header.
316    Turn,
317    /// None: bytes go out as they are given and come back in the pieces the socket reads.
318    /// A TURN-TCP data connection (RFC 6062 section 4.5), whose ConnectionBind exchange and
319    /// then the peer's stream its user delimits itself.
320    Raw,
321}
322
323impl Framing {
324    /// `message` as it goes on the wire.
325    ///
326    /// # Errors
327    ///
328    /// [`Error::ErrStreamMessageTooLong`] for an RFC 4571 message over 65535 bytes.
329    pub fn encode(self, message: &[u8]) -> Result<Vec<u8>> {
330        match self {
331            Framing::Rfc4571 => {
332                if message.len() > MAX_FRAMED_PACKET_SIZE {
333                    return Err(Error::ErrStreamMessageTooLong);
334                }
335                let mut framed = Vec::with_capacity(FRAMING_HEADER_LEN + message.len());
336                framed.extend_from_slice(&(message.len() as u16).to_be_bytes());
337                framed.extend_from_slice(message);
338                Ok(framed)
339            }
340            Framing::Turn | Framing::Raw => Ok(message.to_vec()),
341        }
342    }
343
344    /// The most bytes one message takes on the wire, framing included.
345    fn max_wire_len(self) -> usize {
346        match self {
347            Framing::Rfc4571 => FRAMING_HEADER_LEN + MAX_FRAMED_PACKET_SIZE,
348            // A STUN header (20) or a padded ChannelData message (4 + 65535 + 1).
349            Framing::Turn => 20 + MAX_FRAMED_PACKET_SIZE,
350            Framing::Raw => MAX_FRAMED_PACKET_SIZE,
351        }
352    }
353}
354
355/// Splits a byte stream of one [`Framing`] back into its messages. Bytes can be fed in any
356/// segmentation; memory stays bounded by two messages whatever the read size, because input is
357/// taken a message's worth at a time and drained in between.
358#[derive(Debug)]
359pub struct StreamDecoder {
360    framing: Framing,
361    rfc4571: TcpFrameDecoder,
362    turn: TurnStreamDecoder,
363}
364
365impl StreamDecoder {
366    /// A decoder for `framing`.
367    pub fn new(framing: Framing) -> Self {
368        Self {
369            framing,
370            rfc4571: TcpFrameDecoder::new(),
371            turn: TurnStreamDecoder::new(),
372        }
373    }
374
375    /// Takes `data` and returns every message it completes, in order.
376    ///
377    /// # Errors
378    ///
379    /// For [`Framing::Turn`], bytes that start neither a STUN nor a ChannelData message
380    /// ([`Error::OtherTurnErr`]): the stream cannot be resynchronised and must be closed.
381    pub fn decode(&mut self, data: &[u8]) -> Result<Vec<Vec<u8>>> {
382        let mut out = Vec::new();
383        for chunk in data.chunks(self.framing.max_wire_len()) {
384            match self.framing {
385                Framing::Rfc4571 => {
386                    // Never refused: at most one partial frame is held before the chunk.
387                    self.rfc4571.push(chunk)?;
388                    while let Some(message) = self.rfc4571.next_packet() {
389                        out.push(message);
390                    }
391                }
392                Framing::Turn => {
393                    self.turn.extend_from_slice(chunk);
394                    while let Some(message) = self.turn.next_message()? {
395                        out.push(message);
396                    }
397                }
398                Framing::Raw => {
399                    if !chunk.is_empty() {
400                        out.push(chunk.to_vec());
401                    }
402                }
403            }
404        }
405        Ok(out)
406    }
407
408    /// Bytes held that do not make a whole message yet.
409    pub fn buffered_len(&self) -> usize {
410        match self.framing {
411            Framing::Rfc4571 => self.rfc4571.buffered_len(),
412            Framing::Turn => self.turn.buffered_len(),
413            Framing::Raw => 0,
414        }
415    }
416}
417
418/// A security layer between the framing and the socket: TLS for TURN over TLS, in its
419/// sans-I/O form. Ciphertext comes in with [`receive`](Self::receive), plaintext goes out
420/// with [`send`](Self::send) once the handshake [is done](Self::is_established), and the
421/// table collects what the layer has to write after every call.
422pub trait StreamLayer: Send {
423    /// Takes bytes received from the peer and processes them.
424    ///
425    /// # Errors
426    ///
427    /// A protocol error (bad record, failed certificate verification): the connection is
428    /// reset.
429    fn receive(&mut self, data: &[u8]) -> Result<()>;
430    /// Appends the plaintext received so far to `out`.
431    fn read_plaintext(&mut self, out: &mut Vec<u8>) -> Result<()>;
432    /// Whether plaintext can be sent: the handshake is complete.
433    fn is_established(&self) -> bool;
434    /// Takes plaintext to send.
435    fn send(&mut self, plaintext: &[u8]) -> Result<()>;
436    /// Appends the bytes the layer has to write to `out`.
437    fn write_wire(&mut self, out: &mut Vec<u8>) -> Result<()>;
438    /// Starts an orderly close (TLS `close_notify`).
439    fn close(&mut self);
440    /// Whether the peer closed the layer (TLS `close_notify` received).
441    fn peer_closed(&self) -> bool;
442}
443
444/// Limits of a [`StreamTable`].
445#[derive(Debug, Clone, Copy, PartialEq, Eq)]
446pub struct StreamConfig {
447    /// Bytes of a connection handed to the driver and not yet reported written, beyond which
448    /// no more is handed out (one transmit is always allowed).
449    pub window: usize,
450    /// Bytes of a connection queued in the engine, beyond which a message is dropped whole.
451    pub max_queued: usize,
452    /// Connections at most, accepted ones included; an accept beyond it is refused.
453    pub max_connections: usize,
454}
455
456impl Default for StreamConfig {
457    fn default() -> Self {
458        Self {
459            window: 64 * 1024,
460            max_queued: 512 * 1024,
461            max_connections: 256,
462        }
463    }
464}
465
466/// How a connection came to be.
467#[derive(Debug, Clone, Copy, PartialEq, Eq)]
468#[non_exhaustive]
469pub enum StreamOrigin {
470    /// The engine asked for it ([`StreamCommand::Connect`]).
471    Connected,
472    /// The driver accepted it on a listener.
473    Accepted(ListenerId),
474}
475
476/// Where a connection is in its life.
477#[derive(Debug, Clone, Copy, PartialEq, Eq)]
478#[non_exhaustive]
479pub enum StreamState {
480    /// Asked for, not yet established.
481    Connecting,
482    /// Established.
483    Open,
484    /// The engine closed it; the driver writes what it holds, then closes.
485    Closing,
486}
487
488/// A connection, as [`StreamTable::info`] describes it.
489#[derive(Debug, Clone, Copy, PartialEq, Eq)]
490pub struct StreamInfo {
491    /// Its id.
492    pub id: StreamId,
493    /// The owner's tag, given when it was opened or when its listener was.
494    pub tag: u32,
495    /// How it came to be.
496    pub origin: StreamOrigin,
497    /// Its state.
498    pub state: StreamState,
499    /// Its local address: the requested one until it is established, then the bound one.
500    pub local: SocketAddr,
501    /// The local address it was asked for (port 0: any).
502    pub requested_local: SocketAddr,
503    /// The peer's address.
504    pub remote: SocketAddr,
505    /// Its framing.
506    pub framing: Framing,
507    /// Messages sent and received, and messages dropped by back-pressure.
508    pub messages_sent: u64,
509    /// Messages received.
510    pub messages_received: u64,
511    /// Messages dropped because the queue was full.
512    pub messages_dropped: u64,
513    /// Bytes handed to the driver and not yet reported written.
514    pub in_flight: usize,
515    /// Bytes queued in the engine.
516    pub queued: usize,
517}
518
519/// What a [`StreamTable`] reports to its owner, in the order it happened.
520#[derive(Debug, Clone, PartialEq, Eq)]
521#[non_exhaustive]
522pub enum StreamNotice {
523    /// A listener is bound.
524    Listening {
525        /// The listener.
526        listener: ListenerId,
527        /// Its tag.
528        tag: u32,
529        /// The bound address.
530        local: SocketAddr,
531    },
532    /// A listener could not be bound.
533    ListenFailed {
534        /// The listener.
535        listener: ListenerId,
536        /// Its tag.
537        tag: u32,
538        /// The address it was asked for.
539        requested: SocketAddr,
540    },
541    /// A connection the engine asked for is established.
542    Connected {
543        /// The connection.
544        id: StreamId,
545        /// Its tag.
546        tag: u32,
547        /// Its local address.
548        local: SocketAddr,
549        /// The peer.
550        remote: SocketAddr,
551    },
552    /// A connection the engine asked for could not be established; its queued messages are
553    /// gone.
554    ConnectFailed {
555        /// The connection.
556        id: StreamId,
557        /// Its tag.
558        tag: u32,
559        /// The local address it was asked for.
560        local: SocketAddr,
561        /// The peer.
562        remote: SocketAddr,
563    },
564    /// A connection is gone: closed (`reset` false) or broken (`reset` true). Not reported
565    /// for a connection the engine reset itself.
566    Closed {
567        /// The connection.
568        id: StreamId,
569        /// Its tag.
570        tag: u32,
571        /// Its local address.
572        local: SocketAddr,
573        /// The peer.
574        remote: SocketAddr,
575        /// Whether it broke rather than closed.
576        reset: bool,
577    },
578    /// A name the engine asked for was resolved.
579    Resolved {
580        /// The query.
581        query: u64,
582        /// The addresses (empty: the name did not resolve).
583        addresses: Vec<SocketAddr>,
584    },
585    /// Records the engine asked for were looked up.
586    ResolvedRecords {
587        /// The query.
588        query: u64,
589        /// The records (possibly none).
590        records: Vec<DnsRecord>,
591    },
592    /// One family of a name the engine asked for was resolved.
593    ResolvedFamily {
594        /// The query.
595        query: u64,
596        /// Whether these are the IPv6 addresses.
597        ipv6: bool,
598        /// The addresses of that family (possibly none).
599        addresses: Vec<SocketAddr>,
600    },
601}
602
603struct Listener {
604    tag: u32,
605    framing: Framing,
606    requested: SocketAddr,
607    bound: Option<SocketAddr>,
608}
609
610struct Connection {
611    tag: u32,
612    origin: StreamOrigin,
613    state: StreamState,
614    requested_local: SocketAddr,
615    local: SocketAddr,
616    remote: SocketAddr,
617    framing: Framing,
618    decoder: StreamDecoder,
619    layer: Option<Box<dyn StreamLayer>>,
620    /// Framed messages waiting for the layer's handshake.
621    pending_plaintext: VecDeque<Vec<u8>>,
622    /// Wire bytes not yet handed to the driver.
623    queue: VecDeque<Vec<u8>>,
624    queued: usize,
625    in_flight: usize,
626    close_sent: bool,
627    messages_sent: u64,
628    messages_received: u64,
629    messages_dropped: u64,
630}
631
632impl Connection {
633    fn info(&self, id: StreamId) -> StreamInfo {
634        StreamInfo {
635            id,
636            tag: self.tag,
637            origin: self.origin,
638            state: self.state,
639            local: self.local,
640            requested_local: self.requested_local,
641            remote: self.remote,
642            framing: self.framing,
643            messages_sent: self.messages_sent,
644            messages_received: self.messages_received,
645            messages_dropped: self.messages_dropped,
646            in_flight: self.in_flight,
647            queued: self.queued,
648        }
649    }
650
651    fn enqueue_wire(&mut self, bytes: Vec<u8>) {
652        if !bytes.is_empty() {
653            self.queued += bytes.len();
654            self.queue.push_back(bytes);
655        }
656    }
657
658    /// Moves what the layer has to write into the queue.
659    fn collect_layer_output(&mut self) -> Result<()> {
660        if let Some(layer) = self.layer.as_mut() {
661            let mut out = Vec::new();
662            layer.write_wire(&mut out)?;
663            self.enqueue_wire(out);
664        }
665        Ok(())
666    }
667
668    /// Hands messages that waited for the handshake to the layer once it is established.
669    fn flush_pending_plaintext(&mut self) -> Result<()> {
670        let Some(layer) = self.layer.as_mut() else {
671            return Ok(());
672        };
673        if !layer.is_established() {
674            return Ok(());
675        }
676        while let Some(frame) = self.pending_plaintext.pop_front() {
677            self.queued -= frame.len();
678            layer.send(&frame)?;
679        }
680        self.collect_layer_output()
681    }
682}
683
684/// The engine's side of its stream transports: listeners, connections, framing, the optional
685/// security layer and back-pressure. See the [module documentation](self).
686///
687/// The *tag* given to [`listen`](Self::listen) and [`connect`](Self::connect) is the owner's:
688/// one table can serve several users (ICE-TCP and a TURN client, say), each finding its
689/// connections by tag.
690pub struct StreamTable {
691    config: StreamConfig,
692    next_id: u64,
693    next_listener: u64,
694    connections: BTreeMap<StreamId, Connection>,
695    listeners: BTreeMap<ListenerId, Listener>,
696    commands: VecDeque<StreamCommand>,
697    notices: VecDeque<StreamNotice>,
698    last_transmit: Option<StreamId>,
699    next_query: u64,
700}
701
702impl fmt::Debug for StreamTable {
703    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
704        f.debug_struct("StreamTable")
705            .field("connections", &self.connections.len())
706            .field("listeners", &self.listeners.len())
707            .field("commands", &self.commands.len())
708            .finish()
709    }
710}
711
712impl Default for StreamTable {
713    fn default() -> Self {
714        Self::new(StreamConfig::default())
715    }
716}
717
718impl StreamTable {
719    /// An empty table.
720    pub fn new(config: StreamConfig) -> Self {
721        Self {
722            config,
723            next_id: 1,
724            next_listener: 1,
725            connections: BTreeMap::new(),
726            listeners: BTreeMap::new(),
727            commands: VecDeque::new(),
728            notices: VecDeque::new(),
729            last_transmit: None,
730            next_query: 1,
731        }
732    }
733
734    /// Its limits.
735    pub fn config(&self) -> StreamConfig {
736        self.config
737    }
738
739    /// Asks the driver to listen on `local`; connections it accepts get `framing` and `tag`.
740    pub fn listen(
741        &mut self,
742        local: SocketAddr,
743        framing: Framing,
744        tag: u32,
745        reuse_address: bool,
746    ) -> ListenerId {
747        let listener = ListenerId(self.next_listener);
748        self.next_listener += 1;
749        self.listeners.insert(
750            listener,
751            Listener {
752                tag,
753                framing,
754                requested: local,
755                bound: None,
756            },
757        );
758        self.commands.push_back(StreamCommand::Listen {
759            listener,
760            local,
761            reuse_address,
762        });
763        listener
764    }
765
766    /// Asks the driver to resolve `host`; the answer comes as [`StreamNotice::Resolved`] with
767    /// the returned query id.
768    pub fn resolve(&mut self, host: String, port: u16) -> u64 {
769        let query = self.next_query;
770        self.next_query += 1;
771        self.commands
772            .push_back(StreamCommand::Resolve { query, host, port });
773        query
774    }
775
776    /// Asks the driver for the `kind` records of `name`; the answer comes as
777    /// [`StreamNotice::ResolvedRecords`] with the returned query id (ids are shared with
778    /// [`resolve`](Self::resolve)).
779    pub fn resolve_records(&mut self, name: String, kind: RecordKind) -> u64 {
780        let query = self.next_query;
781        self.next_query += 1;
782        self.commands
783            .push_back(StreamCommand::ResolveRecords { query, name, kind });
784        query
785    }
786
787    /// Asks the driver to close the listener. Unknown listeners are ignored.
788    pub fn stop_listening(&mut self, listener: ListenerId) {
789        if self.listeners.remove(&listener).is_some() {
790            self.commands
791                .push_back(StreamCommand::StopListening { listener });
792        }
793    }
794
795    /// The address a listener is bound to, once the driver said so.
796    pub fn listener_address(&self, listener: ListenerId) -> Option<SocketAddr> {
797        self.listeners.get(&listener).and_then(|l| l.bound)
798    }
799
800    /// The listeners: id, tag, requested and bound address.
801    pub fn listeners(
802        &self,
803    ) -> impl Iterator<Item = (ListenerId, u32, SocketAddr, Option<SocketAddr>)> + '_ {
804        self.listeners
805            .iter()
806            .map(|(id, l)| (*id, l.tag, l.requested, l.bound))
807    }
808
809    /// Asks the driver for a connection from `local` (port 0: ephemeral) to `remote`. Messages
810    /// can be sent at once; they wait for the connection. With a `layer`, what it writes first
811    /// (a TLS ClientHello) is sent first, and messages wait for its handshake.
812    ///
813    /// # Errors
814    ///
815    /// [`Error::ErrBufferFull`] when the table holds [`StreamConfig::max_connections`]; an
816    /// error of the layer.
817    pub fn connect(
818        &mut self,
819        local: SocketAddr,
820        remote: SocketAddr,
821        framing: Framing,
822        tag: u32,
823        reuse_address: bool,
824        layer: Option<Box<dyn StreamLayer>>,
825    ) -> Result<StreamId> {
826        if self.connections.len() >= self.config.max_connections {
827            return Err(Error::ErrBufferFull);
828        }
829        let id = StreamId(self.next_id);
830        self.next_id += 1;
831        let mut connection = Connection {
832            tag,
833            origin: StreamOrigin::Connected,
834            state: StreamState::Connecting,
835            requested_local: local,
836            local,
837            remote,
838            framing,
839            decoder: StreamDecoder::new(framing),
840            layer,
841            pending_plaintext: VecDeque::new(),
842            queue: VecDeque::new(),
843            queued: 0,
844            in_flight: 0,
845            close_sent: false,
846            messages_sent: 0,
847            messages_received: 0,
848            messages_dropped: 0,
849        };
850        connection.collect_layer_output()?;
851        self.connections.insert(id, connection);
852        self.commands.push_back(StreamCommand::Connect {
853            id,
854            local,
855            remote,
856            reuse_address,
857        });
858        Ok(id)
859    }
860
861    /// The driver accepted a connection from `remote` on `listener`, arriving on `local`.
862    /// Returns its id, or `None` when the listener is unknown or the table is full: the driver
863    /// closes the socket then.
864    pub fn accept(
865        &mut self,
866        listener: ListenerId,
867        local: SocketAddr,
868        remote: SocketAddr,
869    ) -> Option<StreamId> {
870        let (tag, framing) = {
871            let l = self.listeners.get(&listener)?;
872            (l.tag, l.framing)
873        };
874        if self.connections.len() >= self.config.max_connections {
875            return None;
876        }
877        let id = StreamId(self.next_id);
878        self.next_id += 1;
879        self.connections.insert(
880            id,
881            Connection {
882                tag,
883                origin: StreamOrigin::Accepted(listener),
884                state: StreamState::Open,
885                requested_local: local,
886                local,
887                remote,
888                framing,
889                decoder: StreamDecoder::new(framing),
890                layer: None,
891                pending_plaintext: VecDeque::new(),
892                queue: VecDeque::new(),
893                queued: 0,
894                in_flight: 0,
895                close_sent: false,
896                messages_sent: 0,
897                messages_received: 0,
898                messages_dropped: 0,
899            },
900        );
901        Some(id)
902    }
903
904    /// Queues `message` on the connection, framed (and encrypted with its layer). Returns
905    /// `false` when back-pressure dropped it: the connection already holds
906    /// [`StreamConfig::max_queued`] bytes.
907    ///
908    /// # Errors
909    ///
910    /// [`Error::ErrUnknownStream`], [`Error::ErrStreamConnectionClosed`] (closing),
911    /// [`Error::ErrStreamMessageTooLong`], or an error of the layer.
912    pub fn send(&mut self, id: StreamId, message: &[u8]) -> Result<bool> {
913        let max_queued = self.config.max_queued;
914        let connection = self
915            .connections
916            .get_mut(&id)
917            .ok_or(Error::ErrUnknownStream)?;
918        if connection.state == StreamState::Closing {
919            return Err(Error::ErrStreamConnectionClosed);
920        }
921        let frame = connection.framing.encode(message)?;
922        if connection.queued > 0 && connection.queued + frame.len() > max_queued {
923            connection.messages_dropped += 1;
924            return Ok(false);
925        }
926        connection.messages_sent += 1;
927        match connection.layer.as_mut() {
928            Some(layer) if layer.is_established() && connection.pending_plaintext.is_empty() => {
929                layer.send(&frame)?;
930                connection.collect_layer_output()?;
931            }
932            Some(_) => {
933                connection.queued += frame.len();
934                connection.pending_plaintext.push_back(frame);
935            }
936            None => connection.enqueue_wire(frame),
937        }
938        Ok(true)
939    }
940
941    /// Bytes the driver read from the connection, in whatever piece: returns the messages
942    /// they complete, in order.
943    ///
944    /// # Errors
945    ///
946    /// [`Error::ErrUnknownStream`]; a stream that is not of its framing (TURN) or a layer
947    /// error: the connection is then reset ([`StreamCommand::Reset`] is issued) and reported
948    /// [`StreamNotice::Closed`].
949    pub fn read(&mut self, id: StreamId, data: &[u8]) -> Result<Vec<Vec<u8>>> {
950        let connection = self
951            .connections
952            .get_mut(&id)
953            .ok_or(Error::ErrUnknownStream)?;
954        let result = (|| {
955            let plaintext = match connection.layer.as_mut() {
956                Some(layer) => {
957                    layer.receive(data)?;
958                    let mut plaintext = Vec::new();
959                    layer.read_plaintext(&mut plaintext)?;
960                    connection.collect_layer_output()?;
961                    connection.flush_pending_plaintext()?;
962                    plaintext
963                }
964                None => data.to_vec(),
965            };
966            connection.decoder.decode(&plaintext)
967        })();
968        match result {
969            Ok(messages) => {
970                connection.messages_received += messages.len() as u64;
971                let peer_closed = connection
972                    .layer
973                    .as_ref()
974                    .is_some_and(|layer| layer.peer_closed());
975                if peer_closed && connection.state != StreamState::Closing {
976                    self.close(id);
977                }
978                Ok(messages)
979            }
980            Err(err) => {
981                self.fail(id, true);
982                Err(err)
983            }
984        }
985    }
986
987    /// Closes the connection in order: what is queued is still handed out, then
988    /// [`StreamCommand::Close`] is issued. A connection still connecting is reset instead.
989    /// Unknown ids are ignored.
990    pub fn close(&mut self, id: StreamId) {
991        let Some(connection) = self.connections.get_mut(&id) else {
992            return;
993        };
994        match connection.state {
995            StreamState::Connecting => self.reset(id),
996            StreamState::Closing => {}
997            StreamState::Open => {
998                connection.state = StreamState::Closing;
999                // Messages still waiting for a handshake will never be sent.
1000                for frame in connection.pending_plaintext.drain(..) {
1001                    connection.queued -= frame.len();
1002                }
1003                if let Some(layer) = connection.layer.as_mut() {
1004                    layer.close();
1005                }
1006                let _ = connection.collect_layer_output();
1007                self.issue_closes();
1008            }
1009        }
1010    }
1011
1012    /// Aborts the connection: [`StreamCommand::Reset`] is issued and the id forgotten. Unknown
1013    /// ids are ignored.
1014    pub fn reset(&mut self, id: StreamId) {
1015        if self.connections.remove(&id).is_some() {
1016            self.commands.push_back(StreamCommand::Reset { id });
1017        }
1018    }
1019
1020    /// Takes an event from the driver. Events for ids the table no longer knows (a connection
1021    /// it reset, a listener it stopped) are ignored: they cross on the way.
1022    ///
1023    /// # Errors
1024    ///
1025    /// An error of a connection's layer once it is established.
1026    pub fn handle_event(&mut self, event: StreamEvent) -> Result<()> {
1027        match event {
1028            StreamEvent::Listening { listener, local } => {
1029                if let Some(l) = self.listeners.get_mut(&listener) {
1030                    l.bound = Some(local);
1031                    self.notices.push_back(StreamNotice::Listening {
1032                        listener,
1033                        tag: l.tag,
1034                        local,
1035                    });
1036                }
1037            }
1038            StreamEvent::ListenFailed { listener } => {
1039                if let Some(l) = self.listeners.remove(&listener) {
1040                    self.notices.push_back(StreamNotice::ListenFailed {
1041                        listener,
1042                        tag: l.tag,
1043                        requested: l.requested,
1044                    });
1045                }
1046            }
1047            StreamEvent::Connected { id, local } => {
1048                if let Some(connection) = self.connections.get_mut(&id)
1049                    && connection.state == StreamState::Connecting
1050                {
1051                    connection.state = StreamState::Open;
1052                    connection.local = local;
1053                    self.notices.push_back(StreamNotice::Connected {
1054                        id,
1055                        tag: connection.tag,
1056                        local,
1057                        remote: connection.remote,
1058                    });
1059                }
1060            }
1061            StreamEvent::ConnectFailed { id } => {
1062                if let Some(connection) = self.connections.remove(&id) {
1063                    self.notices.push_back(StreamNotice::ConnectFailed {
1064                        id,
1065                        tag: connection.tag,
1066                        local: connection.requested_local,
1067                        remote: connection.remote,
1068                    });
1069                }
1070            }
1071            StreamEvent::Written { id, bytes } => {
1072                if let Some(connection) = self.connections.get_mut(&id) {
1073                    connection.in_flight = connection.in_flight.saturating_sub(bytes);
1074                }
1075            }
1076            StreamEvent::Closed { id } => self.fail(id, false),
1077            StreamEvent::Reset { id } => self.fail(id, true),
1078            StreamEvent::Resolved { query, addresses } => self
1079                .notices
1080                .push_back(StreamNotice::Resolved { query, addresses }),
1081            StreamEvent::ResolvedRecords { query, records } => self
1082                .notices
1083                .push_back(StreamNotice::ResolvedRecords { query, records }),
1084            StreamEvent::ResolvedFamily {
1085                query,
1086                ipv6,
1087                addresses,
1088            } => self.notices.push_back(StreamNotice::ResolvedFamily {
1089                query,
1090                ipv6,
1091                addresses,
1092            }),
1093        }
1094        Ok(())
1095    }
1096
1097    /// Forgets a connection that ended and reports it; with `issue_reset`, also tells the
1098    /// driver to abort it (an engine-side error).
1099    fn fail(&mut self, id: StreamId, reset: bool) {
1100        if let Some(connection) = self.connections.remove(&id) {
1101            self.notices.push_back(StreamNotice::Closed {
1102                id,
1103                tag: connection.tag,
1104                local: connection.local,
1105                remote: connection.remote,
1106                reset,
1107            });
1108            if reset {
1109                self.commands.push_back(StreamCommand::Reset { id });
1110            }
1111        }
1112    }
1113
1114    /// Issues [`StreamCommand::Close`] for closing connections with nothing left to hand out.
1115    fn issue_closes(&mut self) {
1116        for (id, connection) in self.connections.iter_mut() {
1117            if connection.state == StreamState::Closing
1118                && !connection.close_sent
1119                && connection.queue.is_empty()
1120            {
1121                connection.close_sent = true;
1122                self.commands.push_back(StreamCommand::Close { id: *id });
1123            }
1124        }
1125    }
1126
1127    /// The next command for the driver.
1128    pub fn poll_command(&mut self) -> Option<StreamCommand> {
1129        self.issue_closes();
1130        self.commands.pop_front()
1131    }
1132
1133    /// The next notice for the owner.
1134    pub fn poll_notice(&mut self) -> Option<StreamNotice> {
1135        self.notices.pop_front()
1136    }
1137
1138    /// The next bytes to write, connections taking turns. Only established connections
1139    /// transmit, each within its [window](StreamConfig::window).
1140    pub fn poll_transmit(&mut self) -> Option<StreamTransmit> {
1141        let window = self.config.window;
1142        let start = self.last_transmit.map_or(Bound::Unbounded, Bound::Excluded);
1143        let candidates: Vec<StreamId> = self
1144            .connections
1145            .range((start, Bound::Unbounded))
1146            .chain(self.connections.range(..))
1147            .filter(|(_, c)| {
1148                c.state != StreamState::Connecting
1149                    && c.queue.front().is_some_and(|front| {
1150                        c.in_flight == 0 || c.in_flight + front.len() <= window
1151                    })
1152            })
1153            .map(|(id, _)| *id)
1154            .take(1)
1155            .collect();
1156        let id = *candidates.first()?;
1157        let connection = self.connections.get_mut(&id)?;
1158        let mut data = connection.queue.pop_front()?;
1159        // Coalesce what else fits in the window.
1160        while let Some(next) = connection.queue.front() {
1161            if connection.in_flight + data.len() + next.len() > window {
1162                break;
1163            }
1164            let next = connection.queue.pop_front()?;
1165            data.extend_from_slice(&next);
1166        }
1167        connection.queued -= data.len();
1168        connection.in_flight += data.len();
1169        self.last_transmit = Some(id);
1170        if connection.state == StreamState::Closing && connection.queue.is_empty() {
1171            self.issue_closes();
1172        }
1173        Some(StreamTransmit { id, data, dscp: 0 })
1174    }
1175
1176    /// A connection's description, while the table knows it.
1177    pub fn info(&self, id: StreamId) -> Option<StreamInfo> {
1178        self.connections.get(&id).map(|c| c.info(id))
1179    }
1180
1181    /// Every connection.
1182    pub fn connections(&self) -> impl Iterator<Item = StreamInfo> + '_ {
1183        self.connections.iter().map(|(id, c)| c.info(*id))
1184    }
1185
1186    /// A connection of `tag` to `remote` from `local` that can still carry data (not closing),
1187    /// an established one before one still connecting. With `local_ip_only`, any local port
1188    /// on `local`'s address matches (an RFC 6544 active candidate, whose connections each get
1189    /// an ephemeral port).
1190    pub fn find(
1191        &self,
1192        tag: u32,
1193        local: SocketAddr,
1194        remote: SocketAddr,
1195        local_ip_only: bool,
1196    ) -> Option<StreamId> {
1197        let matches = |c: &Connection| {
1198            c.tag == tag
1199                && c.remote == remote
1200                && c.state != StreamState::Closing
1201                && (if local_ip_only {
1202                    c.local.ip() == local.ip()
1203                } else {
1204                    c.local == local
1205                        || (c.state == StreamState::Connecting && c.requested_local == local)
1206                })
1207        };
1208        let mut connecting = None;
1209        for (id, c) in &self.connections {
1210            if matches(c) {
1211                if c.state == StreamState::Open {
1212                    return Some(*id);
1213                }
1214                connecting.get_or_insert(*id);
1215            }
1216        }
1217        connecting
1218    }
1219
1220    /// Whether anything is waiting for the driver: a command or a transmit it may take.
1221    pub fn has_output(&self) -> bool {
1222        !self.commands.is_empty()
1223            || self.connections.values().any(|c| {
1224                (c.state != StreamState::Connecting && !c.queue.is_empty())
1225                    || (c.state == StreamState::Closing && !c.close_sent && c.queue.is_empty())
1226            })
1227    }
1228}
1229
1230pub mod happy_eyeballs;
1231
1232#[cfg(test)]
1233mod stream_test;