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
use crate::core::{Memcached, MtopError};
use std::collections::HashMap;
use std::fmt;
use std::fs::File;
use std::io::BufReader as StdBufReader;
use std::ops::{Deref, DerefMut};
use std::path::PathBuf;
use std::sync::Arc;
use tokio::net::{TcpStream, ToSocketAddrs};
use tokio::runtime::Handle;
use tokio::sync::Mutex;
use tokio_rustls::rustls::{Certificate, ClientConfig, OwnedTrustAnchor, PrivateKey, RootCertStore, ServerName};
use tokio_rustls::TlsConnector;
use webpki::TrustAnchor;

#[derive(Debug)]
pub struct PooledMemcached {
    inner: Memcached,
    host: String,
}

impl Deref for PooledMemcached {
    type Target = Memcached;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for PooledMemcached {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

#[derive(Debug)]
pub struct PoolConfig {
    pub check_on_get: bool,
    pub check_on_put: bool,
    pub tls: TLSConfig,
}

impl Default for PoolConfig {
    fn default() -> Self {
        Self {
            check_on_get: true,
            check_on_put: true,
            tls: TLSConfig::default(),
        }
    }
}

#[derive(Debug, Default)]
pub struct TLSConfig {
    pub enabled: bool,
    pub ca_path: Option<PathBuf>,
    pub cert_path: Option<PathBuf>,
    pub key_path: Option<PathBuf>,
    pub server_name: Option<String>,
}

#[derive(Debug)]
pub struct MemcachedPool {
    clients: Mutex<HashMap<String, Memcached>>,
    client_config: Option<Arc<ClientConfig>>,
    server: Option<ServerName>,
    config: PoolConfig,
}

impl MemcachedPool {
    pub async fn new(handle: Handle, config: PoolConfig) -> Result<Self, MtopError> {
        let server = if let Some(s) = &config.tls.server_name {
            Some(Self::host_to_server_name(s)?)
        } else {
            None
        };

        let client_config = if config.tls.enabled {
            Some(Arc::new(Self::client_config(handle, &config.tls).await?))
        } else {
            None
        };

        Ok(MemcachedPool {
            clients: Mutex::new(HashMap::new()),
            client_config,
            server,
            config,
        })
    }

    async fn client_config(handle: Handle, tls: &TLSConfig) -> Result<ClientConfig, MtopError> {
        let ca = if let Some(p) = &tls.ca_path {
            let certs = Self::load_cert(&handle, p).await?;
            tracing::debug!(message = "loaded CA certs", num_certs = certs.len(), path = ?p);
            Some(certs)
        } else {
            None
        };

        let client_cert = if let Some(p) = &tls.cert_path {
            let certs = Self::load_cert(&handle, p).await?;
            tracing::debug!(message = "loaded client certs", num_certs = certs.len(), path = ?p);
            Some(certs)
        } else {
            None
        };

        let client_key = if let Some(p) = &tls.key_path {
            let keys = Self::load_key(&handle, p).await?;
            tracing::debug!(message = "loaded client key", path = ?p);
            Some(keys)
        } else {
            None
        };

        let trust_store = Self::trust_store(ca)?;
        let builder = ClientConfig::builder()
            .with_safe_defaults()
            .with_root_certificates(trust_store);

        let config = match (client_cert, client_key) {
            (Some(cert), Some(key)) => {
                tracing::debug!(message = "using key and cert for client authentication");
                builder
                    .with_client_auth_cert(cert, key)
                    .map_err(|e| MtopError::configuration_cause("unable to use client cert or key", e))?
            }
            _ => {
                tracing::debug!(message = "not using any client authentication");
                builder.with_no_client_auth()
            }
        };

        Ok(config)
    }

    async fn load_cert(handle: &Handle, path: &PathBuf) -> Result<Vec<Certificate>, MtopError> {
        let mut reader = File::open(path.clone())
            .map(StdBufReader::new)
            .map_err(|e| MtopError::configuration_cause(format!("unable to load cert {:?}", path), e))?;

        Ok(handle
            .spawn_blocking(move || rustls_pemfile::certs(&mut reader))
            .await
            .unwrap()
            .map_err(|e| MtopError::configuration_cause(format!("unable to parse cert {:?}", path), e))? // unwrap the spawn result, try the read result
            .into_iter()
            .map(Certificate)
            .collect())
    }

    async fn load_key(handle: &Handle, path: &PathBuf) -> Result<PrivateKey, MtopError> {
        let mut reader = File::open(path.clone())
            .map(StdBufReader::new)
            .map_err(|e| MtopError::configuration_cause(format!("unable to load key {:?}", path), e))?;

        handle
            .spawn_blocking(move || rustls_pemfile::pkcs8_private_keys(&mut reader))
            .await
            .unwrap()
            .map_err(|e| MtopError::configuration_cause(format!("unable to parse key {:?}", path), e))? // unwrap the spawn result, try the read result
            .into_iter()
            .next()
            .map(PrivateKey)
            .ok_or_else(|| MtopError::configuration(format!("no keys available in {:?}", path)))
    }

    fn trust_store(ca: Option<Vec<Certificate>>) -> Result<RootCertStore, MtopError> {
        let mut root_cert_store = RootCertStore::empty();

        if let Some(ca_certs) = ca {
            let mut anchors = Vec::with_capacity(ca_certs.len());
            for cert in ca_certs {
                let anchor = TrustAnchor::try_from_cert_der(&cert.0)
                    .map(|ta| {
                        OwnedTrustAnchor::from_subject_spki_name_constraints(ta.subject, ta.spki, ta.name_constraints)
                    })
                    .map_err(|e| MtopError::internal_cause("unable to parse CA cert", e))?;
                anchors.push(anchor);
            }

            tracing::debug!(message = "adding custom CA certs for roots", num_certs = anchors.len());
            root_cert_store.add_trust_anchors(anchors.into_iter());
        } else {
            tracing::debug!(message = "using default CA certs for roots");
            root_cert_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| {
                OwnedTrustAnchor::from_subject_spki_name_constraints(ta.subject, ta.spki, ta.name_constraints)
            }));
        }

        Ok(root_cert_store)
    }

    async fn connect(&self, host: &str) -> Result<Memcached, MtopError> {
        if let Some(cfg) = &self.client_config {
            let server = match &self.server {
                Some(v) => v.clone(),
                None => host
                    .split_once(':')
                    .ok_or_else(|| MtopError::configuration(format!("invalid server name '{}'", host)))
                    .and_then(|(hostname, _)| Self::host_to_server_name(hostname))?,
            };

            tracing::debug!(message = "using server name for TLS validation", server_name = ?server);
            tls_connect(host, server, cfg.clone()).await
        } else {
            plain_connect(host).await
        }
    }

    fn host_to_server_name(host: &str) -> Result<ServerName, MtopError> {
        ServerName::try_from(host)
            .map_err(|e| MtopError::configuration_cause(format!("invalid server name '{}'", host), e))
    }

    pub async fn get(&self, host: &str) -> Result<PooledMemcached, MtopError> {
        let mut map = self.clients.lock().await;
        let mut inner = match map.remove(host) {
            Some(c) => c,
            None => self.connect(host).await?,
        };

        if self.config.check_on_get {
            inner.ping().await?;
        }

        Ok(PooledMemcached {
            inner,
            host: host.to_owned(),
        })
    }

    pub async fn put(&self, mut client: PooledMemcached) {
        if !self.config.check_on_put || client.ping().await.is_ok() {
            let mut map = self.clients.lock().await;
            map.insert(client.host, client.inner);
        }
    }
}

async fn plain_connect<A>(host: A) -> Result<Memcached, MtopError>
where
    A: ToSocketAddrs + fmt::Display,
{
    let tcp_stream = tcp_stream(host).await?;
    let (read, write) = tcp_stream.into_split();
    Ok(Memcached::new(read, write))
}

async fn tls_connect<A>(host: A, server: ServerName, config: Arc<ClientConfig>) -> Result<Memcached, MtopError>
where
    A: ToSocketAddrs + fmt::Display,
{
    let tcp_stream = tcp_stream(host).await?;
    let connector = TlsConnector::from(config);
    let tls_stream = connector.connect(server, tcp_stream).await?;
    let (read, write) = tokio::io::split(tls_stream);
    Ok(Memcached::new(read, write))
}

async fn tcp_stream<A>(host: A) -> Result<TcpStream, MtopError>
where
    A: ToSocketAddrs + fmt::Display,
{
    TcpStream::connect(&host)
        .await
        // The client buffers and flushes writes so we don't need delay here to
        // avoid lots of tiny packets.
        .and_then(|s| s.set_nodelay(true).map(|_| s))
        .map_err(|e| MtopError::from((host.to_string(), e)))
}