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}
302
303/// How messages are delimited on a connection.
304#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
305#[non_exhaustive]
306pub enum Framing {
307 /// RFC 4571: a two-byte length before each message (ICE-TCP, RFC 6544 section 3).
308 Rfc4571,
309 /// TURN over TCP / TLS (RFC 8656 section 12.5): STUN and ChannelData messages back to
310 /// back, each delimited by its own header.
311 Turn,
312 /// None: bytes go out as they are given and come back in the pieces the socket reads.
313 /// A TURN-TCP data connection (RFC 6062 section 4.5), whose ConnectionBind exchange and
314 /// then the peer's stream its user delimits itself.
315 Raw,
316}
317
318impl Framing {
319 /// `message` as it goes on the wire.
320 ///
321 /// # Errors
322 ///
323 /// [`Error::ErrStreamMessageTooLong`] for an RFC 4571 message over 65535 bytes.
324 pub fn encode(self, message: &[u8]) -> Result<Vec<u8>> {
325 match self {
326 Framing::Rfc4571 => {
327 if message.len() > MAX_FRAMED_PACKET_SIZE {
328 return Err(Error::ErrStreamMessageTooLong);
329 }
330 let mut framed = Vec::with_capacity(FRAMING_HEADER_LEN + message.len());
331 framed.extend_from_slice(&(message.len() as u16).to_be_bytes());
332 framed.extend_from_slice(message);
333 Ok(framed)
334 }
335 Framing::Turn | Framing::Raw => Ok(message.to_vec()),
336 }
337 }
338
339 /// The most bytes one message takes on the wire, framing included.
340 fn max_wire_len(self) -> usize {
341 match self {
342 Framing::Rfc4571 => FRAMING_HEADER_LEN + MAX_FRAMED_PACKET_SIZE,
343 // A STUN header (20) or a padded ChannelData message (4 + 65535 + 1).
344 Framing::Turn => 20 + MAX_FRAMED_PACKET_SIZE,
345 Framing::Raw => MAX_FRAMED_PACKET_SIZE,
346 }
347 }
348}
349
350/// Splits a byte stream of one [`Framing`] back into its messages. Bytes can be fed in any
351/// segmentation; memory stays bounded by two messages whatever the read size, because input is
352/// taken a message's worth at a time and drained in between.
353#[derive(Debug)]
354pub struct StreamDecoder {
355 framing: Framing,
356 rfc4571: TcpFrameDecoder,
357 turn: TurnStreamDecoder,
358}
359
360impl StreamDecoder {
361 /// A decoder for `framing`.
362 pub fn new(framing: Framing) -> Self {
363 Self {
364 framing,
365 rfc4571: TcpFrameDecoder::new(),
366 turn: TurnStreamDecoder::new(),
367 }
368 }
369
370 /// Takes `data` and returns every message it completes, in order.
371 ///
372 /// # Errors
373 ///
374 /// For [`Framing::Turn`], bytes that start neither a STUN nor a ChannelData message
375 /// ([`Error::OtherTurnErr`]): the stream cannot be resynchronised and must be closed.
376 pub fn decode(&mut self, data: &[u8]) -> Result<Vec<Vec<u8>>> {
377 let mut out = Vec::new();
378 for chunk in data.chunks(self.framing.max_wire_len()) {
379 match self.framing {
380 Framing::Rfc4571 => {
381 // Never refused: at most one partial frame is held before the chunk.
382 self.rfc4571.push(chunk)?;
383 while let Some(message) = self.rfc4571.next_packet() {
384 out.push(message);
385 }
386 }
387 Framing::Turn => {
388 self.turn.extend_from_slice(chunk);
389 while let Some(message) = self.turn.next_message()? {
390 out.push(message);
391 }
392 }
393 Framing::Raw => {
394 if !chunk.is_empty() {
395 out.push(chunk.to_vec());
396 }
397 }
398 }
399 }
400 Ok(out)
401 }
402
403 /// Bytes held that do not make a whole message yet.
404 pub fn buffered_len(&self) -> usize {
405 match self.framing {
406 Framing::Rfc4571 => self.rfc4571.buffered_len(),
407 Framing::Turn => self.turn.buffered_len(),
408 Framing::Raw => 0,
409 }
410 }
411}
412
413/// A security layer between the framing and the socket: TLS for TURN over TLS, in its
414/// sans-I/O form. Ciphertext comes in with [`receive`](Self::receive), plaintext goes out
415/// with [`send`](Self::send) once the handshake [is done](Self::is_established), and the
416/// table collects what the layer has to write after every call.
417pub trait StreamLayer: Send {
418 /// Takes bytes received from the peer and processes them.
419 ///
420 /// # Errors
421 ///
422 /// A protocol error (bad record, failed certificate verification): the connection is
423 /// reset.
424 fn receive(&mut self, data: &[u8]) -> Result<()>;
425 /// Appends the plaintext received so far to `out`.
426 fn read_plaintext(&mut self, out: &mut Vec<u8>) -> Result<()>;
427 /// Whether plaintext can be sent: the handshake is complete.
428 fn is_established(&self) -> bool;
429 /// Takes plaintext to send.
430 fn send(&mut self, plaintext: &[u8]) -> Result<()>;
431 /// Appends the bytes the layer has to write to `out`.
432 fn write_wire(&mut self, out: &mut Vec<u8>) -> Result<()>;
433 /// Starts an orderly close (TLS `close_notify`).
434 fn close(&mut self);
435 /// Whether the peer closed the layer (TLS `close_notify` received).
436 fn peer_closed(&self) -> bool;
437}
438
439/// Limits of a [`StreamTable`].
440#[derive(Debug, Clone, Copy, PartialEq, Eq)]
441pub struct StreamConfig {
442 /// Bytes of a connection handed to the driver and not yet reported written, beyond which
443 /// no more is handed out (one transmit is always allowed).
444 pub window: usize,
445 /// Bytes of a connection queued in the engine, beyond which a message is dropped whole.
446 pub max_queued: usize,
447 /// Connections at most, accepted ones included; an accept beyond it is refused.
448 pub max_connections: usize,
449}
450
451impl Default for StreamConfig {
452 fn default() -> Self {
453 Self {
454 window: 64 * 1024,
455 max_queued: 512 * 1024,
456 max_connections: 256,
457 }
458 }
459}
460
461/// How a connection came to be.
462#[derive(Debug, Clone, Copy, PartialEq, Eq)]
463#[non_exhaustive]
464pub enum StreamOrigin {
465 /// The engine asked for it ([`StreamCommand::Connect`]).
466 Connected,
467 /// The driver accepted it on a listener.
468 Accepted(ListenerId),
469}
470
471/// Where a connection is in its life.
472#[derive(Debug, Clone, Copy, PartialEq, Eq)]
473#[non_exhaustive]
474pub enum StreamState {
475 /// Asked for, not yet established.
476 Connecting,
477 /// Established.
478 Open,
479 /// The engine closed it; the driver writes what it holds, then closes.
480 Closing,
481}
482
483/// A connection, as [`StreamTable::info`] describes it.
484#[derive(Debug, Clone, Copy, PartialEq, Eq)]
485pub struct StreamInfo {
486 /// Its id.
487 pub id: StreamId,
488 /// The owner's tag, given when it was opened or when its listener was.
489 pub tag: u32,
490 /// How it came to be.
491 pub origin: StreamOrigin,
492 /// Its state.
493 pub state: StreamState,
494 /// Its local address: the requested one until it is established, then the bound one.
495 pub local: SocketAddr,
496 /// The local address it was asked for (port 0: any).
497 pub requested_local: SocketAddr,
498 /// The peer's address.
499 pub remote: SocketAddr,
500 /// Its framing.
501 pub framing: Framing,
502 /// Messages sent and received, and messages dropped by back-pressure.
503 pub messages_sent: u64,
504 /// Messages received.
505 pub messages_received: u64,
506 /// Messages dropped because the queue was full.
507 pub messages_dropped: u64,
508 /// Bytes handed to the driver and not yet reported written.
509 pub in_flight: usize,
510 /// Bytes queued in the engine.
511 pub queued: usize,
512}
513
514/// What a [`StreamTable`] reports to its owner, in the order it happened.
515#[derive(Debug, Clone, PartialEq, Eq)]
516#[non_exhaustive]
517pub enum StreamNotice {
518 /// A listener is bound.
519 Listening {
520 /// The listener.
521 listener: ListenerId,
522 /// Its tag.
523 tag: u32,
524 /// The bound address.
525 local: SocketAddr,
526 },
527 /// A listener could not be bound.
528 ListenFailed {
529 /// The listener.
530 listener: ListenerId,
531 /// Its tag.
532 tag: u32,
533 /// The address it was asked for.
534 requested: SocketAddr,
535 },
536 /// A connection the engine asked for is established.
537 Connected {
538 /// The connection.
539 id: StreamId,
540 /// Its tag.
541 tag: u32,
542 /// Its local address.
543 local: SocketAddr,
544 /// The peer.
545 remote: SocketAddr,
546 },
547 /// A connection the engine asked for could not be established; its queued messages are
548 /// gone.
549 ConnectFailed {
550 /// The connection.
551 id: StreamId,
552 /// Its tag.
553 tag: u32,
554 /// The local address it was asked for.
555 local: SocketAddr,
556 /// The peer.
557 remote: SocketAddr,
558 },
559 /// A connection is gone: closed (`reset` false) or broken (`reset` true). Not reported
560 /// for a connection the engine reset itself.
561 Closed {
562 /// The connection.
563 id: StreamId,
564 /// Its tag.
565 tag: u32,
566 /// Its local address.
567 local: SocketAddr,
568 /// The peer.
569 remote: SocketAddr,
570 /// Whether it broke rather than closed.
571 reset: bool,
572 },
573 /// A name the engine asked for was resolved.
574 Resolved {
575 /// The query.
576 query: u64,
577 /// The addresses (empty: the name did not resolve).
578 addresses: Vec<SocketAddr>,
579 },
580 /// Records the engine asked for were looked up.
581 ResolvedRecords {
582 /// The query.
583 query: u64,
584 /// The records (possibly none).
585 records: Vec<DnsRecord>,
586 },
587 /// One family of a name the engine asked for was resolved.
588 ResolvedFamily {
589 /// The query.
590 query: u64,
591 /// Whether these are the IPv6 addresses.
592 ipv6: bool,
593 /// The addresses of that family (possibly none).
594 addresses: Vec<SocketAddr>,
595 },
596}
597
598struct Listener {
599 tag: u32,
600 framing: Framing,
601 requested: SocketAddr,
602 bound: Option<SocketAddr>,
603}
604
605struct Connection {
606 tag: u32,
607 origin: StreamOrigin,
608 state: StreamState,
609 requested_local: SocketAddr,
610 local: SocketAddr,
611 remote: SocketAddr,
612 framing: Framing,
613 decoder: StreamDecoder,
614 layer: Option<Box<dyn StreamLayer>>,
615 /// Framed messages waiting for the layer's handshake.
616 pending_plaintext: VecDeque<Vec<u8>>,
617 /// Wire bytes not yet handed to the driver.
618 queue: VecDeque<Vec<u8>>,
619 queued: usize,
620 in_flight: usize,
621 close_sent: bool,
622 messages_sent: u64,
623 messages_received: u64,
624 messages_dropped: u64,
625}
626
627impl Connection {
628 fn info(&self, id: StreamId) -> StreamInfo {
629 StreamInfo {
630 id,
631 tag: self.tag,
632 origin: self.origin,
633 state: self.state,
634 local: self.local,
635 requested_local: self.requested_local,
636 remote: self.remote,
637 framing: self.framing,
638 messages_sent: self.messages_sent,
639 messages_received: self.messages_received,
640 messages_dropped: self.messages_dropped,
641 in_flight: self.in_flight,
642 queued: self.queued,
643 }
644 }
645
646 fn enqueue_wire(&mut self, bytes: Vec<u8>) {
647 if !bytes.is_empty() {
648 self.queued += bytes.len();
649 self.queue.push_back(bytes);
650 }
651 }
652
653 /// Moves what the layer has to write into the queue.
654 fn collect_layer_output(&mut self) -> Result<()> {
655 if let Some(layer) = self.layer.as_mut() {
656 let mut out = Vec::new();
657 layer.write_wire(&mut out)?;
658 self.enqueue_wire(out);
659 }
660 Ok(())
661 }
662
663 /// Hands messages that waited for the handshake to the layer once it is established.
664 fn flush_pending_plaintext(&mut self) -> Result<()> {
665 let Some(layer) = self.layer.as_mut() else {
666 return Ok(());
667 };
668 if !layer.is_established() {
669 return Ok(());
670 }
671 while let Some(frame) = self.pending_plaintext.pop_front() {
672 self.queued -= frame.len();
673 layer.send(&frame)?;
674 }
675 self.collect_layer_output()
676 }
677}
678
679/// The engine's side of its stream transports: listeners, connections, framing, the optional
680/// security layer and back-pressure. See the [module documentation](self).
681///
682/// The *tag* given to [`listen`](Self::listen) and [`connect`](Self::connect) is the owner's:
683/// one table can serve several users (ICE-TCP and a TURN client, say), each finding its
684/// connections by tag.
685pub struct StreamTable {
686 config: StreamConfig,
687 next_id: u64,
688 next_listener: u64,
689 connections: BTreeMap<StreamId, Connection>,
690 listeners: BTreeMap<ListenerId, Listener>,
691 commands: VecDeque<StreamCommand>,
692 notices: VecDeque<StreamNotice>,
693 last_transmit: Option<StreamId>,
694 next_query: u64,
695}
696
697impl fmt::Debug for StreamTable {
698 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
699 f.debug_struct("StreamTable")
700 .field("connections", &self.connections.len())
701 .field("listeners", &self.listeners.len())
702 .field("commands", &self.commands.len())
703 .finish()
704 }
705}
706
707impl Default for StreamTable {
708 fn default() -> Self {
709 Self::new(StreamConfig::default())
710 }
711}
712
713impl StreamTable {
714 /// An empty table.
715 pub fn new(config: StreamConfig) -> Self {
716 Self {
717 config,
718 next_id: 1,
719 next_listener: 1,
720 connections: BTreeMap::new(),
721 listeners: BTreeMap::new(),
722 commands: VecDeque::new(),
723 notices: VecDeque::new(),
724 last_transmit: None,
725 next_query: 1,
726 }
727 }
728
729 /// Its limits.
730 pub fn config(&self) -> StreamConfig {
731 self.config
732 }
733
734 /// Asks the driver to listen on `local`; connections it accepts get `framing` and `tag`.
735 pub fn listen(
736 &mut self,
737 local: SocketAddr,
738 framing: Framing,
739 tag: u32,
740 reuse_address: bool,
741 ) -> ListenerId {
742 let listener = ListenerId(self.next_listener);
743 self.next_listener += 1;
744 self.listeners.insert(
745 listener,
746 Listener {
747 tag,
748 framing,
749 requested: local,
750 bound: None,
751 },
752 );
753 self.commands.push_back(StreamCommand::Listen {
754 listener,
755 local,
756 reuse_address,
757 });
758 listener
759 }
760
761 /// Asks the driver to resolve `host`; the answer comes as [`StreamNotice::Resolved`] with
762 /// the returned query id.
763 pub fn resolve(&mut self, host: String, port: u16) -> u64 {
764 let query = self.next_query;
765 self.next_query += 1;
766 self.commands
767 .push_back(StreamCommand::Resolve { query, host, port });
768 query
769 }
770
771 /// Asks the driver for the `kind` records of `name`; the answer comes as
772 /// [`StreamNotice::ResolvedRecords`] with the returned query id (ids are shared with
773 /// [`resolve`](Self::resolve)).
774 pub fn resolve_records(&mut self, name: String, kind: RecordKind) -> u64 {
775 let query = self.next_query;
776 self.next_query += 1;
777 self.commands
778 .push_back(StreamCommand::ResolveRecords { query, name, kind });
779 query
780 }
781
782 /// Asks the driver to close the listener. Unknown listeners are ignored.
783 pub fn stop_listening(&mut self, listener: ListenerId) {
784 if self.listeners.remove(&listener).is_some() {
785 self.commands
786 .push_back(StreamCommand::StopListening { listener });
787 }
788 }
789
790 /// The address a listener is bound to, once the driver said so.
791 pub fn listener_address(&self, listener: ListenerId) -> Option<SocketAddr> {
792 self.listeners.get(&listener).and_then(|l| l.bound)
793 }
794
795 /// The listeners: id, tag, requested and bound address.
796 pub fn listeners(
797 &self,
798 ) -> impl Iterator<Item = (ListenerId, u32, SocketAddr, Option<SocketAddr>)> + '_ {
799 self.listeners
800 .iter()
801 .map(|(id, l)| (*id, l.tag, l.requested, l.bound))
802 }
803
804 /// Asks the driver for a connection from `local` (port 0: ephemeral) to `remote`. Messages
805 /// can be sent at once; they wait for the connection. With a `layer`, what it writes first
806 /// (a TLS ClientHello) is sent first, and messages wait for its handshake.
807 ///
808 /// # Errors
809 ///
810 /// [`Error::ErrBufferFull`] when the table holds [`StreamConfig::max_connections`]; an
811 /// error of the layer.
812 pub fn connect(
813 &mut self,
814 local: SocketAddr,
815 remote: SocketAddr,
816 framing: Framing,
817 tag: u32,
818 reuse_address: bool,
819 layer: Option<Box<dyn StreamLayer>>,
820 ) -> Result<StreamId> {
821 if self.connections.len() >= self.config.max_connections {
822 return Err(Error::ErrBufferFull);
823 }
824 let id = StreamId(self.next_id);
825 self.next_id += 1;
826 let mut connection = Connection {
827 tag,
828 origin: StreamOrigin::Connected,
829 state: StreamState::Connecting,
830 requested_local: local,
831 local,
832 remote,
833 framing,
834 decoder: StreamDecoder::new(framing),
835 layer,
836 pending_plaintext: VecDeque::new(),
837 queue: VecDeque::new(),
838 queued: 0,
839 in_flight: 0,
840 close_sent: false,
841 messages_sent: 0,
842 messages_received: 0,
843 messages_dropped: 0,
844 };
845 connection.collect_layer_output()?;
846 self.connections.insert(id, connection);
847 self.commands.push_back(StreamCommand::Connect {
848 id,
849 local,
850 remote,
851 reuse_address,
852 });
853 Ok(id)
854 }
855
856 /// The driver accepted a connection from `remote` on `listener`, arriving on `local`.
857 /// Returns its id, or `None` when the listener is unknown or the table is full: the driver
858 /// closes the socket then.
859 pub fn accept(
860 &mut self,
861 listener: ListenerId,
862 local: SocketAddr,
863 remote: SocketAddr,
864 ) -> Option<StreamId> {
865 let (tag, framing) = {
866 let l = self.listeners.get(&listener)?;
867 (l.tag, l.framing)
868 };
869 if self.connections.len() >= self.config.max_connections {
870 return None;
871 }
872 let id = StreamId(self.next_id);
873 self.next_id += 1;
874 self.connections.insert(
875 id,
876 Connection {
877 tag,
878 origin: StreamOrigin::Accepted(listener),
879 state: StreamState::Open,
880 requested_local: local,
881 local,
882 remote,
883 framing,
884 decoder: StreamDecoder::new(framing),
885 layer: None,
886 pending_plaintext: VecDeque::new(),
887 queue: VecDeque::new(),
888 queued: 0,
889 in_flight: 0,
890 close_sent: false,
891 messages_sent: 0,
892 messages_received: 0,
893 messages_dropped: 0,
894 },
895 );
896 Some(id)
897 }
898
899 /// Queues `message` on the connection, framed (and encrypted with its layer). Returns
900 /// `false` when back-pressure dropped it: the connection already holds
901 /// [`StreamConfig::max_queued`] bytes.
902 ///
903 /// # Errors
904 ///
905 /// [`Error::ErrUnknownStream`], [`Error::ErrStreamConnectionClosed`] (closing),
906 /// [`Error::ErrStreamMessageTooLong`], or an error of the layer.
907 pub fn send(&mut self, id: StreamId, message: &[u8]) -> Result<bool> {
908 let max_queued = self.config.max_queued;
909 let connection = self
910 .connections
911 .get_mut(&id)
912 .ok_or(Error::ErrUnknownStream)?;
913 if connection.state == StreamState::Closing {
914 return Err(Error::ErrStreamConnectionClosed);
915 }
916 let frame = connection.framing.encode(message)?;
917 if connection.queued > 0 && connection.queued + frame.len() > max_queued {
918 connection.messages_dropped += 1;
919 return Ok(false);
920 }
921 connection.messages_sent += 1;
922 match connection.layer.as_mut() {
923 Some(layer) if layer.is_established() && connection.pending_plaintext.is_empty() => {
924 layer.send(&frame)?;
925 connection.collect_layer_output()?;
926 }
927 Some(_) => {
928 connection.queued += frame.len();
929 connection.pending_plaintext.push_back(frame);
930 }
931 None => connection.enqueue_wire(frame),
932 }
933 Ok(true)
934 }
935
936 /// Bytes the driver read from the connection, in whatever piece: returns the messages
937 /// they complete, in order.
938 ///
939 /// # Errors
940 ///
941 /// [`Error::ErrUnknownStream`]; a stream that is not of its framing (TURN) or a layer
942 /// error: the connection is then reset ([`StreamCommand::Reset`] is issued) and reported
943 /// [`StreamNotice::Closed`].
944 pub fn read(&mut self, id: StreamId, data: &[u8]) -> Result<Vec<Vec<u8>>> {
945 let connection = self
946 .connections
947 .get_mut(&id)
948 .ok_or(Error::ErrUnknownStream)?;
949 let result = (|| {
950 let plaintext = match connection.layer.as_mut() {
951 Some(layer) => {
952 layer.receive(data)?;
953 let mut plaintext = Vec::new();
954 layer.read_plaintext(&mut plaintext)?;
955 connection.collect_layer_output()?;
956 connection.flush_pending_plaintext()?;
957 plaintext
958 }
959 None => data.to_vec(),
960 };
961 connection.decoder.decode(&plaintext)
962 })();
963 match result {
964 Ok(messages) => {
965 connection.messages_received += messages.len() as u64;
966 let peer_closed = connection
967 .layer
968 .as_ref()
969 .is_some_and(|layer| layer.peer_closed());
970 if peer_closed && connection.state != StreamState::Closing {
971 self.close(id);
972 }
973 Ok(messages)
974 }
975 Err(err) => {
976 self.fail(id, true);
977 Err(err)
978 }
979 }
980 }
981
982 /// Closes the connection in order: what is queued is still handed out, then
983 /// [`StreamCommand::Close`] is issued. A connection still connecting is reset instead.
984 /// Unknown ids are ignored.
985 pub fn close(&mut self, id: StreamId) {
986 let Some(connection) = self.connections.get_mut(&id) else {
987 return;
988 };
989 match connection.state {
990 StreamState::Connecting => self.reset(id),
991 StreamState::Closing => {}
992 StreamState::Open => {
993 connection.state = StreamState::Closing;
994 // Messages still waiting for a handshake will never be sent.
995 for frame in connection.pending_plaintext.drain(..) {
996 connection.queued -= frame.len();
997 }
998 if let Some(layer) = connection.layer.as_mut() {
999 layer.close();
1000 }
1001 let _ = connection.collect_layer_output();
1002 self.issue_closes();
1003 }
1004 }
1005 }
1006
1007 /// Aborts the connection: [`StreamCommand::Reset`] is issued and the id forgotten. Unknown
1008 /// ids are ignored.
1009 pub fn reset(&mut self, id: StreamId) {
1010 if self.connections.remove(&id).is_some() {
1011 self.commands.push_back(StreamCommand::Reset { id });
1012 }
1013 }
1014
1015 /// Takes an event from the driver. Events for ids the table no longer knows (a connection
1016 /// it reset, a listener it stopped) are ignored: they cross on the way.
1017 ///
1018 /// # Errors
1019 ///
1020 /// An error of a connection's layer once it is established.
1021 pub fn handle_event(&mut self, event: StreamEvent) -> Result<()> {
1022 match event {
1023 StreamEvent::Listening { listener, local } => {
1024 if let Some(l) = self.listeners.get_mut(&listener) {
1025 l.bound = Some(local);
1026 self.notices.push_back(StreamNotice::Listening {
1027 listener,
1028 tag: l.tag,
1029 local,
1030 });
1031 }
1032 }
1033 StreamEvent::ListenFailed { listener } => {
1034 if let Some(l) = self.listeners.remove(&listener) {
1035 self.notices.push_back(StreamNotice::ListenFailed {
1036 listener,
1037 tag: l.tag,
1038 requested: l.requested,
1039 });
1040 }
1041 }
1042 StreamEvent::Connected { id, local } => {
1043 if let Some(connection) = self.connections.get_mut(&id)
1044 && connection.state == StreamState::Connecting
1045 {
1046 connection.state = StreamState::Open;
1047 connection.local = local;
1048 self.notices.push_back(StreamNotice::Connected {
1049 id,
1050 tag: connection.tag,
1051 local,
1052 remote: connection.remote,
1053 });
1054 }
1055 }
1056 StreamEvent::ConnectFailed { id } => {
1057 if let Some(connection) = self.connections.remove(&id) {
1058 self.notices.push_back(StreamNotice::ConnectFailed {
1059 id,
1060 tag: connection.tag,
1061 local: connection.requested_local,
1062 remote: connection.remote,
1063 });
1064 }
1065 }
1066 StreamEvent::Written { id, bytes } => {
1067 if let Some(connection) = self.connections.get_mut(&id) {
1068 connection.in_flight = connection.in_flight.saturating_sub(bytes);
1069 }
1070 }
1071 StreamEvent::Closed { id } => self.fail(id, false),
1072 StreamEvent::Reset { id } => self.fail(id, true),
1073 StreamEvent::Resolved { query, addresses } => self
1074 .notices
1075 .push_back(StreamNotice::Resolved { query, addresses }),
1076 StreamEvent::ResolvedRecords { query, records } => self
1077 .notices
1078 .push_back(StreamNotice::ResolvedRecords { query, records }),
1079 StreamEvent::ResolvedFamily {
1080 query,
1081 ipv6,
1082 addresses,
1083 } => self.notices.push_back(StreamNotice::ResolvedFamily {
1084 query,
1085 ipv6,
1086 addresses,
1087 }),
1088 }
1089 Ok(())
1090 }
1091
1092 /// Forgets a connection that ended and reports it; with `issue_reset`, also tells the
1093 /// driver to abort it (an engine-side error).
1094 fn fail(&mut self, id: StreamId, reset: bool) {
1095 if let Some(connection) = self.connections.remove(&id) {
1096 self.notices.push_back(StreamNotice::Closed {
1097 id,
1098 tag: connection.tag,
1099 local: connection.local,
1100 remote: connection.remote,
1101 reset,
1102 });
1103 if reset {
1104 self.commands.push_back(StreamCommand::Reset { id });
1105 }
1106 }
1107 }
1108
1109 /// Issues [`StreamCommand::Close`] for closing connections with nothing left to hand out.
1110 fn issue_closes(&mut self) {
1111 for (id, connection) in self.connections.iter_mut() {
1112 if connection.state == StreamState::Closing
1113 && !connection.close_sent
1114 && connection.queue.is_empty()
1115 {
1116 connection.close_sent = true;
1117 self.commands.push_back(StreamCommand::Close { id: *id });
1118 }
1119 }
1120 }
1121
1122 /// The next command for the driver.
1123 pub fn poll_command(&mut self) -> Option<StreamCommand> {
1124 self.issue_closes();
1125 self.commands.pop_front()
1126 }
1127
1128 /// The next notice for the owner.
1129 pub fn poll_notice(&mut self) -> Option<StreamNotice> {
1130 self.notices.pop_front()
1131 }
1132
1133 /// The next bytes to write, connections taking turns. Only established connections
1134 /// transmit, each within its [window](StreamConfig::window).
1135 pub fn poll_transmit(&mut self) -> Option<StreamTransmit> {
1136 let window = self.config.window;
1137 let start = self.last_transmit.map_or(Bound::Unbounded, Bound::Excluded);
1138 let candidates: Vec<StreamId> = self
1139 .connections
1140 .range((start, Bound::Unbounded))
1141 .chain(self.connections.range(..))
1142 .filter(|(_, c)| {
1143 c.state != StreamState::Connecting
1144 && c.queue.front().is_some_and(|front| {
1145 c.in_flight == 0 || c.in_flight + front.len() <= window
1146 })
1147 })
1148 .map(|(id, _)| *id)
1149 .take(1)
1150 .collect();
1151 let id = *candidates.first()?;
1152 let connection = self.connections.get_mut(&id)?;
1153 let mut data = connection.queue.pop_front()?;
1154 // Coalesce what else fits in the window.
1155 while let Some(next) = connection.queue.front() {
1156 if connection.in_flight + data.len() + next.len() > window {
1157 break;
1158 }
1159 let next = connection.queue.pop_front()?;
1160 data.extend_from_slice(&next);
1161 }
1162 connection.queued -= data.len();
1163 connection.in_flight += data.len();
1164 self.last_transmit = Some(id);
1165 if connection.state == StreamState::Closing && connection.queue.is_empty() {
1166 self.issue_closes();
1167 }
1168 Some(StreamTransmit { id, data })
1169 }
1170
1171 /// A connection's description, while the table knows it.
1172 pub fn info(&self, id: StreamId) -> Option<StreamInfo> {
1173 self.connections.get(&id).map(|c| c.info(id))
1174 }
1175
1176 /// Every connection.
1177 pub fn connections(&self) -> impl Iterator<Item = StreamInfo> + '_ {
1178 self.connections.iter().map(|(id, c)| c.info(*id))
1179 }
1180
1181 /// A connection of `tag` to `remote` from `local` that can still carry data (not closing),
1182 /// an established one before one still connecting. With `local_ip_only`, any local port
1183 /// on `local`'s address matches (an RFC 6544 active candidate, whose connections each get
1184 /// an ephemeral port).
1185 pub fn find(
1186 &self,
1187 tag: u32,
1188 local: SocketAddr,
1189 remote: SocketAddr,
1190 local_ip_only: bool,
1191 ) -> Option<StreamId> {
1192 let matches = |c: &Connection| {
1193 c.tag == tag
1194 && c.remote == remote
1195 && c.state != StreamState::Closing
1196 && (if local_ip_only {
1197 c.local.ip() == local.ip()
1198 } else {
1199 c.local == local
1200 || (c.state == StreamState::Connecting && c.requested_local == local)
1201 })
1202 };
1203 let mut connecting = None;
1204 for (id, c) in &self.connections {
1205 if matches(c) {
1206 if c.state == StreamState::Open {
1207 return Some(*id);
1208 }
1209 connecting.get_or_insert(*id);
1210 }
1211 }
1212 connecting
1213 }
1214
1215 /// Whether anything is waiting for the driver: a command or a transmit it may take.
1216 pub fn has_output(&self) -> bool {
1217 !self.commands.is_empty()
1218 || self.connections.values().any(|c| {
1219 (c.state != StreamState::Connecting && !c.queue.is_empty())
1220 || (c.state == StreamState::Closing && !c.close_sent && c.queue.is_empty())
1221 })
1222 }
1223}
1224
1225pub mod happy_eyeballs;
1226
1227#[cfg(test)]
1228mod stream_test;