Skip to main content

bornera_rustls/
transport.rs

1//! Concrete nonblocking TCP and rustls client connection ownership.
2
3use std::net::SocketAddr;
4
5use bornera::{
6    TransportDiagnostic, TransportError, TransportFailureKind, TransportFailurePhase,
7    TransportLimits,
8};
9use calandria::Readiness;
10use mio::net::TcpStream;
11use rustls::ClientConnection;
12
13use crate::{RustlsConnectError, RustlsTransportConfig};
14
15/// One registered TCP source with a bounded rustls client connection.
16#[derive(Debug)]
17pub struct RustlsTransport {
18    pub(crate) stream: TcpStream,
19    pub(crate) tls: ClientConnection,
20    pub(crate) phase: TransportPhase,
21    pub(crate) readiness: Readiness,
22    pub(crate) preference: TlsPreference,
23    pub(crate) plaintext_bytes: usize,
24    pub(crate) eof: EofState,
25    pub(crate) shutdown: ShutdownState,
26    pub(crate) limits: crate::RustlsTransportLimits,
27    pub(crate) pending_error: Option<TransportDiagnostic>,
28}
29
30impl RustlsTransport {
31    /// Initiates one exact nonblocking TCP and rustls client attempt.
32    ///
33    /// TLS construction and memory-capacity validation occur before socket acquisition.
34    pub fn connect(
35        address: SocketAddr,
36        config: &RustlsTransportConfig,
37        supplied: TransportLimits,
38    ) -> Result<Self, RustlsConnectError> {
39        let limits = config.limits();
40        let required = limits.transport_limits().retained_bytes();
41        if required > supplied.retained_bytes() {
42            return Err(RustlsConnectError::Capacity {
43                required,
44                supplied: supplied.retained_bytes(),
45            });
46        }
47        let mut tls =
48            ClientConnection::new(config.client_config().clone(), config.server_name().clone())
49                .map_err(RustlsConnectError::Tls)?;
50        tls.set_buffer_limit(Some(limits.application_write_buffer_bytes().get()));
51        let state = tls.process_new_packets().map_err(RustlsConnectError::Tls)?;
52        limits
53            .validate_state(&state, TransportFailurePhase::Establishment)
54            .map_err(RustlsConnectError::Transport)?;
55        let stream = TcpStream::connect(address).map_err(RustlsConnectError::Io)?;
56        Ok(Self {
57            stream,
58            tls,
59            phase: TransportPhase::Connecting,
60            readiness: Readiness::EMPTY,
61            preference: TlsPreference::Write,
62            plaintext_bytes: state.plaintext_bytes_to_read(),
63            eof: EofState::Live,
64            shutdown: ShutdownState::NotStarted,
65            limits,
66            pending_error: None,
67        })
68    }
69
70    pub(crate) fn observe(&mut self, readiness: Readiness) {
71        self.readiness |= readiness;
72    }
73
74    pub(crate) fn refresh_state(
75        &mut self,
76        phase: TransportFailurePhase,
77    ) -> Result<(), TransportError> {
78        let state = self
79            .tls
80            .process_new_packets()
81            .map_err(|error| crate::diagnostic::protocol_error(phase, &error))?;
82        self.limits
83            .validate_state(&state, phase)
84            .map_err(TransportError::new)?;
85        self.plaintext_bytes = state.plaintext_bytes_to_read();
86        if state.peer_has_closed() {
87            self.eof = EofState::Clean;
88        }
89        Ok(())
90    }
91
92    pub(crate) fn record_pending_error(&mut self, diagnostic: TransportDiagnostic) {
93        self.pending_error.get_or_insert(diagnostic);
94    }
95
96    pub(crate) fn take_pending_error(&mut self) -> Option<TransportError> {
97        self.pending_error.take().map(TransportError::new)
98    }
99}
100
101impl crate::RustlsTransportLimits {
102    pub(crate) fn validate_state(
103        self,
104        state: &rustls::IoState,
105        phase: TransportFailurePhase,
106    ) -> Result<(), TransportDiagnostic> {
107        if state.tls_bytes_to_write() > self.max_tls_egress_bytes().get()
108            || state.plaintext_bytes_to_read() > self.max_plaintext_bytes().get()
109        {
110            return Err(TransportDiagnostic::new(
111                phase,
112                TransportFailureKind::Capacity,
113                std::io::ErrorKind::OutOfMemory,
114                Some(crate::RustlsDiagnostic::Capacity.code()),
115            ));
116        }
117        Ok(())
118    }
119}
120
121#[derive(Clone, Copy, Debug, Eq, PartialEq)]
122pub(crate) enum TransportPhase {
123    Connecting,
124    NoDelay,
125    Keepalive,
126    Handshaking,
127    Open,
128}
129
130#[derive(Clone, Copy, Debug, Eq, PartialEq)]
131pub(crate) enum TlsPreference {
132    Read,
133    Write,
134}
135
136#[derive(Clone, Copy, Debug, Eq, PartialEq)]
137pub(crate) enum EofState {
138    Live,
139    Clean,
140    Truncated,
141}
142
143#[derive(Clone, Copy, Debug, Eq, PartialEq)]
144pub(crate) enum ShutdownState {
145    NotStarted,
146    Started,
147}