httpsd 0.1.1

A pure-Rust HTTP/HTTPS server — usable as a sans-I/O library with pluggable runtimes (thread pool, tokio, mio) or as a CLI that serves a directory or a TOML config.
Documentation
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! TOML configuration loading.
//!
//! A [`ServerConfig`] mirrors the TOML file the CLI accepts. It can also be
//! turned directly into a runnable [`Server`](crate::rt::Server) when a runtime
//! feature is enabled.
//!
//! ```toml
//! listen = "0.0.0.0:8080"      # or ["127.0.0.1:8080", "[::1]:8080"]
//! root = "/var/www"            # document root for static file serving
//! server_name = "httpsd"
//! workers = 8
//!
//! [tls]
//! cert = "cert.pem"            # PEM chain (leaf first)
//! key = "key.pem"              # PEM private key
//! # self_signed = ["localhost"]  # alternatively, generate an ephemeral cert
//!
//! [compress]
//! enabled = true
//! min_size = 256
//! ```

use std::path::PathBuf;

use serde::Deserialize;

use crate::error::{Error, Result};

/// Either a single value or a list of them (used for `listen`).
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
enum OneOrMany {
    One(String),
    Many(Vec<String>),
}

impl OneOrMany {
    fn into_vec(self) -> Vec<String> {
        match self {
            OneOrMany::One(s) => vec![s],
            OneOrMany::Many(v) => v,
        }
    }
}

/// TLS settings.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TlsConfig {
    /// Path to the PEM certificate chain (leaf first).
    pub cert: Option<String>,
    /// Path to the PEM private key.
    pub key: Option<String>,
    /// Generate an ephemeral self-signed certificate for these host names
    /// instead of loading `cert`/`key`.
    pub self_signed: Option<Vec<String>>,
}

/// Compression settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CompressConfig {
    /// Master switch (default `true`).
    #[serde(default = "yes")]
    pub enabled: bool,
    /// Minimum body size to compress (default `256`).
    #[serde(default = "default_min_size")]
    pub min_size: usize,
}

fn yes() -> bool {
    true
}
fn default_min_size() -> usize {
    256
}

impl Default for CompressConfig {
    fn default() -> CompressConfig {
        CompressConfig {
            enabled: true,
            min_size: default_min_size(),
        }
    }
}

/// Automatic-certificate (ACME) settings.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AcmeFileConfig {
    /// Must be `true` to enable automatic issuance (accepts the CA's ToS).
    #[serde(default)]
    pub accept_tos: bool,
    /// Account contact email (optional).
    pub email: Option<String>,
    /// ACME directory URL (defaults to Let's Encrypt production).
    pub directory: Option<String>,
    /// Use the Let's Encrypt staging environment.
    #[serde(default)]
    pub staging: bool,
    /// Only issue for these host names, if set.
    pub host_whitelist: Option<Vec<String>>,
    /// Override the certificate storage directory.
    pub cert_dir: Option<PathBuf>,
}

/// Privilege-dropping settings (drop root after binding; Unix only).
#[cfg(feature = "privdrop")]
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PrivDropConfig {
    /// User to switch to: `NAME` or `UID` (a group may be appended as
    /// `NAME:GROUP`, or supplied separately via `group`).
    pub user: Option<String>,
    /// Group to switch to: `NAME` or `GID`. Overrides the user's primary group.
    pub group: Option<String>,
    /// Directory to `chroot` into before dropping.
    pub chroot: Option<PathBuf>,
}

/// `Strict-Transport-Security` settings.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HstsConfig {
    /// `max-age` in seconds (default one year).
    #[serde(default = "default_hsts_max_age")]
    pub max_age: u64,
    /// Append `; includeSubDomains`.
    #[serde(default)]
    pub include_subdomains: bool,
    /// Append `; preload`.
    #[serde(default)]
    pub preload: bool,
}

fn default_hsts_max_age() -> u64 {
    31_536_000
}

impl HstsConfig {
    /// Render the header value, e.g. `max-age=31536000; includeSubDomains`.
    pub fn header_value(&self) -> String {
        let mut v = format!("max-age={}", self.max_age);
        if self.include_subdomains {
            v.push_str("; includeSubDomains");
        }
        if self.preload {
            v.push_str("; preload");
        }
        v
    }
}

/// The parsed server configuration.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServerConfig {
    /// Listen address(es).
    listen: OneOrMany,
    /// Document root for static file serving.
    pub root: Option<PathBuf>,
    /// `Server` header value.
    pub server_name: Option<String>,
    /// Omit the `Server` response header entirely. Wins over `server_name`.
    #[serde(default)]
    pub no_server_header: bool,
    /// Worker thread count (thread-pool runtime).
    pub workers: Option<usize>,
    /// TLS settings.
    pub tls: Option<TlsConfig>,
    /// Compression settings.
    pub compress: Option<CompressConfig>,
    /// Serve content over plain HTTP instead of redirecting to HTTPS.
    #[serde(default)]
    pub allow_http: bool,
    /// Plain-HTTP listener address(es) for redirects + ACME HTTP-01.
    http_listen: Option<OneOrMany>,
    /// Automatic certificate management.
    pub acme: Option<AcmeFileConfig>,
    /// `Strict-Transport-Security` settings (sent on secure responses).
    pub hsts: Option<HstsConfig>,
    /// Privilege-dropping settings (drop root after binding; Unix only).
    #[cfg(feature = "privdrop")]
    pub privdrop: Option<PrivDropConfig>,
}

impl ServerConfig {
    /// Parse a configuration from a TOML string.
    pub fn from_toml_str(s: &str) -> Result<ServerConfig> {
        toml::from_str(s).map_err(|e| Error::Config(e.to_string()))
    }

    /// Read and parse a configuration file.
    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<ServerConfig> {
        let text = std::fs::read_to_string(path.as_ref())
            .map_err(|e| Error::Config(format!("reading {}: {e}", path.as_ref().display())))?;
        ServerConfig::from_toml_str(&text)
    }

    /// The configured listen addresses, as strings.
    pub fn listen_addrs(&self) -> Vec<String> {
        self.listen.clone().into_vec()
    }

    /// Resolve the `[privdrop]` table into a runnable
    /// [`PrivDrop`](crate::privdrop::PrivDrop), if configured.
    ///
    /// Because dropping privileges is process-wide and must happen only after
    /// every listener (TCP, HTTP redirect, and HTTP/3 UDP) is bound, the actual
    /// drop is performed by the caller (the CLI) — not by
    /// [`into_server`](ServerConfig::into_server). This exposes the parsed
    /// actions so the binary can apply them once, under the bind-readiness
    /// handshake.
    #[cfg(feature = "privdrop")]
    pub fn priv_drop(&self) -> Result<Option<crate::privdrop::PrivDrop>> {
        let Some(pd) = &self.privdrop else {
            return Ok(None);
        };
        if pd.user.is_none() && pd.group.is_none() && pd.chroot.is_none() {
            return Ok(None);
        }
        let user_spec = match (&pd.user, &pd.group) {
            (Some(u), Some(g)) => Some(format!("{u}:{g}")),
            (Some(u), None) => Some(u.clone()),
            (None, Some(_)) => {
                return Err(Error::Config("[privdrop] `group` requires `user`".into()));
            }
            (None, None) => None,
        };
        let chroot = match &pd.chroot {
            Some(p) => Some(p.to_str().ok_or_else(|| {
                Error::Config("[privdrop] chroot path is not valid UTF-8".into())
            })?),
            None => None,
        };
        Ok(Some(crate::privdrop::PrivDrop::parse(
            user_spec.as_deref(),
            chroot,
        )?))
    }

    /// Build a runnable [`Server`](crate::rt::Server) from this configuration.
    #[cfg(any(feature = "rt-threadpool", feature = "rt-tokio", feature = "rt-mio"))]
    pub fn into_server(self) -> Result<crate::rt::Server> {
        let addrs = self.listen_addrs();
        let first = addrs
            .first()
            .ok_or_else(|| Error::Config("no listen address".into()))?;
        let mut server = crate::rt::Server::bind(first.as_str())?;

        if let Some(root) = &self.root {
            server = server.serve_dir(root.clone());
        }
        if let Some(workers) = self.workers {
            server = server.workers(workers);
        }
        if self.no_server_header {
            server = server.server_name(None);
        } else if self.server_name.is_some() {
            server = server.server_name(self.server_name.clone());
        }

        if let Some(hsts) = &self.hsts {
            server = server.hsts(Some(hsts.header_value()));
        }
        if self.allow_http {
            server = server.allow_http(true);
        }
        if let Some(http) = &self.http_listen {
            use std::net::ToSocketAddrs;
            let mut resolved = Vec::new();
            for a in http.clone().into_vec() {
                resolved.extend(a.to_socket_addrs()?);
            }
            server = server.http_redirect(resolved.as_slice())?;
        }

        server = self.apply_tls(server)?;
        server = self.apply_compress(server);
        server = self.apply_acme(server)?;

        Ok(server)
    }

    #[cfg(all(
        feature = "acme",
        any(feature = "rt-threadpool", feature = "rt-tokio", feature = "rt-mio")
    ))]
    fn apply_acme(&self, server: crate::rt::Server) -> Result<crate::rt::Server> {
        let Some(acme) = &self.acme else {
            return Ok(server);
        };
        let directory = if acme.staging {
            crate::acme::client::LETSENCRYPT_STAGING.to_owned()
        } else {
            acme.directory
                .clone()
                .unwrap_or_else(|| crate::acme::client::LETSENCRYPT_PRODUCTION.to_owned())
        };
        let whitelist = acme.host_whitelist.as_ref().map(|hosts| {
            hosts
                .iter()
                .map(|h| h.trim().trim_end_matches('.').to_ascii_lowercase())
                .collect()
        });
        let cfg = crate::acme::AcmeConfig {
            directory_url: directory,
            accept_tos: acme.accept_tos,
            email: acme.email.clone(),
            host_whitelist: whitelist,
            cert_dir: acme.cert_dir.clone(),
        };
        Ok(server.acme(crate::acme::AcmeManager::new(cfg)?))
    }

    #[cfg(all(
        not(feature = "acme"),
        any(feature = "rt-threadpool", feature = "rt-tokio", feature = "rt-mio")
    ))]
    fn apply_acme(&self, server: crate::rt::Server) -> Result<crate::rt::Server> {
        if self.acme.is_some() {
            return Err(Error::Config(
                "[acme] configured but the `acme` feature is not enabled".into(),
            ));
        }
        Ok(server)
    }

    #[cfg(all(
        feature = "tls",
        any(feature = "rt-threadpool", feature = "rt-tokio", feature = "rt-mio")
    ))]
    fn apply_tls(&self, server: crate::rt::Server) -> Result<crate::rt::Server> {
        let Some(tls) = &self.tls else {
            return Ok(server);
        };
        let acceptor = match (&tls.cert, &tls.key, &tls.self_signed) {
            (Some(cert), Some(key), _) => crate::tls::TlsAcceptor::from_pem_files(cert, key)?,
            (_, _, Some(names)) => {
                let refs: Vec<&str> = names.iter().map(String::as_str).collect();
                crate::tls::TlsAcceptor::self_signed(&refs)?
            }
            _ => {
                return Err(Error::Config(
                    "[tls] requires either cert+key or self_signed".into(),
                ));
            }
        };
        Ok(server.tls(acceptor))
    }

    #[cfg(all(
        not(feature = "tls"),
        any(feature = "rt-threadpool", feature = "rt-tokio", feature = "rt-mio")
    ))]
    fn apply_tls(&self, server: crate::rt::Server) -> Result<crate::rt::Server> {
        if self.tls.is_some() {
            return Err(Error::Config(
                "[tls] configured but the `tls` feature is not enabled".into(),
            ));
        }
        Ok(server)
    }

    #[cfg(all(
        feature = "compress",
        any(feature = "rt-threadpool", feature = "rt-tokio", feature = "rt-mio")
    ))]
    fn apply_compress(&self, server: crate::rt::Server) -> crate::rt::Server {
        let c = self.compress.clone().unwrap_or_default();
        server.compression(crate::compress::Options {
            enabled: c.enabled,
            min_size: c.min_size,
        })
    }

    #[cfg(all(
        not(feature = "compress"),
        any(feature = "rt-threadpool", feature = "rt-tokio", feature = "rt-mio")
    ))]
    fn apply_compress(&self, server: crate::rt::Server) -> crate::rt::Server {
        server
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_minimal() {
        let cfg =
            ServerConfig::from_toml_str("listen = \"127.0.0.1:8080\"\nroot = \"/srv\"\n").unwrap();
        assert_eq!(cfg.listen_addrs(), vec!["127.0.0.1:8080"]);
        assert_eq!(cfg.root, Some(PathBuf::from("/srv")));
    }

    #[test]
    fn parses_full() {
        let toml = r#"
            listen = ["127.0.0.1:8443", "[::1]:8443"]
            root = "/var/www"
            workers = 16

            [tls]
            self_signed = ["localhost"]

            [compress]
            enabled = false
            min_size = 1024
        "#;
        let cfg = ServerConfig::from_toml_str(toml).unwrap();
        assert_eq!(cfg.listen_addrs().len(), 2);
        assert_eq!(cfg.workers, Some(16));
        assert!(cfg.tls.is_some());
        assert!(!cfg.compress.as_ref().unwrap().enabled);
    }
}