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