ntex_tls/rustls/
server.rs1use std::{any, cell::RefCell, io, sync::Arc, task::Poll};
3
4use ntex_io::{Filter, FilterBuf, FilterLayer, Io, Layer};
5use ntex_util::time::Millis;
6use tls_rustls::{ServerConfig, ServerConnection};
7
8use crate::{Servername, rustls::Stream};
9
10#[derive(Debug)]
11pub struct TlsServerFilter {
18 session: RefCell<ServerConnection>,
20}
21
22impl FilterLayer for TlsServerFilter {
23 fn query(&self, id: any::TypeId) -> Option<Box<dyn any::Any>> {
26 let mut session = self.session.try_borrow_mut().ok()?;
27 if id == any::TypeId::of::<Servername>() {
28 let name = session.server_name()?;
29 Some(Box::new(Servername(name.to_string())))
30 } else {
31 Stream::new(&mut *session).query(id)
32 }
33 }
34
35 fn process_read_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
37 let mut peer_closed = false;
38 let result = self.stream(|s| s.process_read_buf(buf, &mut peer_closed));
39 if peer_closed {
41 buf.io().close();
42 }
43 result
44 }
45
46 fn process_write_buf(&self, buf: &FilterBuf<'_>) -> io::Result<()> {
47 self.stream(|s| s.process_write_buf(buf))
48 }
49
50 fn shutdown(&self, buf: &FilterBuf<'_>) -> io::Result<Poll<()>> {
51 self.stream(|s| s.shutdown(buf))
52 }
53}
54
55impl TlsServerFilter {
56 pub fn create<F: Filter>(
71 io: Io<F>,
72 cfg: Arc<ServerConfig>,
73 timeout: Millis,
74 ) -> impl Future<Output = Result<Io<Layer<TlsServerFilter, F>>, io::Error>> {
75 crate::utils::with_timeout(timeout, async move {
76 log::trace!("{}: Initiate server connection", io.tag());
77
78 let mut session = ServerConnection::new(cfg).map_err(io::Error::other)?;
79 session.set_buffer_limit(Some(io.cfg().write_size().capacity()));
80 let io = io.add_filter(TlsServerFilter {
81 session: RefCell::new(session),
82 });
83
84 crate::utils::handshake(&io, || Ok(io.filter().is_handshaking())).await?;
85 log::trace!("{}: TLS Handshake succeeded", io.tag());
86 Ok(io)
87 })
88 }
89
90 fn is_handshaking(&self) -> bool {
92 self.session.borrow().is_handshaking()
93 }
94
95 pub(super) fn stream<F, R>(&self, f: F) -> R
100 where
101 F: FnOnce(&mut Stream<'_, ServerConnection>) -> R,
102 {
103 #[cfg(test)]
104 let _borrow = crate::utils::testing::TlsBorrow::new();
105
106 let mut session = self.session.borrow_mut();
107 f(&mut Stream::new(&mut *session))
108 }
109}