Skip to main content

rust_web_server/entry_point/config_file/
mod.rs

1use std::collections::HashMap;
2use std::env;
3use std::io::{BufRead, Cursor};
4use crate::entry_point::command_line_args::CommandLineArgument;
5use file_ext::FileExt;
6
7#[cfg(test)]
8mod tests;
9
10/// Settings that have an `RWS_CONFIG_*` variable but no command-line flag.
11/// In `rws.config.toml` they're written like any other key — the variable
12/// name is the table path plus key, upper-cased: `[rate_limit] max_requests`
13/// → `RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS`. Settings that do have a flag are
14/// taken from `CommandLineArgument::get_command_line_arg_list()` instead.
15/// `tests.rs` checks this list against every `RWS_CONFIG_*` name in `src/`.
16pub const SETTINGS_WITHOUT_FLAG: &[&str] = &[
17    "RWS_CONFIG_ACME_ACCOUNT_KEY_PATH",
18    "RWS_CONFIG_ACME_RENEW_BEFORE_DAYS",
19    "RWS_CONFIG_ACME_RENEW_CHECK_INTERVAL_SECS",
20    "RWS_CONFIG_CIRCUIT_BREAKER_FAILURE_THRESHOLD",
21    "RWS_CONFIG_CIRCUIT_BREAKER_MAX_HALF_OPEN_PROBES",
22    "RWS_CONFIG_CIRCUIT_BREAKER_RECOVERY_SECS",
23    "RWS_CONFIG_CLIENT_HINTS",
24    "RWS_CONFIG_CSP",
25    "RWS_CONFIG_ACME_DNS_TSIG_SECRET",
26    "RWS_CONFIG_ACME_REDIS_PASSWORD",
27    "RWS_CONFIG_ACME_DNS_API_TOKEN",
28    "RWS_CONFIG_ACCESS_LOG",
29    "RWS_CONFIG_ACCESS_LOG_KEEP",
30    "RWS_CONFIG_ACCESS_LOG_MAX_SIZE",
31    "RWS_CONFIG_LOG_FORMAT",
32    "RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES",
33    "RWS_CONFIG_NANOS_HEADERS",
34    "RWS_CONFIG_OPEN_FILE_CACHE_SECS",
35    "RWS_CONFIG_OPEN_FILE_CACHE_STRICT",
36    "RWS_CONFIG_PROXY_PROTOCOL",
37    "RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS",
38    "RWS_CONFIG_RATE_LIMIT_WINDOW_SECS",
39    "RWS_CONFIG_RUNTIME",
40    "RWS_CONFIG_SECURITY_HEADERS",
41    "RWS_CONFIG_SERVE_DOTFILES",
42    "RWS_CONFIG_SPA_FALLBACK",
43    "RWS_CONFIG_SPA_FALLBACK_EXCLUDE_PREFIXES",
44    "RWS_CONFIG_STATIC_CACHE_CONTROL",
45    "RWS_CONFIG_TEMPLATE_DIR",
46    "RWS_CONFIG_TLS_CLIENT_CA_FILE",
47    "RWS_CONFIG_WATCH",
48];
49
50/// Tables (and their sub-tables) read by `proxy_config`'s own parser, not
51/// mapped to `RWS_CONFIG_*` variables.
52const PROXY_TABLES: &[&str] = &["route", "upstream", "tcp_proxy", "udp_proxy", "ws_proxy", "middleware"];
53
54/// `[[virtual_host]]` fields, set as `RWS_CONFIG_VIRTUAL_HOST_<n>_<FIELD>`.
55const VIRTUAL_HOST_FIELDS: &[&str] = &["DOMAIN", "CERT_FILE", "KEY_FILE"];
56
57/// The settings of a `rws.config.toml` document, resolved to the
58/// `RWS_CONFIG_*` variables they set — without touching the environment.
59#[derive(Debug, Default, PartialEq)]
60pub struct ConfigSettings {
61    /// `(RWS_CONFIG_* name, value)` in file order.
62    pub settings: Vec<(String, String)>,
63    /// Keys no setting answers to, as `key` or `[table] key`.
64    pub unknown: Vec<String>,
65}
66
67/// Resolve every setting in a `rws.config.toml` document. `prefix` is the
68/// table the document starts in (normally empty).
69///
70/// Top-level keys and keys in plain `[tables]` map to `RWS_CONFIG_<TABLE>_<KEY>`
71/// (`[cors] allow_all` → `RWS_CONFIG_CORS_ALLOW_ALL`); each `[[virtual_host]]`
72/// block maps to `RWS_CONFIG_VIRTUAL_HOST_<n>_*`. Strings keep their exact
73/// contents (spaces, quotes inside them); arrays become comma-separated lists.
74/// Proxy tables (`[[route]]`, `[[upstream]]`, …) are left to `proxy_config`.
75pub fn collect_settings(
76    cursor: Cursor<&[u8]>,
77    prefix: String) -> Result<ConfigSettings, String> {
78
79    let mut table = prefix;
80    // Index of the current [[array-table]] entry, per array-table name.
81    let mut array_table_counters: HashMap<String, usize> = HashMap::new();
82    let mut array_index: Option<usize> = None;
83    let mut resolved = ConfigSettings::default();
84    let flags = CommandLineArgument::get_command_line_arg_list();
85
86    for line in cursor.lines() {
87        let line = line.map_err(|e| e.to_string())?;
88        let line = strip_comment(&line).trim().to_string();
89        if line.is_empty() {
90            continue;
91        }
92
93        if let Some(name) = line.strip_prefix("[[").and_then(|l| l.strip_suffix("]]")) {
94            let name = name.trim().to_string();
95            let count = array_table_counters.entry(name.clone()).or_insert(0);
96            array_index = Some(*count);
97            *count += 1;
98            table = name;
99            continue;
100        }
101        if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
102            table = name.trim().to_string();
103            array_index = None;
104            continue;
105        }
106
107        let Some((raw_key, raw_value)) = line.split_once('=') else { continue };
108        let key = raw_key.trim();
109
110        let root = table.split('.').next().unwrap_or("");
111        if PROXY_TABLES.contains(&root) {
112            continue;
113        }
114
115        // An inline table, `rate_limit = { max_requests = 5 }`, is the
116        // sub-table `[rate_limit]` (or `[<table>.rate_limit]`), as in TOML
117        // and as in the proxy sections.
118        if let Some(inner) = raw_value.trim().strip_prefix('{').and_then(|v| v.strip_suffix('}')) {
119            let sub_table = if table.is_empty() { key.to_string() } else { format!("{}.{}", table, key) };
120            for entry in split_top_level(inner) {
121                if let Some((inner_key, inner_value)) = entry.split_once('=') {
122                    resolve_setting(&sub_table, array_index, inner_key.trim(), parse_value(inner_value), &flags, &mut resolved);
123                } else if !entry.trim().is_empty() {
124                    resolved.unknown.push(qualified_key(&sub_table, entry.trim()));
125                }
126            }
127            continue;
128        }
129
130        resolve_setting(&table, array_index, key, parse_value(raw_value), &flags, &mut resolved);
131    }
132
133    Ok(resolved)
134}
135
136/// Map one `key = value` in `table` to its `RWS_CONFIG_*` setting, or record
137/// it as unknown.
138fn resolve_setting(
139    table: &str,
140    array_index: Option<usize>,
141    key: &str,
142    value: String,
143    flags: &[CommandLineArgument],
144    resolved: &mut ConfigSettings,
145) {
146    if table == "virtual_host" {
147        let field = key.to_ascii_uppercase();
148        if VIRTUAL_HOST_FIELDS.contains(&field.as_str()) {
149            let name = format!("RWS_CONFIG_VIRTUAL_HOST_{}_{}", array_index.unwrap_or(0), field);
150            resolved.settings.push((name, value));
151        } else {
152            resolved.unknown.push(qualified_key(table, key));
153        }
154        return;
155    }
156
157    let path = if table.is_empty() { key.to_string() } else { format!("{}_{}", table.replace('.', "_"), key) };
158    let long_form = path.replace('_', "-");
159    if let Some(flag) = flags.iter().find(|f| f.long_form == long_form) {
160        resolved.settings.push((flag.environment_variable.clone(), value));
161        return;
162    }
163    let name = format!("RWS_CONFIG_{}", path.to_ascii_uppercase());
164    if SETTINGS_WITHOUT_FLAG.contains(&name.as_str()) {
165        resolved.settings.push((name, value));
166    } else {
167        resolved.unknown.push(qualified_key(table, key));
168    }
169}
170
171/// Split an inline table's body on commas outside quotes and `[...]`.
172fn split_top_level(inner: &str) -> Vec<&str> {
173    let mut items = vec![];
174    let mut quote: Option<char> = None;
175    let mut depth = 0usize;
176    let mut start = 0;
177    for (i, c) in inner.char_indices() {
178        match (quote, c) {
179            (None, '"') | (None, '\'') => quote = Some(c),
180            (Some(q), c) if c == q => quote = None,
181            (None, '[') => depth += 1,
182            (None, ']') => depth = depth.saturating_sub(1),
183            (None, ',') if depth == 0 => {
184                items.push(&inner[start..i]);
185                start = i + 1;
186            }
187            _ => {}
188        }
189    }
190    items.push(&inner[start..]);
191    items
192}
193
194/// Apply every setting in a `rws.config.toml` document to the process
195/// environment (see [`collect_settings`]). Unknown keys are reported on
196/// stderr instead of being ignored silently.
197pub fn read_config_file(
198    cursor: Cursor<&[u8]>,
199    prefix: String) -> Result<bool, String> {
200    let resolved = collect_settings(cursor, prefix)?;
201    for (name, value) in &resolved.settings {
202        set_setting(name, value);
203    }
204    for key in &resolved.unknown {
205        eprintln!("    Warning: unknown setting '{}' in rws.config.toml — ignored", key);
206    }
207    Ok(true)
208}
209
210fn set_setting(name: &str, value: &str) {
211    if value.contains('\0') {
212        // env::set_var panics on NUL — a stray byte in the file must not crash startup.
213        eprintln!("    Warning: value for {} contains a NUL byte — ignored", name);
214        return;
215    }
216    env::set_var(name, value);
217    crate::server_config::invalidate();
218    println!("    Set env variable '{}' to value '{}'", name, crate::entry_point::shown(name, value));
219}
220
221fn qualified_key(table: &str, key: &str) -> String {
222    if table.is_empty() { key.to_string() } else { format!("[{}] {}", table, key) }
223}
224
225/// Drop a trailing `# comment`, ignoring `#` inside quoted strings.
226fn strip_comment(line: &str) -> &str {
227    let mut quote: Option<char> = None;
228    for (i, c) in line.char_indices() {
229        match (quote, c) {
230            (None, '"') | (None, '\'') => quote = Some(c),
231            (Some(q), c) if c == q => quote = None,
232            (None, '#') => return &line[..i],
233            _ => {}
234        }
235    }
236    line
237}
238
239/// A TOML value as a plain string: quoted strings lose only their quotes,
240/// arrays become `a,b,c`, anything else (numbers, booleans) is trimmed.
241fn parse_value(raw: &str) -> String {
242    let raw = raw.trim();
243    if let Some(inner) = raw.strip_prefix('[').and_then(|r| r.strip_suffix(']')) {
244        return split_array(inner)
245            .iter()
246            .map(|item| unquote(item.trim()))
247            .filter(|item| !item.is_empty())
248            .collect::<Vec<_>>()
249            .join(",");
250    }
251    unquote(raw)
252}
253
254fn unquote(s: &str) -> String {
255    for q in ['"', '\''] {
256        if s.len() >= 2 && s.starts_with(q) && s.ends_with(q) {
257            return s[1..s.len() - 1].to_string();
258        }
259    }
260    s.to_string()
261}
262
263/// Split array items on commas outside quotes.
264fn split_array(inner: &str) -> Vec<&str> {
265    let mut items = vec![];
266    let mut quote: Option<char> = None;
267    let mut start = 0;
268    for (i, c) in inner.char_indices() {
269        match (quote, c) {
270            (None, '"') | (None, '\'') => quote = Some(c),
271            (Some(q), c) if c == q => quote = None,
272            (None, ',') => {
273                items.push(&inner[start..i]);
274                start = i + 1;
275            }
276            _ => {}
277        }
278    }
279    items.push(&inner[start..]);
280    items
281}
282
283/// Load `rws.config.toml` into the environment: `filepath` (relative to the
284/// working directory) when given, else the file named by `RWS_CONFIG_FILE`
285/// (absolute, or relative to the working directory) — the same variable
286/// `proxy_config` reads routes from — else `rws.config.toml` in the working
287/// directory.
288pub fn override_environment_variables_from_config(filepath: Option<&str>) {
289    println!("\n  Start of Config Section");
290
291    let from_env = env::var("RWS_CONFIG_FILE").ok().filter(|p| !p.trim().is_empty());
292    let resolved = match (filepath, from_env) {
293        (Some(path), _) => FileExt::get_static_filepath(path),
294        (None, Some(path)) => Ok(path),
295        (None, None) => FileExt::get_static_filepath("/rws.config.toml"),
296    };
297    let path = match resolved {
298        Ok(path) => path,
299        Err(e) => {
300            eprintln!("{}", e);
301            println!("  End of Config Section");
302            return;
303        }
304    };
305
306    match std::fs::read_to_string(&path) {
307        Ok(content) => {
308            if let Err(e) = read_config_file(Cursor::new(content.as_bytes()), String::new()) {
309                eprintln!("    Unable to parse {}: {}", path, e);
310            }
311        }
312        Err(e) => eprintln!("    Unable to read {}: {}", path, e),
313    }
314
315    println!("  End of Config Section");
316}