1use std::fmt;
9
10use crate::info::ConnectionInfo;
11
12pub trait TlsAcceptor: Send + Sync + 'static {
22 type Session: TlsSession;
24
25 fn session(&self, info: &ConnectionInfo) -> Result<Self::Session, TlsError>;
31}
32
33pub trait TlsSession: Send + 'static {
37 fn step<'i>(
44 &mut self,
45 input: &'i mut [u8],
46 output: &mut [u8],
47 ) -> Result<TlsProgress<'i>, TlsError>;
48
49 fn encrypt(&mut self, plaintext: &[u8], output: &mut [u8]) -> Result<usize, TlsError>;
55
56 fn close(&mut self, output: &mut [u8]) -> Result<usize, TlsError>;
62
63 fn on_transport_closed(&mut self) -> TlsCloseKind;
65
66 fn info(&self) -> Option<TlsInfo>;
68
69 fn input_capacity_required(&self) -> usize;
71}
72
73#[must_use]
75#[derive(Debug)]
76pub struct TlsProgress<'i> {
77 pub consumed: usize,
79 pub written: usize,
81 pub event: TlsEvent<'i>,
83}
84
85#[non_exhaustive]
87#[derive(Debug)]
88pub enum TlsEvent<'i> {
89 NeedInput,
91 Transmit,
93 HandshakeComplete,
95 Data(&'i [u8]),
97 OutputFull,
99 PeerClosed,
101 Closed,
103}
104
105#[non_exhaustive]
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum TlsCloseKind {
113 Clean,
115 Unclean,
117}
118
119#[non_exhaustive]
125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
126pub enum TlsFailure {
127 Handshake,
129 HelloRefused,
131 Capacity,
133 Protocol,
135 OutputFull,
137 State,
139}
140
141#[non_exhaustive]
149#[derive(Clone, Copy, Debug, PartialEq, Eq)]
150pub struct TlsError {
151 pub kind: TlsFailure,
153 pub code: u16,
155 pub alert: Option<u8>,
157}
158
159impl TlsError {
160 #[must_use]
162 pub const fn new(kind: TlsFailure, code: u16, alert: Option<u8>) -> TlsError {
163 TlsError { kind, code, alert }
164 }
165}
166
167impl fmt::Display for TlsError {
168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169 write!(f, "{:?} (engine code {}", self.kind, self.code)?;
170 if let Some(alert) = self.alert {
171 write!(f, ", alert {alert}")?;
172 }
173 f.write_str(")")
174 }
175}
176
177impl std::error::Error for TlsError {}
178
179#[non_exhaustive]
190#[derive(Clone, Copy)]
191pub struct TlsInfo {
192 sni: [u8; 255],
193 sni_len: u8,
194 alpn: [u8; 32],
195 alpn_len: u8,
196 version: u16,
197 cipher_suite: u16,
198 peer_spki: Option<[u8; 32]>,
199}
200
201impl TlsInfo {
202 #[must_use]
204 pub fn new(
205 sni: Option<&str>,
206 alpn: Option<&[u8]>,
207 version: u16,
208 cipher_suite: u16,
209 ) -> Option<TlsInfo> {
210 let sni = sni.unwrap_or("").as_bytes();
211 let alpn = alpn.unwrap_or(&[]);
212 if sni.len() > 255 || alpn.len() > 32 {
213 return None;
214 }
215 let mut info = TlsInfo {
216 sni: [0; 255],
217 sni_len: u8::try_from(sni.len()).ok()?,
218 alpn: [0; 32],
219 alpn_len: u8::try_from(alpn.len()).ok()?,
220 version,
221 cipher_suite,
222 peer_spki: None,
223 };
224 info.sni[..sni.len()].copy_from_slice(sni);
225 info.alpn[..alpn.len()].copy_from_slice(alpn);
226 Some(info)
227 }
228
229 #[must_use]
231 pub fn sni(&self) -> Option<&str> {
232 if self.sni_len == 0 {
233 return None;
234 }
235 std::str::from_utf8(&self.sni[..usize::from(self.sni_len)]).ok()
236 }
237
238 #[must_use]
240 pub fn alpn(&self) -> Option<&[u8]> {
241 (self.alpn_len > 0).then(|| &self.alpn[..usize::from(self.alpn_len)])
242 }
243
244 #[must_use]
246 pub fn version(&self) -> u16 {
247 self.version
248 }
249
250 #[must_use]
252 pub fn cipher_suite(&self) -> u16 {
253 self.cipher_suite
254 }
255
256 #[must_use]
260 pub fn with_peer_spki_sha256(mut self, hash: [u8; 32]) -> TlsInfo {
261 self.peer_spki = Some(hash);
262 self
263 }
264
265 #[must_use]
269 pub fn peer_spki_sha256(&self) -> Option<&[u8; 32]> {
270 self.peer_spki.as_ref()
271 }
272}
273
274impl fmt::Debug for TlsInfo {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 f.debug_struct("TlsInfo")
277 .field("sni", &self.sni())
278 .field("alpn", &self.alpn().map(String::from_utf8_lossy))
279 .field("version", &format_args!("{:#06x}", self.version))
280 .field("cipher_suite", &format_args!("{:#06x}", self.cipher_suite))
281 .field("peer_spki_sha256", &self.peer_spki.map(Hex))
282 .finish()
283 }
284}
285
286struct Hex([u8; 32]);
288
289impl fmt::Debug for Hex {
290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291 self.0.iter().try_for_each(|b| write!(f, "{b:02x}"))
292 }
293}
294
295#[derive(Clone, Copy, Debug, Default)]
303pub struct NoTls;
304
305#[cfg_attr(not(feature = "tls"), allow(dead_code))]
307pub(crate) trait ErasedAcceptor: Send + Sync {
308 fn session_boxed(&self, info: &ConnectionInfo) -> Result<Box<dyn TlsSession>, TlsError>;
309}
310
311impl<A: TlsAcceptor> ErasedAcceptor for A {
312 fn session_boxed(&self, info: &ConnectionInfo) -> Result<Box<dyn TlsSession>, TlsError> {
313 match crate::gate::guarded(|| self.session(info)) {
314 Some(Ok(s)) => Ok(Box::new(Guarded {
315 inner: Box::new(s),
316 poisoned: false,
317 })),
318 Some(Err(e)) => Err(e),
319 None => Err(PANICKED),
320 }
321 }
322}
323
324const PANICKED: TlsError = TlsError::new(TlsFailure::State, u16::MAX, None);
326
327struct Guarded {
333 inner: Box<dyn TlsSession>,
334 poisoned: bool,
335}
336
337impl Guarded {
338 fn call<R>(
339 &mut self,
340 f: impl FnOnce(&mut dyn TlsSession) -> Result<R, TlsError>,
341 ) -> Result<R, TlsError> {
342 if self.poisoned {
343 return Err(PANICKED);
344 }
345 let inner = &mut *self.inner;
346 match crate::gate::guarded(|| f(inner)) {
347 Some(r) => r,
348 None => {
349 self.poisoned = true;
350 Err(PANICKED)
351 }
352 }
353 }
354}
355
356impl TlsSession for Guarded {
357 fn step<'i>(
358 &mut self,
359 input: &'i mut [u8],
360 output: &mut [u8],
361 ) -> Result<TlsProgress<'i>, TlsError> {
362 if self.poisoned {
363 return Err(PANICKED);
364 }
365 let inner = &mut *self.inner;
366 match crate::gate::guarded(move || inner.step(input, output)) {
367 Some(r) => r,
368 None => {
369 self.poisoned = true;
370 Err(PANICKED)
371 }
372 }
373 }
374
375 fn encrypt(&mut self, plaintext: &[u8], output: &mut [u8]) -> Result<usize, TlsError> {
376 self.call(|s| s.encrypt(plaintext, output))
377 }
378
379 fn close(&mut self, output: &mut [u8]) -> Result<usize, TlsError> {
380 self.call(|s| s.close(output))
381 }
382
383 fn on_transport_closed(&mut self) -> TlsCloseKind {
384 self.call(|s| Ok(s.on_transport_closed()))
385 .unwrap_or(TlsCloseKind::Unclean)
386 }
387
388 fn info(&self) -> Option<TlsInfo> {
389 if self.poisoned {
390 return None;
391 }
392 crate::gate::guarded(|| self.inner.info()).flatten()
393 }
394
395 fn input_capacity_required(&self) -> usize {
396 if self.poisoned {
397 return 0;
398 }
399 crate::gate::guarded(|| self.inner.input_capacity_required()).unwrap_or(0)
400 }
401}
402
403#[derive(Debug)]
405pub enum NoTlsSession {}
406
407impl TlsAcceptor for NoTls {
408 type Session = NoTlsSession;
409 fn session(&self, _info: &ConnectionInfo) -> Result<NoTlsSession, TlsError> {
410 Err(TlsError::new(TlsFailure::State, 0, None))
411 }
412}
413
414impl TlsSession for NoTlsSession {
415 fn step<'i>(
416 &mut self,
417 _input: &'i mut [u8],
418 _output: &mut [u8],
419 ) -> Result<TlsProgress<'i>, TlsError> {
420 match *self {}
421 }
422 fn encrypt(&mut self, _plaintext: &[u8], _output: &mut [u8]) -> Result<usize, TlsError> {
423 match *self {}
424 }
425 fn close(&mut self, _output: &mut [u8]) -> Result<usize, TlsError> {
426 match *self {}
427 }
428 fn on_transport_closed(&mut self) -> TlsCloseKind {
429 match *self {}
430 }
431 fn info(&self) -> Option<TlsInfo> {
432 match *self {}
433 }
434 fn input_capacity_required(&self) -> usize {
435 match *self {}
436 }
437}