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