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_SPA_FALLBACK",
30 "RWS_CONFIG_SPA_FALLBACK_EXCLUDE_PREFIXES",
31 "RWS_CONFIG_TEMPLATE_DIR",
32 "RWS_CONFIG_TLS_CLIENT_CA_FILE",
33];
34
35const PROXY_TABLES: &[&str] = &["route", "upstream", "tcp_proxy", "udp_proxy", "ws_proxy", "middleware"];
38
39const VIRTUAL_HOST_FIELDS: &[&str] = &["DOMAIN", "CERT_FILE", "KEY_FILE"];
41
42#[derive(Debug, Default, PartialEq)]
45pub struct ConfigSettings {
46 pub settings: Vec<(String, String)>,
48 pub unknown: Vec<String>,
50}
51
52pub fn collect_settings(
61 cursor: Cursor<&[u8]>,
62 prefix: String) -> Result<ConfigSettings, String> {
63
64 let mut table = prefix;
65 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
129pub 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 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
160fn 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
174fn 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
198fn 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
218pub 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}