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