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