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