rust_web_server/entry_point/config_file/
mod.rs1use 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
10pub 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
36const PROXY_TABLES: &[&str] = &["route", "upstream", "tcp_proxy", "udp_proxy", "ws_proxy", "middleware"];
39
40const VIRTUAL_HOST_FIELDS: &[&str] = &["DOMAIN", "CERT_FILE", "KEY_FILE"];
42
43#[derive(Debug, Default, PartialEq)]
46pub struct ConfigSettings {
47 pub settings: Vec<(String, String)>,
49 pub unknown: Vec<String>,
51}
52
53pub fn collect_settings(
62 cursor: Cursor<&[u8]>,
63 prefix: String) -> Result<ConfigSettings, String> {
64
65 let mut table = prefix;
66 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
130pub 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 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
161fn 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
175fn 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
199fn 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
219pub 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}