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