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