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