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_CLIENT_HINTS",
24 "RWS_CONFIG_CSP",
25 "RWS_CONFIG_LOG_FORMAT",
26 "RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES",
27 "RWS_CONFIG_NANOS_HEADERS",
28 "RWS_CONFIG_OPEN_FILE_CACHE_SECS",
29 "RWS_CONFIG_OPEN_FILE_CACHE_STRICT",
30 "RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS",
31 "RWS_CONFIG_RATE_LIMIT_WINDOW_SECS",
32 "RWS_CONFIG_RUNTIME",
33 "RWS_CONFIG_SECURITY_HEADERS",
34 "RWS_CONFIG_SERVE_DOTFILES",
35 "RWS_CONFIG_SPA_FALLBACK",
36 "RWS_CONFIG_SPA_FALLBACK_EXCLUDE_PREFIXES",
37 "RWS_CONFIG_STATIC_CACHE_CONTROL",
38 "RWS_CONFIG_TEMPLATE_DIR",
39 "RWS_CONFIG_TLS_CLIENT_CA_FILE",
40];
41
42const PROXY_TABLES: &[&str] = &["route", "upstream", "tcp_proxy", "udp_proxy", "ws_proxy", "middleware"];
45
46const VIRTUAL_HOST_FIELDS: &[&str] = &["DOMAIN", "CERT_FILE", "KEY_FILE"];
48
49#[derive(Debug, Default, PartialEq)]
52pub struct ConfigSettings {
53 pub settings: Vec<(String, String)>,
55 pub unknown: Vec<String>,
57}
58
59pub fn collect_settings(
68 cursor: Cursor<&[u8]>,
69 prefix: String) -> Result<ConfigSettings, String> {
70
71 let mut table = prefix;
72 let mut array_table_counters: HashMap<String, usize> = HashMap::new();
74 let mut array_index: Option<usize> = None;
75 let mut resolved = ConfigSettings::default();
76 let flags = CommandLineArgument::get_command_line_arg_list();
77
78 for line in cursor.lines() {
79 let line = line.map_err(|e| e.to_string())?;
80 let line = strip_comment(&line).trim().to_string();
81 if line.is_empty() {
82 continue;
83 }
84
85 if let Some(name) = line.strip_prefix("[[").and_then(|l| l.strip_suffix("]]")) {
86 let name = name.trim().to_string();
87 let count = array_table_counters.entry(name.clone()).or_insert(0);
88 array_index = Some(*count);
89 *count += 1;
90 table = name;
91 continue;
92 }
93 if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
94 table = name.trim().to_string();
95 array_index = None;
96 continue;
97 }
98
99 let Some((raw_key, raw_value)) = line.split_once('=') else { continue };
100 let key = raw_key.trim();
101
102 let root = table.split('.').next().unwrap_or("");
103 if PROXY_TABLES.contains(&root) {
104 continue;
105 }
106
107 if let Some(inner) = raw_value.trim().strip_prefix('{').and_then(|v| v.strip_suffix('}')) {
111 let sub_table = if table.is_empty() { key.to_string() } else { format!("{}.{}", table, key) };
112 for entry in split_top_level(inner) {
113 if let Some((inner_key, inner_value)) = entry.split_once('=') {
114 resolve_setting(&sub_table, array_index, inner_key.trim(), parse_value(inner_value), &flags, &mut resolved);
115 } else if !entry.trim().is_empty() {
116 resolved.unknown.push(qualified_key(&sub_table, entry.trim()));
117 }
118 }
119 continue;
120 }
121
122 resolve_setting(&table, array_index, key, parse_value(raw_value), &flags, &mut resolved);
123 }
124
125 Ok(resolved)
126}
127
128fn resolve_setting(
131 table: &str,
132 array_index: Option<usize>,
133 key: &str,
134 value: String,
135 flags: &[CommandLineArgument],
136 resolved: &mut ConfigSettings,
137) {
138 if table == "virtual_host" {
139 let field = key.to_ascii_uppercase();
140 if VIRTUAL_HOST_FIELDS.contains(&field.as_str()) {
141 let name = format!("RWS_CONFIG_VIRTUAL_HOST_{}_{}", array_index.unwrap_or(0), field);
142 resolved.settings.push((name, value));
143 } else {
144 resolved.unknown.push(qualified_key(table, key));
145 }
146 return;
147 }
148
149 let path = if table.is_empty() { key.to_string() } else { format!("{}_{}", table.replace('.', "_"), key) };
150 let long_form = path.replace('_', "-");
151 if let Some(flag) = flags.iter().find(|f| f.long_form == long_form) {
152 resolved.settings.push((flag.environment_variable.clone(), value));
153 return;
154 }
155 let name = format!("RWS_CONFIG_{}", path.to_ascii_uppercase());
156 if SETTINGS_WITHOUT_FLAG.contains(&name.as_str()) {
157 resolved.settings.push((name, value));
158 } else {
159 resolved.unknown.push(qualified_key(table, key));
160 }
161}
162
163fn split_top_level(inner: &str) -> Vec<&str> {
165 let mut items = vec![];
166 let mut quote: Option<char> = None;
167 let mut depth = 0usize;
168 let mut start = 0;
169 for (i, c) in inner.char_indices() {
170 match (quote, c) {
171 (None, '"') | (None, '\'') => quote = Some(c),
172 (Some(q), c) if c == q => quote = None,
173 (None, '[') => depth += 1,
174 (None, ']') => depth = depth.saturating_sub(1),
175 (None, ',') if depth == 0 => {
176 items.push(&inner[start..i]);
177 start = i + 1;
178 }
179 _ => {}
180 }
181 }
182 items.push(&inner[start..]);
183 items
184}
185
186pub fn read_config_file(
190 cursor: Cursor<&[u8]>,
191 prefix: String) -> Result<bool, String> {
192 let resolved = collect_settings(cursor, prefix)?;
193 for (name, value) in &resolved.settings {
194 set_setting(name, value);
195 }
196 for key in &resolved.unknown {
197 eprintln!(" Warning: unknown setting '{}' in rws.config.toml — ignored", key);
198 }
199 Ok(true)
200}
201
202fn set_setting(name: &str, value: &str) {
203 if value.contains('\0') {
204 eprintln!(" Warning: value for {} contains a NUL byte — ignored", name);
206 return;
207 }
208 env::set_var(name, value);
209 crate::server_config::invalidate();
210 println!(" Set env variable '{}' to value '{}'", name, value);
211}
212
213fn qualified_key(table: &str, key: &str) -> String {
214 if table.is_empty() { key.to_string() } else { format!("[{}] {}", table, key) }
215}
216
217fn strip_comment(line: &str) -> &str {
219 let mut quote: Option<char> = None;
220 for (i, c) in line.char_indices() {
221 match (quote, c) {
222 (None, '"') | (None, '\'') => quote = Some(c),
223 (Some(q), c) if c == q => quote = None,
224 (None, '#') => return &line[..i],
225 _ => {}
226 }
227 }
228 line
229}
230
231fn parse_value(raw: &str) -> String {
234 let raw = raw.trim();
235 if let Some(inner) = raw.strip_prefix('[').and_then(|r| r.strip_suffix(']')) {
236 return split_array(inner)
237 .iter()
238 .map(|item| unquote(item.trim()))
239 .filter(|item| !item.is_empty())
240 .collect::<Vec<_>>()
241 .join(",");
242 }
243 unquote(raw)
244}
245
246fn unquote(s: &str) -> String {
247 for q in ['"', '\''] {
248 if s.len() >= 2 && s.starts_with(q) && s.ends_with(q) {
249 return s[1..s.len() - 1].to_string();
250 }
251 }
252 s.to_string()
253}
254
255fn split_array(inner: &str) -> Vec<&str> {
257 let mut items = vec![];
258 let mut quote: Option<char> = None;
259 let mut start = 0;
260 for (i, c) in inner.char_indices() {
261 match (quote, c) {
262 (None, '"') | (None, '\'') => quote = Some(c),
263 (Some(q), c) if c == q => quote = None,
264 (None, ',') => {
265 items.push(&inner[start..i]);
266 start = i + 1;
267 }
268 _ => {}
269 }
270 }
271 items.push(&inner[start..]);
272 items
273}
274
275pub fn override_environment_variables_from_config(filepath: Option<&str>) {
281 println!("\n Start of Config Section");
282
283 let from_env = env::var("RWS_CONFIG_FILE").ok().filter(|p| !p.trim().is_empty());
284 let resolved = match (filepath, from_env) {
285 (Some(path), _) => FileExt::get_static_filepath(path),
286 (None, Some(path)) => Ok(path),
287 (None, None) => FileExt::get_static_filepath("/rws.config.toml"),
288 };
289 let path = match resolved {
290 Ok(path) => path,
291 Err(e) => {
292 eprintln!("{}", e);
293 println!(" End of Config Section");
294 return;
295 }
296 };
297
298 match std::fs::read_to_string(&path) {
299 Ok(content) => {
300 if let Err(e) = read_config_file(Cursor::new(content.as_bytes()), String::new()) {
301 eprintln!(" Unable to parse {}: {}", path, e);
302 }
303 }
304 Err(e) => eprintln!(" Unable to read {}: {}", path, e),
305 }
306
307 println!(" End of Config Section");
308}