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