Skip to main content

bornera_rustls/
client_session.rs

1//! Socket-free bounded rustls client progression driven by an external owner.
2
3use bornera::{
4    TransportDiagnostic, TransportError, TransportFailurePhase, TransportLimits, TransportPressure,
5};
6use rustls::ClientConnection;
7
8use crate::{
9    RustlsClientSessionError, RustlsClientStatus, RustlsPeerClosure, RustlsTransportConfig,
10    RustlsTransportLimits,
11    client_status::{
12        STATUS_CLOSE_NOTIFY_SENT, STATUS_HANDSHAKING, STATUS_OPEN, STATUS_WANTS_READ,
13        STATUS_WANTS_WRITE,
14    },
15    diagnostic::protocol_error,
16};
17
18/// One bounded rustls client connection without a socket, clock, task, or runtime.
19#[derive(Debug)]
20pub struct RustlsClientSession {
21    pub(crate) tls: ClientConnection,
22    pub(crate) limits: RustlsTransportLimits,
23    pub(crate) plaintext_bytes: usize,
24    pub(crate) tls_egress_bytes: usize,
25    pub(crate) peer_closure: RustlsPeerClosure,
26    pub(crate) opened: bool,
27    pub(crate) close_notify_sent: bool,
28    pub(crate) failure: Option<TransportDiagnostic>,
29}
30
31impl RustlsClientSession {
32    /// Constructs a session only when its stable charge fits the supplied ceiling.
33    pub fn new(
34        config: &RustlsTransportConfig,
35        supplied: TransportLimits,
36    ) -> Result<Self, RustlsClientSessionError> {
37        let limits = config.limits();
38        let required = limits.transport_limits().retained_bytes();
39        if required > supplied.retained_bytes() {
40            return Err(RustlsClientSessionError::Capacity {
41                required,
42                supplied: supplied.retained_bytes(),
43            });
44        }
45        let mut tls =
46            ClientConnection::new(config.client_config().clone(), config.server_name().clone())
47                .map_err(RustlsClientSessionError::Tls)?;
48        tls.set_buffer_limit(Some(limits.application_write_buffer_bytes().get()));
49        let state = tls
50            .process_new_packets()
51            .map_err(RustlsClientSessionError::Tls)?;
52        limits
53            .validate_state(&state, TransportFailurePhase::Establishment)
54            .map_err(RustlsClientSessionError::Transport)?;
55        Ok(Self {
56            plaintext_bytes: state.plaintext_bytes_to_read(),
57            tls_egress_bytes: state.tls_bytes_to_write(),
58            tls,
59            limits,
60            peer_closure: RustlsPeerClosure::Open,
61            opened: false,
62            close_notify_sent: false,
63            failure: None,
64        })
65    }
66
67    /// Returns the exact externally actionable session state.
68    pub fn status(&self) -> RustlsClientStatus {
69        let failed = self.failure.is_some();
70        let wants_read =
71            self.tls.wants_read() && self.peer_closure == RustlsPeerClosure::Open && !failed;
72        let flags = (u8::from(self.tls.is_handshaking()) * STATUS_HANDSHAKING)
73            | (u8::from(self.opened && !self.close_notify_sent && !failed) * STATUS_OPEN)
74            | (u8::from(wants_read) * STATUS_WANTS_READ)
75            | (u8::from(self.tls.wants_write()) * STATUS_WANTS_WRITE)
76            | (u8::from(self.close_notify_sent) * STATUS_CLOSE_NOTIFY_SENT);
77        RustlsClientStatus {
78            flags,
79            readable_plaintext_bytes: self.plaintext_bytes,
80            tls_egress_bytes: self.tls_egress_bytes,
81            peer_closure: self.peer_closure,
82            failure: self.failure,
83        }
84    }
85
86    /// Returns the exact stable charge reserved for this session.
87    pub const fn pressure(&self) -> TransportPressure {
88        self.limits.pressure()
89    }
90
91    /// Returns the logical and accounting limits enforced by this session.
92    pub const fn limits(&self) -> RustlsTransportLimits {
93        self.limits
94    }
95
96    /// Returns the negotiated ALPN identifier without copying it.
97    pub fn alpn_protocol(&self) -> Option<&[u8]> {
98        self.tls.alpn_protocol()
99    }
100
101    pub(crate) fn refresh(&mut self, phase: TransportFailurePhase) -> Result<(), TransportError> {
102        let state = self
103            .tls
104            .process_new_packets()
105            .map_err(|error| protocol_error(phase, &error))?;
106        self.limits
107            .validate_state(&state, phase)
108            .map_err(TransportError::new)?;
109        self.plaintext_bytes = state.plaintext_bytes_to_read();
110        self.tls_egress_bytes = state.tls_bytes_to_write();
111        if state.peer_has_closed() {
112            self.peer_closure = RustlsPeerClosure::Clean;
113        }
114        if !self.tls.is_handshaking() && !self.tls.wants_write() {
115            self.opened = true;
116        }
117        Ok(())
118    }
119
120    pub(crate) fn ensure_progressing(&self) -> Result<(), TransportError> {
121        self.failure
122            .map_or(Ok(()), |diagnostic| Err(TransportError::new(diagnostic)))
123    }
124
125    pub(crate) fn latch(&mut self, diagnostic: TransportDiagnostic) -> TransportError {
126        self.failure.get_or_insert(diagnostic);
127        TransportError::new(diagnostic)
128    }
129
130    pub(crate) fn read_phase(&self) -> TransportFailurePhase {
131        if self.tls.is_handshaking() {
132            TransportFailurePhase::Establishment
133        } else {
134            TransportFailurePhase::TransportRead
135        }
136    }
137
138    pub(crate) fn write_phase(&self) -> TransportFailurePhase {
139        if self.tls.is_handshaking() {
140            TransportFailurePhase::Establishment
141        } else if self.close_notify_sent {
142            TransportFailurePhase::Shutdown
143        } else {
144            TransportFailurePhase::TransportWrite
145        }
146    }
147
148    pub(crate) fn ingress_limit(&self) -> usize {
149        usize::try_from(self.limits.pressure().inbound().get()).unwrap_or(usize::MAX)
150    }
151}