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