Skip to main content

rws_http/entry_point/
mod.rs

1#[cfg(test)]
2mod tests;
3/// `println!` for startup detail, printed only with `--verbose` (or
4/// `RWS_VERBOSE=true`): see [`verbose`].
5macro_rules! startup_note {
6    ($($arg:tt)*) => {
7        if $crate::entry_point::verbose() {
8            println!($($arg)*);
9        }
10    };
11}
12
13pub mod command_line_args;
14pub mod config_file;
15pub mod environment_variables;
16mod rws_env;
17pub use rws_env::RwsEnv;
18
19
20use std::{env};
21use crate::virtual_host::VirtualHostConfig;
22
23use crate::entry_point::command_line_args::{override_environment_variables_from_command_line_args};
24use crate::entry_point::config_file::override_environment_variables_from_config;
25use crate::entry_point::environment_variables::read_system_environment_variables;
26
27/// Whether startup prints every setting and step (`--verbose` or
28/// `RWS_VERBOSE=true`, since 18.37.0). Without it rws prints a few lines:
29/// version, where the configuration came from, the address it serves on.
30pub fn verbose() -> bool {
31    static VERBOSE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
32    *VERBOSE.get_or_init(|| {
33        env::args().any(|a| a == "--verbose")
34            || env::var("RWS_VERBOSE").is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes"))
35    })
36}
37
38/// One line of startup detail (see [`verbose`]).
39pub fn note(line: &str) {
40    if verbose() {
41        println!("{line}");
42    }
43}
44
45/// The configuration file the last load read, or `None` when there was
46/// none (rws runs on defaults, environment and flags).
47pub fn config_source() -> Option<String> {
48    CONFIG_SOURCE.lock().ok().and_then(|s| s.clone())
49}
50
51pub(crate) static CONFIG_SOURCE: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
52
53/// Levenshtein distance, for "did you mean" hints.
54pub fn edit_distance(a: &str, b: &str) -> usize {
55    let b: Vec<char> = b.chars().collect();
56    let mut prev: Vec<usize> = (0..=b.len()).collect();
57    for (i, ca) in a.chars().enumerate() {
58        let mut cur = vec![i + 1; b.len() + 1];
59        for (j, cb) in b.iter().enumerate() {
60            cur[j + 1] = (prev[j] + usize::from(ca != *cb)).min(prev[j + 1] + 1).min(cur[j] + 1);
61        }
62        prev = cur;
63    }
64    prev[b.len()]
65}
66
67/// `value` as startup output may show it: secrets (a name with `SECRET`,
68/// `PASSWORD` or `TOKEN`) are replaced.
69pub fn shown<'a>(name: &str, value: &'a str) -> std::borrow::Cow<'a, str> {
70    let upper = name.to_ascii_uppercase();
71    if ["SECRET", "PASSWORD", "TOKEN"].iter().any(|word| upper.contains(word)) && !value.is_empty() {
72        return std::borrow::Cow::Borrowed("(hidden)");
73    }
74    // A PIN inside a PKCS#11 URI (`tls_key_file = "pkcs11:…?pin-value=1234"`).
75    if let Some(at) = value.find("pin-value=") {
76        let start = at + "pin-value=".len();
77        let end = value[start..].find(['&', ';']).map_or(value.len(), |n| start + n);
78        return std::borrow::Cow::Owned(format!("{}(hidden){}", &value[..start], &value[end..]));
79    }
80    std::borrow::Cow::Borrowed(value)
81}
82
83#[derive(PartialEq, Eq, Clone, Debug)]
84pub struct Config {}
85
86impl Config {
87    pub const RWS_CONFIG_IP: &'static str = "RWS_CONFIG_IP";
88    /// Default is `0.0.0.0` so the server is reachable inside containers and K8s pods.
89    /// For local development you can override to `127.0.0.1` via env var or config file.
90    pub const RWS_CONFIG_IP_DEFAULT_VALUE: &'static str = "0.0.0.0";
91
92    /// Log format: `"combined"` (default, Combined Log Format) or `"json"` (structured JSON).
93    pub const RWS_CONFIG_LOG_FORMAT: &'static str = "RWS_CONFIG_LOG_FORMAT";
94    pub const RWS_CONFIG_LOG_FORMAT_DEFAULT_VALUE: &'static str = "json";
95
96    pub const RWS_CONFIG_PORT: &'static str = "RWS_CONFIG_PORT";
97    pub const RWS_CONFIG_PORT_DEFAULT_VALUE: &'static str = "7878";
98
99    pub const RWS_CONFIG_THREAD_COUNT: &'static str = "RWS_CONFIG_THREAD_COUNT";
100    pub const RWS_CONFIG_THREAD_COUNT_DEFAULT_VALUE: &'static str = "200";
101
102    pub const RWS_CONFIG_CORS_ALLOW_ALL: &'static str = "RWS_CONFIG_CORS_ALLOW_ALL";
103    pub const RWS_CONFIG_CORS_ALLOW_ALL_DEFAULT_VALUE: &'static str = "false";
104
105    pub const RWS_CONFIG_CORS_ALLOW_ORIGINS: &'static str = "RWS_CONFIG_CORS_ALLOW_ORIGINS";
106    pub const RWS_CONFIG_CORS_ALLOW_ORIGINS_DEFAULT_VALUE: &'static str = "";
107
108    pub const RWS_CONFIG_CORS_ALLOW_CREDENTIALS: &'static str = "RWS_CONFIG_CORS_ALLOW_CREDENTIALS";
109    pub const RWS_CONFIG_CORS_ALLOW_CREDENTIALS_DEFAULT_VALUE: &'static str = "";
110
111    pub const RWS_CONFIG_CORS_ALLOW_HEADERS: &'static str = "RWS_CONFIG_CORS_ALLOW_HEADERS";
112    pub const RWS_CONFIG_CORS_ALLOW_HEADERS_DEFAULT_VALUE: &'static str = "";
113
114    pub const RWS_CONFIG_CORS_ALLOW_METHODS: &'static str = "RWS_CONFIG_CORS_ALLOW_METHODS";
115    pub const RWS_CONFIG_CORS_ALLOW_METHODS_DEFAULT_VALUE: &'static str = "";
116
117    pub const RWS_CONFIG_CORS_EXPOSE_HEADERS: &'static str = "RWS_CONFIG_CORS_EXPOSE_HEADERS";
118    pub const RWS_CONFIG_CORS_EXPOSE_HEADERS_DEFAULT_VALUE: &'static str = "";
119
120    pub const RWS_CONFIG_CORS_MAX_AGE: &'static str = "RWS_CONFIG_CORS_MAX_AGE";
121    pub const RWS_CONFIG_CORS_MAX_AGE_DEFAULT_VALUE: &'static str = "86400";
122
123    pub const RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES: &'static str = "RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES";
124    pub const RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES_DEFAULT_VALUE: &'static str = "10000";
125
126    /// Maximum accepted request body size in bytes, checked against `Content-Length`
127    /// before any body bytes are read off the socket. `0` (the default) means
128    /// unlimited — this is opt-in, not a default-on behavior change. Requests whose
129    /// declared body exceeds this get `413 Payload Too Large` and the connection is
130    /// closed (not kept alive), since bytes the server chose not to read are still
131    /// queued on the client's side of the socket.
132    pub const RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES: &'static str = "RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES";
133    pub const RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES_DEFAULT_VALUE: &'static str = "0";
134
135    /// Serve this file (e.g. `"index.html"`) for a `GET`/`HEAD` request that doesn't
136    /// match any real file/directory, instead of `404` — the standard client-side-router
137    /// ("SPA") fallback pattern needed for deep links in a React Router / Vue Router /
138    /// etc. app. Empty (default) disables it entirely. See
139    /// `crate::app::controller::static_resource` for the matching heuristic (skips
140    /// paths that look like a missed static asset, i.e. the last segment has a `.`).
141    pub const RWS_CONFIG_SPA_FALLBACK: &'static str = "RWS_CONFIG_SPA_FALLBACK";
142    pub const RWS_CONFIG_SPA_FALLBACK_DEFAULT_VALUE: &'static str = "";
143
144    /// Comma-separated path prefixes (e.g. `"/api,/healthz"`) that never receive the
145    /// SPA fallback even when `RWS_CONFIG_SPA_FALLBACK` is set — so a real API `404`
146    /// isn't silently rewritten into a `200`. Empty (default) excludes nothing.
147    pub const RWS_CONFIG_SPA_FALLBACK_EXCLUDE_PREFIXES: &'static str = "RWS_CONFIG_SPA_FALLBACK_EXCLUDE_PREFIXES";
148    pub const RWS_CONFIG_SPA_FALLBACK_EXCLUDE_PREFIXES_DEFAULT_VALUE: &'static str = "";
149
150    /// SPA fallbacks per path prefix, comma-separated `prefix=file` pairs
151    /// (`"/cloud=cloud/index.html,/admin=admin/index.html"`): an unknown path at or under
152    /// a prefix gets that prefix's file, so several single-page apps can share one server
153    /// beside ordinary pages whose misses stay `404`. The longest matching prefix wins;
154    /// paths under no prefix fall back to `RWS_CONFIG_SPA_FALLBACK` (if set). Excluded
155    /// prefixes and paths that look like a missed asset are never rewritten.
156    pub const RWS_CONFIG_SPA_FALLBACK_ROUTES: &'static str = "RWS_CONFIG_SPA_FALLBACK_ROUTES";
157    pub const RWS_CONFIG_SPA_FALLBACK_ROUTES_DEFAULT_VALUE: &'static str = "";
158
159    pub const RWS_CONFIG_TLS_CERT_FILE: &'static str = "RWS_CONFIG_TLS_CERT_FILE";
160    pub const RWS_CONFIG_TLS_CERT_FILE_DEFAULT_VALUE: &'static str = "";
161
162    pub const RWS_CONFIG_TLS_KEY_FILE: &'static str = "RWS_CONFIG_TLS_KEY_FILE";
163    pub const RWS_CONFIG_TLS_KEY_FILE_DEFAULT_VALUE: &'static str = "";
164
165    /// Path to a PEM-encoded CA certificate used to verify client certificates (mTLS).
166    /// When set, the TLS handshake requires a valid client certificate signed by this CA.
167    /// Connections without a valid cert are rejected at the TLS layer (before any HTTP processing).
168    pub const RWS_CONFIG_TLS_CLIENT_CA_FILE: &'static str = "RWS_CONFIG_TLS_CLIENT_CA_FILE";
169    pub const RWS_CONFIG_TLS_CLIENT_CA_FILE_DEFAULT_VALUE: &'static str = "";
170
171    /// Directory containing Tera HTML templates (default: `"templates"`). Requires `tera` feature.
172    pub const RWS_CONFIG_TEMPLATE_DIR: &'static str = "RWS_CONFIG_TEMPLATE_DIR";
173    pub const RWS_CONFIG_TEMPLATE_DIR_DEFAULT_VALUE: &'static str = "templates";
174
175    /// When non-empty, a plain-HTTP listener on this port redirects all requests to HTTPS.
176    /// Set to e.g. `"80"` when running on standard ports. Requires TLS to be configured.
177    pub const RWS_CONFIG_HTTP_REDIRECT_PORT: &'static str = "RWS_CONFIG_HTTP_REDIRECT_PORT";
178    pub const RWS_CONFIG_HTTP_REDIRECT_PORT_DEFAULT_VALUE: &'static str = "";
179
180    // ── ACME (Automatic Certificate Management Environment) ───────────────────
181
182    /// Comma-separated list of domain names to obtain a certificate for.
183    /// Setting this activates ACME at startup. Example: `"example.com,www.example.com"`
184    pub const RWS_CONFIG_ACME_DOMAINS: &'static str = "RWS_CONFIG_ACME_DOMAINS";
185    pub const RWS_CONFIG_ACME_DOMAINS_DEFAULT_VALUE: &'static str = "";
186
187    /// Contact email sent to the CA. Recommended but not required.
188    pub const RWS_CONFIG_ACME_EMAIL: &'static str = "RWS_CONFIG_ACME_EMAIL";
189    pub const RWS_CONFIG_ACME_EMAIL_DEFAULT_VALUE: &'static str = "";
190
191    /// Set to `"true"` to use the Let's Encrypt staging environment (for testing).
192    pub const RWS_CONFIG_ACME_STAGING: &'static str = "RWS_CONFIG_ACME_STAGING";
193    pub const RWS_CONFIG_ACME_STAGING_DEFAULT_VALUE: &'static str = "false";
194
195    /// Custom ACME directory URL. Defaults to Let's Encrypt production.
196    pub const RWS_CONFIG_ACME_DIRECTORY: &'static str = "RWS_CONFIG_ACME_DIRECTORY";
197    pub const RWS_CONFIG_ACME_DIRECTORY_DEFAULT_VALUE: &'static str = "";
198
199    /// Where to write the provisioned certificate chain (PEM). Defaults to `RWS_CONFIG_TLS_CERT_FILE`,
200    /// or `cert.pem` in the working directory when that is empty too.
201    pub const RWS_CONFIG_ACME_CERT_PATH: &'static str = "RWS_CONFIG_ACME_CERT_PATH";
202    pub const RWS_CONFIG_ACME_CERT_PATH_DEFAULT_VALUE: &'static str = "";
203
204    /// Where to write the certificate's private key (PEM). Defaults to `RWS_CONFIG_TLS_KEY_FILE`,
205    /// or `key.pem` in the working directory when that is empty too.
206    pub const RWS_CONFIG_ACME_KEY_PATH: &'static str = "RWS_CONFIG_ACME_KEY_PATH";
207    pub const RWS_CONFIG_ACME_KEY_PATH_DEFAULT_VALUE: &'static str = "";
208
209    /// Port for the temporary HTTP-01 challenge server (default 80).
210    /// Must be reachable from the internet on port 80. Not used with DNS-01.
211    pub const RWS_CONFIG_ACME_CHALLENGE_PORT: &'static str = "RWS_CONFIG_ACME_CHALLENGE_PORT";
212    pub const RWS_CONFIG_ACME_CHALLENGE_PORT_DEFAULT_VALUE: &'static str = "80";
213
214    /// Renew when fewer than this many days remain on the certificate (default 30).
215    pub const RWS_CONFIG_ACME_RENEW_BEFORE_DAYS: &'static str = "RWS_CONFIG_ACME_RENEW_BEFORE_DAYS";
216    /// Empty: renew at two-thirds of the certificate's lifetime (or the CA's
217    /// renewal window), not a fixed number of days before expiry.
218    pub const RWS_CONFIG_ACME_RENEW_BEFORE_DAYS_DEFAULT_VALUE: &'static str = "";
219    pub const RWS_CONFIG_ACME_PROFILE: &'static str = "RWS_CONFIG_ACME_PROFILE";
220
221    /// Path to persist the ACME account key between restarts (default `acme_account.key`).
222    pub const RWS_CONFIG_ACME_ACCOUNT_KEY_PATH: &'static str = "RWS_CONFIG_ACME_ACCOUNT_KEY_PATH";
223    pub const RWS_CONFIG_ACME_ACCOUNT_KEY_PATH_DEFAULT_VALUE: &'static str = "acme_account.key";
224
225    /// PEM file of extra root CAs to trust when talking to the ACME directory,
226    /// on top of the public Web PKI roots — for a private ACME CA (step-ca,
227    /// Pebble, an internal Boulder). Empty means public roots only.
228    pub const RWS_CONFIG_ACME_CA_FILE: &'static str = "RWS_CONFIG_ACME_CA_FILE";
229    pub const RWS_CONFIG_ACME_CA_FILE_DEFAULT_VALUE: &'static str = "";
230
231    /// Seconds between certificate-expiry checks in the renewal loop (default 12h).
232    /// After a failed renewal the next attempt comes after at most one hour.
233    pub const RWS_CONFIG_ACME_RENEW_CHECK_INTERVAL_SECS: &'static str = "RWS_CONFIG_ACME_RENEW_CHECK_INTERVAL_SECS";
234    pub const RWS_CONFIG_ACME_RENEW_CHECK_INTERVAL_SECS_DEFAULT_VALUE: &'static str = "43200";
235
236    /// How to prove control of the domains: `http-01` (default),
237    /// `tls-alpn-01` (on the HTTPS port) or `dns-01` (needed for wildcards).
238    pub const RWS_CONFIG_ACME_CHALLENGE: &'static str = "RWS_CONFIG_ACME_CHALLENGE";
239    /// DNS-01: `rfc2136` (a DNS UPDATE to `RWS_CONFIG_ACME_DNS_SERVER`) or
240    /// `exec` (a program that adds and removes the record).
241    pub const RWS_CONFIG_ACME_DNS_PROVIDER: &'static str = "RWS_CONFIG_ACME_DNS_PROVIDER";
242    /// DNS-01 `rfc2136`: the primary server, `host[:port]` (port 53).
243    pub const RWS_CONFIG_ACME_DNS_SERVER: &'static str = "RWS_CONFIG_ACME_DNS_SERVER";
244    /// DNS-01: the zone holding the records; found by SOA lookup when empty.
245    pub const RWS_CONFIG_ACME_DNS_ZONE: &'static str = "RWS_CONFIG_ACME_DNS_ZONE";
246    /// DNS-01 `rfc2136`: the TSIG key name the server knows.
247    pub const RWS_CONFIG_ACME_DNS_TSIG_KEY: &'static str = "RWS_CONFIG_ACME_DNS_TSIG_KEY";
248    /// DNS-01 `rfc2136`: the TSIG secret, base64 — never printed.
249    pub const RWS_CONFIG_ACME_DNS_TSIG_SECRET: &'static str = "RWS_CONFIG_ACME_DNS_TSIG_SECRET";
250    /// DNS-01 `rfc2136`: `hmac-sha256` (default) or `hmac-sha512`.
251    pub const RWS_CONFIG_ACME_DNS_TSIG_ALGORITHM: &'static str = "RWS_CONFIG_ACME_DNS_TSIG_ALGORITHM";
252    /// DNS-01 `exec`: the program run as `<program> present|cleanup <fqdn> <value>`.
253    pub const RWS_CONFIG_ACME_DNS_EXEC: &'static str = "RWS_CONFIG_ACME_DNS_EXEC";
254    /// DNS-01: how long to wait for the record to be visible (default 120).
255    pub const RWS_CONFIG_ACME_DNS_PROPAGATION_SECS: &'static str = "RWS_CONFIG_ACME_DNS_PROPAGATION_SECS";
256    /// DNS-01 cloudflare: the API token (DNS edit) — never printed.
257    pub const RWS_CONFIG_ACME_DNS_API_TOKEN: &'static str = "RWS_CONFIG_ACME_DNS_API_TOKEN";
258    /// DNS-01 cloudflare / route53: the API base URL instead of the
259    /// provider's own (a proxy, a test double).
260    pub const RWS_CONFIG_ACME_DNS_API_URL: &'static str = "RWS_CONFIG_ACME_DNS_API_URL";
261    /// DNS-01 cloudflare / route53: the zone's id, instead of looking it up.
262    pub const RWS_CONFIG_ACME_DNS_ZONE_ID: &'static str = "RWS_CONFIG_ACME_DNS_ZONE_ID";
263    /// Redis (`host:port`) shared by replicas: one orders, all install.
264    pub const RWS_CONFIG_ACME_REDIS: &'static str = "RWS_CONFIG_ACME_REDIS";
265    /// Password for `RWS_CONFIG_ACME_REDIS` — never printed.
266    pub const RWS_CONFIG_ACME_REDIS_PASSWORD: &'static str = "RWS_CONFIG_ACME_REDIS_PASSWORD";
267    /// Key prefix in that Redis (default `rws:acme`).
268    pub const RWS_CONFIG_ACME_REDIS_PREFIX: &'static str = "RWS_CONFIG_ACME_REDIS_PREFIX";
269    /// `true`: order a certificate at the first TLS handshake for a name
270    /// `RWS_CONFIG_ACME_ON_DEMAND_ASK` allows (since 18.4.0).
271    pub const RWS_CONFIG_ACME_ON_DEMAND: &'static str = "RWS_CONFIG_ACME_ON_DEMAND";
272    /// On-demand TLS: URL asked `?domain=<name>` before each order; 2xx allows it.
273    pub const RWS_CONFIG_ACME_ON_DEMAND_ASK: &'static str = "RWS_CONFIG_ACME_ON_DEMAND_ASK";
274    /// `[admin] listen`: `host:port` of the admin API (since 18.10.0); unset = off.
275    pub const RWS_CONFIG_ADMIN_LISTEN: &'static str = "RWS_CONFIG_ADMIN_LISTEN";
276    /// `[admin] token_env`: the environment variable holding the admin bearer
277    /// token (default `RWS_ADMIN_TOKEN`).
278    pub const RWS_CONFIG_ADMIN_TOKEN_ENV: &'static str = "RWS_CONFIG_ADMIN_TOKEN_ENV";
279    /// `[admin] allowed_origins`: browser origins allowed besides the admin
280    /// listener's own (comma list).
281    pub const RWS_CONFIG_ADMIN_ALLOWED_ORIGINS: &'static str = "RWS_CONFIG_ADMIN_ALLOWED_ORIGINS";
282
283
284    pub const RWS_DEFAULT_IP: &'static str = "127.0.0.1";
285    pub const RWS_DEFAULT_PORT: &'static i32 = &7878;
286    pub const RWS_DEFAULT_THREAD_COUNT: &'static i32 = &200;
287    pub const RWS_DEFAULT_REQUEST_ALLOCATION_SIZE_IN_BYTES: &'static i64 = &10000;
288
289
290}
291
292pub fn bootstrap() {
293    read_system_environment_variables();
294    override_environment_variables_from_config(None);
295    override_environment_variables_from_command_line_args();
296    crate::server_config::invalidate();
297}
298
299pub fn set_default_values() {
300    startup_note!("  Initializing default values");
301
302    let is_var_set = env::var(Config::RWS_CONFIG_IP).is_ok();
303    if !is_var_set {
304        env::set_var(Config::RWS_CONFIG_IP, Config::RWS_CONFIG_IP_DEFAULT_VALUE);
305        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_IP, Config::RWS_CONFIG_IP_DEFAULT_VALUE);
306    } else {
307        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_IP);
308    }
309
310
311    let is_var_set = env::var(Config::RWS_CONFIG_PORT).is_ok();
312    if !is_var_set {
313        env::set_var(Config::RWS_CONFIG_PORT, Config::RWS_CONFIG_PORT_DEFAULT_VALUE);
314        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_PORT, Config::RWS_CONFIG_PORT_DEFAULT_VALUE);
315    } else {
316        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_PORT);
317    }
318
319    let is_var_set = env::var(Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES).is_ok();
320    if !is_var_set {
321        env::set_var(Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES, Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES_DEFAULT_VALUE);
322        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES, Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES_DEFAULT_VALUE);
323    } else {
324        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES);
325    }
326
327
328    let is_var_set = env::var(Config::RWS_CONFIG_THREAD_COUNT).is_ok();
329    if !is_var_set {
330        env::set_var(Config::RWS_CONFIG_THREAD_COUNT, Config::RWS_CONFIG_THREAD_COUNT_DEFAULT_VALUE);
331        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_THREAD_COUNT, Config::RWS_CONFIG_THREAD_COUNT_DEFAULT_VALUE);
332    } else {
333        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_THREAD_COUNT);
334    }
335
336    let is_var_set = env::var(Config::RWS_CONFIG_CORS_ALLOW_ALL).is_ok();
337    if !is_var_set {
338        env::set_var(Config::RWS_CONFIG_CORS_ALLOW_ALL, Config::RWS_CONFIG_CORS_ALLOW_ALL_DEFAULT_VALUE);
339        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_CORS_ALLOW_ALL, Config::RWS_CONFIG_CORS_ALLOW_ALL_DEFAULT_VALUE);
340    } else {
341        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_CORS_ALLOW_ALL);
342    }
343
344
345    let is_var_set = env::var(Config::RWS_CONFIG_CORS_ALLOW_ORIGINS).is_ok();
346    if !is_var_set {
347        env::set_var(Config::RWS_CONFIG_CORS_ALLOW_ORIGINS, Config::RWS_CONFIG_CORS_ALLOW_ORIGINS_DEFAULT_VALUE);
348        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_CORS_ALLOW_ORIGINS, Config::RWS_CONFIG_CORS_ALLOW_ORIGINS_DEFAULT_VALUE);
349    } else {
350        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_CORS_ALLOW_ORIGINS);
351    }
352
353    let is_var_set = env::var(Config::RWS_CONFIG_CORS_ALLOW_CREDENTIALS).is_ok();
354    if !is_var_set {
355        env::set_var(Config::RWS_CONFIG_CORS_ALLOW_CREDENTIALS, Config::RWS_CONFIG_CORS_ALLOW_CREDENTIALS_DEFAULT_VALUE);
356        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_CORS_ALLOW_CREDENTIALS, Config::RWS_CONFIG_CORS_ALLOW_CREDENTIALS_DEFAULT_VALUE);
357    } else {
358        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_CORS_ALLOW_CREDENTIALS);
359    }
360
361    let is_var_set = env::var(Config::RWS_CONFIG_CORS_ALLOW_HEADERS).is_ok();
362    if !is_var_set {
363        env::set_var(Config::RWS_CONFIG_CORS_ALLOW_HEADERS, Config::RWS_CONFIG_CORS_ALLOW_HEADERS_DEFAULT_VALUE);
364        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_CORS_ALLOW_HEADERS, Config::RWS_CONFIG_CORS_ALLOW_HEADERS_DEFAULT_VALUE);
365    } else {
366        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_CORS_ALLOW_HEADERS);
367    }
368
369
370    let is_var_set = env::var(Config::RWS_CONFIG_CORS_ALLOW_METHODS).is_ok();
371    if !is_var_set {
372        env::set_var(Config::RWS_CONFIG_CORS_ALLOW_METHODS, Config::RWS_CONFIG_CORS_ALLOW_METHODS_DEFAULT_VALUE);
373        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_CORS_ALLOW_METHODS, Config::RWS_CONFIG_CORS_ALLOW_METHODS_DEFAULT_VALUE);
374    } else {
375        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_CORS_ALLOW_METHODS);
376    }
377
378    let is_var_set = env::var(Config::RWS_CONFIG_CORS_EXPOSE_HEADERS).is_ok();
379    if !is_var_set {
380        env::set_var(Config::RWS_CONFIG_CORS_EXPOSE_HEADERS, Config::RWS_CONFIG_CORS_EXPOSE_HEADERS_DEFAULT_VALUE);
381        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_CORS_EXPOSE_HEADERS, Config::RWS_CONFIG_CORS_EXPOSE_HEADERS_DEFAULT_VALUE);
382    } else {
383        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_CORS_EXPOSE_HEADERS);
384    }
385
386    let is_var_set = env::var(Config::RWS_CONFIG_CORS_MAX_AGE).is_ok();
387    if !is_var_set {
388        env::set_var(Config::RWS_CONFIG_CORS_MAX_AGE, Config::RWS_CONFIG_CORS_MAX_AGE_DEFAULT_VALUE);
389        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_CORS_MAX_AGE, Config::RWS_CONFIG_CORS_MAX_AGE_DEFAULT_VALUE);
390    } else {
391        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_CORS_MAX_AGE);
392    }
393
394
395    let is_var_set = env::var(Config::RWS_CONFIG_TLS_CERT_FILE).is_ok();
396    if !is_var_set {
397        env::set_var(Config::RWS_CONFIG_TLS_CERT_FILE, Config::RWS_CONFIG_TLS_CERT_FILE_DEFAULT_VALUE);
398        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_TLS_CERT_FILE, Config::RWS_CONFIG_TLS_CERT_FILE_DEFAULT_VALUE);
399    } else {
400        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_TLS_CERT_FILE);
401    }
402
403    let is_var_set = env::var(Config::RWS_CONFIG_TLS_KEY_FILE).is_ok();
404    if !is_var_set {
405        env::set_var(Config::RWS_CONFIG_TLS_KEY_FILE, Config::RWS_CONFIG_TLS_KEY_FILE_DEFAULT_VALUE);
406        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_TLS_KEY_FILE, Config::RWS_CONFIG_TLS_KEY_FILE_DEFAULT_VALUE);
407    } else {
408        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_TLS_KEY_FILE);
409    }
410
411    let is_var_set = env::var(Config::RWS_CONFIG_HTTP_REDIRECT_PORT).is_ok();
412    if !is_var_set {
413        env::set_var(Config::RWS_CONFIG_HTTP_REDIRECT_PORT, Config::RWS_CONFIG_HTTP_REDIRECT_PORT_DEFAULT_VALUE);
414        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_HTTP_REDIRECT_PORT, Config::RWS_CONFIG_HTTP_REDIRECT_PORT_DEFAULT_VALUE);
415    } else {
416        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_HTTP_REDIRECT_PORT);
417    }
418
419    let is_var_set = env::var(Config::RWS_CONFIG_LOG_FORMAT).is_ok();
420    if !is_var_set {
421        env::set_var(Config::RWS_CONFIG_LOG_FORMAT, Config::RWS_CONFIG_LOG_FORMAT_DEFAULT_VALUE);
422        startup_note!("    Default value  for '{}' is '{}'", Config::RWS_CONFIG_LOG_FORMAT, Config::RWS_CONFIG_LOG_FORMAT_DEFAULT_VALUE);
423    } else {
424        startup_note!("    There is an environment variable  for '{}', default value won't be set", Config::RWS_CONFIG_LOG_FORMAT);
425    }
426
427    crate::server_config::invalidate();
428    startup_note!("  End of initializing default values\n");
429}
430
431
432pub fn get_ip_port_thread_count() -> (String, i32, i32) {
433    let mut ip : String = Config::RWS_CONFIG_IP_DEFAULT_VALUE.to_string();
434    let mut port: i32 = *Config::RWS_DEFAULT_PORT;
435    let mut thread_count: i32 = *Config::RWS_DEFAULT_THREAD_COUNT;
436
437    let boxed_ip = env::var(Config::RWS_CONFIG_IP);
438    if boxed_ip.is_ok() {
439        ip = boxed_ip.unwrap()
440    }
441
442    let boxed_port = env::var(Config::RWS_CONFIG_PORT);
443    if boxed_port.is_ok() {
444        let _port = boxed_port.unwrap();
445        let boxed_parse = _port.parse::<i32>();
446        if boxed_parse.is_ok() {
447            port = boxed_parse.unwrap();
448        } else {
449            eprintln!("unable to parse port value, expected number, got {}, variable: {}",
450                      _port, Config::RWS_CONFIG_PORT);
451        }
452    } else {
453        eprintln!("unable to parse port value, variable: {}", Config::RWS_CONFIG_PORT);
454    }
455
456    let boxed_thread_count = env::var(Config::RWS_CONFIG_THREAD_COUNT);
457    if boxed_thread_count.is_ok() {
458        let _thread_count = boxed_thread_count.unwrap();
459        let boxed_parse = _thread_count.parse();
460        if boxed_parse.is_ok() {
461            thread_count = boxed_parse.unwrap()
462        } else {
463            eprintln!("unable to parse thread count value, expected number, got {}, variable: {}",
464                      thread_count, Config::RWS_CONFIG_THREAD_COUNT);
465        }
466
467    } else {
468        eprintln!("unable to parse thread count value, variable: {}", Config::RWS_CONFIG_THREAD_COUNT);
469    }
470
471    (ip, port, thread_count)
472}
473
474/// Read all `[[virtual_host]]` entries from config / env vars.
475///
476/// Each entry must have `RWS_CONFIG_VIRTUAL_HOST_{N}_DOMAIN` set; reading
477/// stops at the first missing index.  `cert_file` and `key_file` default to
478/// empty string if omitted.
479pub fn get_virtual_hosts() -> Vec<VirtualHostConfig> {
480    let mut hosts = Vec::new();
481    let mut i = 0usize;
482    loop {
483        match env::var(format!("RWS_CONFIG_VIRTUAL_HOST_{}_DOMAIN", i)) {
484            Err(_) => break,
485            Ok(domain) => {
486                let cert_file = env::var(format!("RWS_CONFIG_VIRTUAL_HOST_{}_CERT_FILE", i))
487                    .unwrap_or_default();
488                let key_file = env::var(format!("RWS_CONFIG_VIRTUAL_HOST_{}_KEY_FILE", i))
489                    .unwrap_or_default();
490                hosts.push(VirtualHostConfig { domain, cert_file, key_file });
491                i += 1;
492            }
493        }
494    }
495    hosts
496}
497
498pub fn get_request_allocation_size() -> i64 {
499    let mut request_allocation_size: i64 = *Config::RWS_DEFAULT_REQUEST_ALLOCATION_SIZE_IN_BYTES;
500
501    let boxed_port = env::var(Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES);
502    if boxed_port.is_ok() {
503        let _request_allocation_size = boxed_port.unwrap();
504        let boxed_parse = _request_allocation_size.parse::<i64>();
505        if boxed_parse.is_ok() {
506            request_allocation_size = boxed_parse.unwrap();
507        } else {
508            eprintln!("unable to parse port value, expected number, got {}, variable: {}",
509                      _request_allocation_size, Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES);
510        }
511    } else {
512        eprintln!("unable to parse request allocation size value, variable: {}", Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES);
513    }
514
515
516    request_allocation_size
517}
518
519/// Maximum accepted request body size in bytes. `0` means unlimited (the default —
520/// enforcing a cap is opt-in). Read fresh on every call, so `RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES`
521/// takes effect immediately, the same as [`get_request_allocation_size`].
522pub fn get_max_body_size() -> u64 {
523    env::var(Config::RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES)
524        .ok()
525        .and_then(|v| v.parse::<u64>().ok())
526        .unwrap_or(0)
527}
528
529/// The configured SPA-fallback file (e.g. `"index.html"`), or `None` if
530/// `RWS_CONFIG_SPA_FALLBACK` is unset/empty (the default — disabled). Read
531/// fresh on every call, so it can be toggled via `rws.config.toml` + `SIGHUP`
532/// without a restart, the same as [`get_max_body_size`].
533pub fn get_spa_fallback() -> Option<String> {
534    env::var(Config::RWS_CONFIG_SPA_FALLBACK).ok().filter(|v| !v.is_empty())
535}
536
537/// The per-prefix SPA fallbacks (`RWS_CONFIG_SPA_FALLBACK_ROUTES`) as `(prefix, file)`
538/// pairs, longest prefix first. Malformed entries (no `=`, a prefix not starting with
539/// `/`, an empty file) are skipped; `rws --check` reports them. A trailing `/` on a prefix is
540/// dropped, so `/cloud/` and `/cloud` are the same. Read fresh on every call, like
541/// [`get_spa_fallback`].
542pub fn get_spa_fallback_routes() -> Vec<(String, String)> {
543    let Ok(value) = env::var(Config::RWS_CONFIG_SPA_FALLBACK_ROUTES) else { return vec![] };
544    parse_spa_fallback_routes(&value)
545}
546
547/// Parses `prefix=file,prefix=file` (see [`get_spa_fallback_routes`]).
548#[doc(hidden)]
549pub fn parse_spa_fallback_routes(value: &str) -> Vec<(String, String)> {
550    let mut routes: Vec<(String, String)> = value
551        .split(',')
552        .filter_map(|entry| {
553            let (prefix, file) = entry.split_once('=')?;
554            let prefix = prefix.trim();
555            let file = file.trim();
556            if !prefix.starts_with('/') || file.is_empty() {
557                return None;
558            }
559            let prefix = prefix.trim_end_matches('/');
560            Some((if prefix.is_empty() { "/".to_string() } else { prefix.to_string() }, file.to_string()))
561        })
562        .collect();
563    routes.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
564    routes
565}
566
567/// Path prefixes that never receive the SPA fallback (`RWS_CONFIG_SPA_FALLBACK_EXCLUDE_PREFIXES`,
568/// comma-separated), even when the fallback is configured. Empty (default) excludes nothing.
569pub fn get_spa_fallback_exclude_prefixes() -> Vec<String> {
570    env::var(Config::RWS_CONFIG_SPA_FALLBACK_EXCLUDE_PREFIXES)
571        .ok()
572        .map(|v| v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect())
573        .unwrap_or_default()
574}
575