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_RATE_LIMIT_MAX_REQUESTS",
27 "RWS_CONFIG_RATE_LIMIT_WINDOW_SECS",
28 "RWS_CONFIG_SPA_FALLBACK",
29 "RWS_CONFIG_SPA_FALLBACK_EXCLUDE_PREFIXES",
30 "RWS_CONFIG_TEMPLATE_DIR",
31 "RWS_CONFIG_TLS_CLIENT_CA_FILE",
32];
33
34const PROXY_TABLES: &[&str] = &["route", "upstream", "tcp_proxy", "udp_proxy", "ws_proxy"];
37
38const VIRTUAL_HOST_FIELDS: &[&str] = &["DOMAIN", "CERT_FILE", "KEY_FILE"];
40
41pub fn read_config_file(
50 cursor: Cursor<&[u8]>,
51 prefix: String) -> Result<bool, String> {
52
53 let mut table = prefix;
54 let mut array_table_counters: HashMap<String, usize> = HashMap::new();
56 let mut array_index: Option<usize> = None;
57 let mut flag_arguments: Vec<String> = vec![];
58 let flags = CommandLineArgument::get_command_line_arg_list();
59
60 for line in cursor.lines() {
61 let line = line.map_err(|e| e.to_string())?;
62 let line = strip_comment(&line).trim().to_string();
63 if line.is_empty() {
64 continue;
65 }
66
67 if let Some(name) = line.strip_prefix("[[").and_then(|l| l.strip_suffix("]]")) {
68 let name = name.trim().to_string();
69 let count = array_table_counters.entry(name.clone()).or_insert(0);
70 array_index = Some(*count);
71 *count += 1;
72 table = name;
73 continue;
74 }
75 if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
76 table = name.trim().to_string();
77 array_index = None;
78 continue;
79 }
80
81 let Some((raw_key, raw_value)) = line.split_once('=') else { continue };
82 let key = raw_key.trim();
83 let value = parse_value(raw_value);
84
85 let root = table.split('.').next().unwrap_or("");
86 if PROXY_TABLES.contains(&root) {
87 continue;
88 }
89
90 if table == "virtual_host" {
91 let field = key.to_ascii_uppercase();
92 if VIRTUAL_HOST_FIELDS.contains(&field.as_str()) {
93 let name = format!("RWS_CONFIG_VIRTUAL_HOST_{}_{}", array_index.unwrap_or(0), field);
94 set_setting(&name, &value);
95 } else {
96 warn_unknown(&table, key);
97 }
98 continue;
99 }
100
101 let path = if table.is_empty() { key.to_string() } else { format!("{}_{}", table.replace('.', "_"), key) };
102 let long_form = path.replace('_', "-");
103 if flags.iter().any(|f| f.long_form == long_form) {
104 flag_arguments.push(format!("--{}={}", long_form, value));
105 continue;
106 }
107 let name = format!("RWS_CONFIG_{}", path.to_ascii_uppercase());
108 if SETTINGS_WITHOUT_FLAG.contains(&name.as_str()) {
109 set_setting(&name, &value);
110 } else {
111 warn_unknown(&table, key);
112 }
113 }
114 CommandLineArgument::_parse(flag_arguments, flags);
115
116 Ok(true)
117}
118
119fn set_setting(name: &str, value: &str) {
120 env::set_var(name, value);
121 println!(" Set env variable '{}' to value '{}'", name, value);
122}
123
124fn warn_unknown(table: &str, key: &str) {
125 let qualified = if table.is_empty() { key.to_string() } else { format!("[{}] {}", table, key) };
126 eprintln!(" Warning: unknown setting '{}' in rws.config.toml — ignored", qualified);
127}
128
129fn strip_comment(line: &str) -> &str {
131 let mut quote: Option<char> = None;
132 for (i, c) in line.char_indices() {
133 match (quote, c) {
134 (None, '"') | (None, '\'') => quote = Some(c),
135 (Some(q), c) if c == q => quote = None,
136 (None, '#') => return &line[..i],
137 _ => {}
138 }
139 }
140 line
141}
142
143fn parse_value(raw: &str) -> String {
146 let raw = raw.trim();
147 if let Some(inner) = raw.strip_prefix('[').and_then(|r| r.strip_suffix(']')) {
148 return split_array(inner)
149 .iter()
150 .map(|item| unquote(item.trim()))
151 .filter(|item| !item.is_empty())
152 .collect::<Vec<_>>()
153 .join(",");
154 }
155 unquote(raw)
156}
157
158fn unquote(s: &str) -> String {
159 for q in ['"', '\''] {
160 if s.len() >= 2 && s.starts_with(q) && s.ends_with(q) {
161 return s[1..s.len() - 1].to_string();
162 }
163 }
164 s.to_string()
165}
166
167fn split_array(inner: &str) -> Vec<&str> {
169 let mut items = vec![];
170 let mut quote: Option<char> = None;
171 let mut start = 0;
172 for (i, c) in inner.char_indices() {
173 match (quote, c) {
174 (None, '"') | (None, '\'') => quote = Some(c),
175 (Some(q), c) if c == q => quote = None,
176 (None, ',') => {
177 items.push(&inner[start..i]);
178 start = i + 1;
179 }
180 _ => {}
181 }
182 }
183 items.push(&inner[start..]);
184 items
185}
186
187pub fn override_environment_variables_from_config(filepath: Option<&str>) {
193 println!("\n Start of Config Section");
194
195 let from_env = env::var("RWS_CONFIG_FILE").ok().filter(|p| !p.trim().is_empty());
196 let resolved = match (filepath, from_env) {
197 (Some(path), _) => FileExt::get_static_filepath(path),
198 (None, Some(path)) => Ok(path),
199 (None, None) => FileExt::get_static_filepath("/rws.config.toml"),
200 };
201 let path = match resolved {
202 Ok(path) => path,
203 Err(e) => {
204 eprintln!("{}", e);
205 println!(" End of Config Section");
206 return;
207 }
208 };
209
210 match std::fs::read_to_string(&path) {
211 Ok(content) => {
212 if let Err(e) = read_config_file(Cursor::new(content.as_bytes()), String::new()) {
213 eprintln!(" Unable to parse {}: {}", path, e);
214 }
215 }
216 Err(e) => eprintln!(" Unable to read {}: {}", path, e),
217 }
218
219 println!(" End of Config Section");
220}