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