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