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