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