1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
use std::sync::Arc;

use async_trait::async_trait;
use rustls::server::ResolvesServerCert;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpListener;

use crate::{Backend, CustomServer, Error};

impl<B: Backend> CustomServer<B> {
    /// Listens for HTTP traffic on `port`. This port will also receive
    /// `WebSocket` connections if feature `websockets` is enabled.
    pub async fn listen_for_tcp_on<S: TcpService, T: tokio::net::ToSocketAddrs + Send + Sync>(
        &self,
        addr: T,
        service: S,
    ) -> Result<(), Error> {
        let listener = TcpListener::bind(&addr).await?;
        let mut shutdown_watcher = self
            .data
            .shutdown
            .watcher()
            .await
            .expect("server already shutdown");

        loop {
            tokio::select! {
                _ = shutdown_watcher.wait_for_shutdown() => {
                    break;
                }
                incoming = listener.accept() => {
                    if incoming.is_err() {
                        continue;
                    }
                    let (connection, remote_addr) = incoming.unwrap();

                    let peer = Peer {
                        address: remote_addr,
                        protocol: service.available_protocols()[0].clone(),
                        secure: false,
                    };

                    let task_self = self.clone();
                    let task_service = service.clone();
                    tokio::spawn(async move {
                        if let Err(err) = task_self.handle_tcp_connection(connection, peer, &task_service).await {
                            log::error!("[server] closing connection {}: {:?}", remote_addr, err);
                        }
                    });
                }
            }
        }

        Ok(())
    }

    /// Listens for HTTPS traffic on `port`. This port will also receive
    /// `WebSocket` connections if feature `websockets` is enabled. If feature
    /// `acme` is enabled, this connection will automatically manage the
    /// server's private key and certificate, which is also used for the
    /// QUIC-based protocol.
    #[cfg_attr(not(feature = "websockets"), allow(unused_variables))]
    #[cfg_attr(not(feature = "acme"), allow(unused_mut))]
    pub async fn listen_for_secure_tcp_on<
        S: TcpService,
        T: tokio::net::ToSocketAddrs + Send + Sync,
    >(
        &self,
        addr: T,
        service: S,
    ) -> Result<(), Error> {
        // We may not have a certificate yet, so we ignore any errors.
        drop(self.refresh_certified_key().await);

        #[cfg(feature = "acme")]
        {
            let task_self = self.clone();
            tokio::task::spawn(async move {
                if let Err(err) = task_self.update_acme_certificates().await {
                    log::error!("[server] acme task error: {0}", err);
                }
            });
        }

        let mut config = rustls::ServerConfig::builder()
            .with_safe_defaults()
            .with_no_client_auth()
            .with_cert_resolver(Arc::new(self.clone()));
        config.alpn_protocols = service
            .available_protocols()
            .iter()
            .map(|proto| proto.alpn_name().to_vec())
            .collect();

        let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config));
        let listener = TcpListener::bind(&addr).await?;
        loop {
            let (stream, peer_addr) = listener.accept().await?;
            let acceptor = acceptor.clone();

            let task_self = self.clone();
            let task_service = service.clone();
            tokio::task::spawn(async move {
                let stream = match acceptor.accept(stream).await {
                    Ok(stream) => stream,
                    Err(err) => {
                        log::error!("[server] error during tls handshake: {:?}", err);
                        return;
                    }
                };

                let available_protocols = task_service.available_protocols();
                let protocol = stream
                    .get_ref()
                    .1
                    .alpn_protocol()
                    .and_then(|protocol| {
                        available_protocols
                            .iter()
                            .find(|p| p.alpn_name() == protocol)
                            .cloned()
                    })
                    .unwrap_or_else(|| available_protocols[0].clone());
                let peer = Peer {
                    address: peer_addr,
                    secure: true,
                    protocol,
                };
                if let Err(err) = task_self
                    .handle_tcp_connection(stream, peer, &task_service)
                    .await
                {
                    log::error!("[server] error for client {}: {:?}", peer_addr, err);
                }
            });
        }
    }

    #[cfg_attr(not(feature = "websockets"), allow(unused_variables))]
    async fn handle_tcp_connection<
        S: TcpService,
        C: AsyncRead + AsyncWrite + Unpin + Send + 'static,
    >(
        &self,
        connection: C,
        peer: Peer<S::ApplicationProtocols>,
        service: &S,
    ) -> Result<(), Error> {
        // For ACME, don't send any traffic over the connection.
        #[cfg(feature = "acme")]
        if peer.protocol.alpn_name() == async_acme::acme::ACME_TLS_ALPN_NAME {
            log::info!("received acme challenge connection");
            return Ok(());
        }

        if let Err(connection) = service.handle_connection(connection, &peer).await {
            #[cfg(feature = "websockets")]
            if let Err(err) = self
                .handle_raw_websocket_connection(connection, peer.address)
                .await
            {
                log::error!(
                    "[server] error on websocket for {}: {:?}",
                    peer.address,
                    err
                );
            }
        }

        Ok(())
    }
}

impl<B: Backend> ResolvesServerCert for CustomServer<B> {
    #[cfg_attr(not(feature = "acme"), allow(unused_variables))]
    fn resolve(
        &self,
        client_hello: rustls::server::ClientHello<'_>,
    ) -> Option<Arc<rustls::sign::CertifiedKey>> {
        #[cfg(feature = "acme")]
        if client_hello
            .alpn()
            .map(|mut iter| iter.any(|n| n == async_acme::acme::ACME_TLS_ALPN_NAME))
            .unwrap_or_default()
        {
            let server_name = client_hello.server_name()?.to_owned();
            let keys = self.data.alpn_keys.lock();
            if let Some(key) = keys.get(AsRef::<str>::as_ref(&server_name)) {
                log::info!("returning acme challenge");
                return Some(key.clone());
            }

            log::error!(
                "acme alpn challenge received with no key for {}",
                server_name
            );
            return None;
        }

        let cached_key = self.data.primary_tls_key.lock();
        if let Some(key) = cached_key.as_ref() {
            Some(key.clone())
        } else {
            log::error!("[server] inbound tls connection with no certificate installed");
            None
        }
    }
}

/// A service that can handle incoming TCP connections.
#[async_trait]
pub trait TcpService: Clone + Send + Sync + 'static {
    /// The application layer protocols that this service supports.
    type ApplicationProtocols: ApplicationProtocols;

    /// Returns all available protocols for this service. The first will be the
    /// default used if a connection is made without negotiating the application
    /// protocol.
    fn available_protocols(&self) -> &[Self::ApplicationProtocols];

    /// Handle an incoming `connection` for `peer`. Return `Err(connection)` to
    /// have BonsaiDb handle the connection internally.
    async fn handle_connection<
        S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
    >(
        &self,
        connection: S,
        peer: &Peer<Self::ApplicationProtocols>,
    ) -> Result<(), S>;
}

/// A service that can handle incoming HTTP connections. A convenience
/// implementation of [`TcpService`] that is useful is you are only serving HTTP
/// and WebSockets over a service.
#[async_trait]
pub trait HttpService: Clone + Send + Sync + 'static {
    /// Handle an incoming `connection` for `peer`. Return `Err(connection)` to
    /// have BonsaiDb handle the connection internally.
    async fn handle_connection<
        S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
    >(
        &self,
        connection: S,
        peer: &Peer,
    ) -> Result<(), S>;
}

#[async_trait]
impl<T> TcpService for T
where
    T: HttpService,
{
    type ApplicationProtocols = StandardTcpProtocols;

    fn available_protocols(&self) -> &[Self::ApplicationProtocols] {
        StandardTcpProtocols::all()
    }

    async fn handle_connection<
        S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
    >(
        &self,
        connection: S,
        peer: &Peer<Self::ApplicationProtocols>,
    ) -> Result<(), S> {
        HttpService::handle_connection(self, connection, peer).await
    }
}

#[async_trait]
impl HttpService for () {
    async fn handle_connection<
        S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
    >(
        &self,
        connection: S,
        _peer: &Peer<StandardTcpProtocols>,
    ) -> Result<(), S> {
        Err(connection)
    }
}

/// A collection of supported protocols for a network service.
pub trait ApplicationProtocols: Clone + std::fmt::Debug + Send + Sync {
    /// Returns the identifier to use in ALPN during TLS negotiation.
    fn alpn_name(&self) -> &'static [u8];
}

/// A connected network peer.
#[derive(Debug, Clone)]
pub struct Peer<P: ApplicationProtocols = StandardTcpProtocols> {
    /// The remote address of the peer.
    pub address: std::net::SocketAddr,
    /// If true, the connection is secured with TLS.
    pub secure: bool,
    /// The application protocol to use for this connection.
    pub protocol: P,
}

/// TCP [`ApplicationProtocols`] that BonsaiDb has some knowledge of.
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub enum StandardTcpProtocols {
    Http1,
    #[cfg(feature = "acme")]
    Acme,
    Other,
}

impl StandardTcpProtocols {
    #[cfg(feature = "acme")]
    const fn all() -> &'static [Self] {
        &[Self::Http1, Self::Acme]
    }

    #[cfg(not(feature = "acme"))]
    const fn all() -> &'static [Self] {
        &[Self::Http1]
    }
}

impl Default for StandardTcpProtocols {
    fn default() -> Self {
        Self::Http1
    }
}

impl ApplicationProtocols for StandardTcpProtocols {
    fn alpn_name(&self) -> &'static [u8] {
        match self {
            Self::Http1 => b"http/1.1",
            #[cfg(feature = "acme")]
            Self::Acme => async_acme::acme::ACME_TLS_ALPN_NAME,
            Self::Other => unreachable!(),
        }
    }
}