Skip to main content

rws_http/entry_point/command_line_args/
mod.rs

1use std::env;
2use crate::entry_point::Config;
3
4#[cfg(test)]
5mod tests;
6
7pub fn override_environment_variables_from_command_line_args() {
8    crate::entry_point::note("\n  Start of Reading Command Line Arguments Section");
9
10    let args = joined_value_forms(&env::args().collect::<Vec<_>>());
11    let params = CommandLineArgument::get_command_line_arg_list();
12    CommandLineArgument::_parse(args, params);
13
14    crate::entry_point::note("  End of Reading Command Line Arguments\n");
15}
16
17/// `-p 8080` / `--port 8080` written as `-p=8080` / `--port=8080`, for every
18/// flag in [`CommandLineArgument::get_command_line_arg_list`] (since
19/// 18.37.0). A flag is joined with the next argument only when that one
20/// doesn't start with `-`. `-h` stays as it is: alone it asks for help.
21pub fn joined_value_forms(args: &[String]) -> Vec<String> {
22    let flags = CommandLineArgument::get_command_line_arg_list();
23    let mut out = Vec::with_capacity(args.len());
24    let mut iter = args.iter().peekable();
25    if let Some(program) = iter.next() {
26        out.push(program.clone());
27    }
28    while let Some(arg) = iter.next() {
29        let flag = flags.iter().find(|f| {
30            (!f.short_form.is_empty() && f.short_form != "h" && *arg == format!("-{}", f.short_form))
31                || *arg == format!("--{}", f.long_form)
32        });
33        match (flag, iter.peek()) {
34            (Some(flag), Some(next)) if !next.starts_with('-') => {
35                out.push(format!("--{}={}", flag.long_form, next));
36                iter.next();
37            }
38            _ => out.push(arg.clone()),
39        }
40    }
41    out
42}
43
44/// Arguments the `rws` binary takes besides the settings flags.
45const BINARY_ARGS: &[&str] = &["--check", "--format=json", "--verbose", "--version", "-V", "--help", "-h", "help", "--manifests"];
46const BINARY_ARG_PREFIXES: &[&str] = &["--check=", "--windows-service=", "--format="];
47
48/// Check the `rws` binary's arguments (program name first) before it starts
49/// a server: every argument must be a settings flag with a value
50/// (`--port=8080`, `-p 8080`) or one of the binary's own (`--check`,
51/// `--verbose`, …). `Err` is the message to print, for exit code 2. Only the
52/// binary calls this: an application built on the library may take
53/// arguments of its own.
54pub fn check_binary_args(args: &[String]) -> Result<(), String> {
55    let flags = CommandLineArgument::get_command_line_arg_list();
56    let joined = joined_value_forms(args);
57    let mut iter = joined.iter().skip(1).peekable();
58    while let Some(arg) = iter.next() {
59        if BINARY_ARGS.contains(&arg.as_str()) || BINARY_ARG_PREFIXES.iter().any(|p| arg.starts_with(p)) {
60            // `--check <file>`: the file is its value.
61            if arg == "--check" && iter.peek().is_some_and(|n| !n.starts_with('-')) {
62                iter.next();
63            }
64            continue;
65        }
66        let (name, has_value) = match arg.split_once('=') {
67            Some((name, _)) => (name, true),
68            None => (arg.as_str(), false),
69        };
70        let flag = flags.iter().find(|f| {
71            (!f.short_form.is_empty() && name == format!("-{}", f.short_form)) || name == format!("--{}", f.long_form)
72        });
73        match flag {
74            Some(_) if has_value => {}
75            Some(flag) => {
76                return Err(format!("rws: {arg} needs a value: --{}=<value>\nrws --help lists every option.", flag.long_form));
77            }
78            None => {
79                let hint = closest_flag(name, &flags).map(|f| format!(" Did you mean --{f}?")).unwrap_or_default();
80                return Err(format!("rws: unknown argument '{arg}'.{hint}\nrws --help lists every option."));
81            }
82        }
83    }
84    Ok(())
85}
86
87/// The flag closest to `name` (edit distance at most 2, or a prefix of one).
88fn closest_flag(name: &str, flags: &[CommandLineArgument]) -> Option<String> {
89    let bare = name.trim_start_matches('-');
90    if bare.len() < 2 {
91        return None;
92    }
93    let mut best: Option<(usize, &str)> = None;
94    for f in flags {
95        let long = f.long_form.as_str();
96        let d = if long.starts_with(bare) { 1 } else { crate::entry_point::edit_distance(bare, long) };
97        if d <= 2 && best.is_none_or(|(b, _)| d < b) {
98            best = Some((d, long));
99        }
100    }
101    best.map(|(_, f)| f.to_string())
102}
103
104/// Returns the text to print for an informational flag — `--version` / `-V`
105/// or `--help` / `-h` / `help` — if `args` (as from `env::args()`, program
106/// name first) contains one, so the binary can print it and exit before
107/// starting a server. `None` means start normally. `-h` alone is help since
108/// 18.37.0; `-h=<list>` is still `--cors-allow-headers`.
109pub fn informational_flag_output(args: &[String]) -> Option<String> {
110    let flags = args.iter().skip(1);
111    for arg in flags {
112        match arg.as_str() {
113            "--version" | "-V" => {
114                // A FIPS build says so (18.23.0); others print just the version.
115                return Some(format!("rws {}{}\n", env!("CARGO_PKG_VERSION"), if cfg!(feature = "fips") { " (FIPS)" } else { "" }));
116            }
117            "--help" | "-h" => return Some(help_text()),
118            _ => {}
119        }
120    }
121    if args.get(1).map(String::as_str) == Some("help") && args.len() == 2 {
122        return Some(help_text());
123    }
124    None
125}
126
127fn help_text() -> String {
128    let mut text = format!(
129        "rws {} — web server, reverse proxy and automatic HTTPS\n\n\
130         Usage:\n\
131         \x20 rws [OPTIONS]                 Serve the working directory (http://localhost:7878)\n\
132         \x20 rws --check[=<file>]          Validate rws.config.toml (or <file>); exit 0 if it has no errors\n\
133         \x20 rws ctl <command>             Drive a running server's admin API (rws ctl help; also rwsctl)\n\
134         \x20 rws gen model|route|migration|test <name>\n\
135         \x20                               Generate code into the project (rws gen --help)\n\
136         \x20 rws db <command>              Run the project's migrations and seeds (rws db --help)\n\
137         \x20 rws trust [--print]           Trust rws's local CA (tls = \"internal\"); --print shows it\n\
138         \x20 rws untrust                   Take the local CA out of the trust store\n\n\
139         An rws.config.toml with [[route]]/[[upstream]] sections in the working\n\
140         directory runs rws as a config-driven reverse proxy instead.\n\n\
141         Each option is also an environment variable (shown) and a key in rws.config.toml.\n\
142         Values: --port=8080 or --port 8080.\n",
143        env!("CARGO_PKG_VERSION")
144    );
145    let list = CommandLineArgument::get_command_line_arg_list();
146    let common = ["port", "ip", "thread-count", "tls", "tls-cert-file", "tls-key-file"];
147    type Wanted = Box<dyn Fn(&str) -> bool>;
148    let groups: [(&str, Wanted); 4] = [
149        ("Common options", Box::new(move |l: &str| common.contains(&l))),
150        ("Automatic HTTPS (ACME)", Box::new(|l: &str| l.starts_with("acme-") || l == "http-redirect-port")),
151        ("CORS", Box::new(|l: &str| l.starts_with("cors-"))),
152        ("Other", Box::new(move |l: &str| !common.contains(&l) && !l.starts_with("acme-") && l != "http-redirect-port" && !l.starts_with("cors-"))),
153    ];
154    for (title, wanted) in groups.iter() {
155        let mut section = String::new();
156        let mut items: Vec<&CommandLineArgument> = list.iter().filter(|a| wanted(&a.long_form)).collect();
157        if *title == "Common options" {
158            items.sort_by_key(|a| common.iter().position(|c| *c == a.long_form));
159        }
160        for argument in items {
161            let flag = if argument.short_form.is_empty() {
162                format!("    --{}=<value>", argument.long_form)
163            } else {
164                format!("-{}, --{}=<value>", argument.short_form, argument.long_form)
165            };
166            let hint = argument._hint.clone().unwrap_or_default();
167            section.push_str(&format!("  {:<44} {}\n  {:<44} [env: {}]\n", flag, hint, "", argument.environment_variable));
168        }
169        if !section.is_empty() {
170            text.push_str(&format!("\n{title}:\n{section}"));
171        }
172    }
173    text.push_str("\nGeneral:\n");
174    text.push_str("      --verbose                                Print every setting and step at startup\n");
175    text.push_str("  -V, --version                                Print version and exit\n");
176    text.push_str("  -h, --help                                   Print this help and exit\n");
177    text.push_str("      --windows-service=<dir>                  (Windows) Run as a service serving <dir>\n\n");
178    text.push_str("Docs: https://rws8.tech/docs/ · every setting: https://rws8.tech/docs/configuration/env-vars/\n");
179    text
180}
181
182pub struct CommandLineArgument {
183    pub short_form: String,
184    pub long_form: String,
185    pub environment_variable: String,
186    pub _hint: Option<String>,
187}
188
189impl CommandLineArgument {
190    pub fn get_command_line_arg_list() -> Vec<CommandLineArgument> {
191        let mut argument_list : Vec<CommandLineArgument> = vec![];
192
193        let argument = CommandLineArgument {
194            short_form: "p".to_string(),
195            long_form: "port".to_string(),
196            environment_variable: Config::RWS_CONFIG_PORT.to_string(),
197            _hint: Some("Port".to_string())
198        };
199        argument_list.push(argument);
200
201        let argument = CommandLineArgument {
202            short_form: "i".to_string(),
203            long_form: "ip".to_string(),
204            environment_variable: Config::RWS_CONFIG_IP.to_string(),
205            _hint: Some("IP or domain".to_string())
206        };
207        argument_list.push(argument);
208
209        let argument = CommandLineArgument {
210            short_form: "t".to_string(),
211            long_form: "thread-count".to_string(),
212            environment_variable: Config::RWS_CONFIG_THREAD_COUNT.to_string(),
213            _hint: Some("Number of threads".to_string())
214        };
215        argument_list.push(argument);
216
217
218        let argument = CommandLineArgument {
219            short_form: "a".to_string(),
220            long_form: "cors-allow-all".to_string(),
221            environment_variable: Config::RWS_CONFIG_CORS_ALLOW_ALL.to_string(),
222            _hint: Some("If set to true, will allow all CORS requests, other CORS properties will be ignored".to_string())
223        };
224        argument_list.push(argument);
225
226        let argument = CommandLineArgument {
227            short_form: "o".to_string(),
228            long_form: "cors-allow-origins".to_string(),
229            environment_variable: Config::RWS_CONFIG_CORS_ALLOW_ORIGINS.to_string(),
230            _hint: Some("Comma separated list of allowed origins, example: https://foo.example,https://bar.example".to_string())
231        };
232        argument_list.push(argument);
233
234        let argument = CommandLineArgument {
235            short_form: "m".to_string(),
236            long_form: "cors-allow-methods".to_string(),
237            environment_variable: Config::RWS_CONFIG_CORS_ALLOW_METHODS.to_string(),
238            _hint: Some("Comma separated list of allowed methods, example: POST,PUT".to_string())
239        };
240        argument_list.push(argument);
241
242        let argument = CommandLineArgument {
243            short_form: "h".to_string(),
244            long_form: "cors-allow-headers".to_string(),
245            environment_variable: Config::RWS_CONFIG_CORS_ALLOW_HEADERS.to_string(),
246            _hint: Some("Comma separated list of allowed request headers, in lowercase, example: content-type,x-custom-header".to_string())
247        };
248        argument_list.push(argument);
249
250        let argument = CommandLineArgument {
251            short_form: "c".to_string(),
252            long_form: "cors-allow-credentials".to_string(),
253            environment_variable: Config::RWS_CONFIG_CORS_ALLOW_CREDENTIALS.to_string(),
254            _hint: Some("If set to true, will allow to transmit credentials via CORS requests".to_string())
255        };
256        argument_list.push(argument);
257
258        let argument = CommandLineArgument {
259            short_form: "e".to_string(),
260            long_form: "cors-expose-headers".to_string(),
261            environment_variable: Config::RWS_CONFIG_CORS_EXPOSE_HEADERS.to_string(),
262            _hint: Some("Comma separated list of allowed response headers, in lowercase, example: content-type,x-custom-header".to_string())
263        };
264        argument_list.push(argument);
265
266        let argument = CommandLineArgument {
267            short_form: "g".to_string(),
268            long_form: "cors-max-age".to_string(),
269            environment_variable: Config::RWS_CONFIG_CORS_MAX_AGE.to_string(),
270            _hint: Some("How long results of preflight requests can be cached (in seconds)".to_string())
271        };
272        argument_list.push(argument);
273
274        let argument = CommandLineArgument {
275            short_form: "r".to_string(),
276            long_form: "request-allocation-size-in-bytes".to_string(),
277            environment_variable: Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES.to_string(),
278            _hint: Some("In bytes, how much memory to allocate for each request".to_string())
279        };
280        argument_list.push(argument);
281
282        let argument = CommandLineArgument {
283            short_form: "s".to_string(),
284            long_form: "tls-cert-file".to_string(),
285            environment_variable: Config::RWS_CONFIG_TLS_CERT_FILE.to_string(),
286            _hint: Some("Path to TLS certificate PEM file (enables HTTPS and HTTP/2)".to_string())
287        };
288        argument_list.push(argument);
289
290        let argument = CommandLineArgument {
291            short_form: "k".to_string(),
292            long_form: "tls-key-file".to_string(),
293            environment_variable: Config::RWS_CONFIG_TLS_KEY_FILE.to_string(),
294            _hint: Some("Path to TLS private key PEM file (enables HTTPS and HTTP/2)".to_string())
295        };
296        argument_list.push(argument);
297
298        // Long-form only (empty short_form): every single letter that reads
299        // naturally is taken. In rws.config.toml these are `http_redirect_port`
300        // at the top level and the keys of an `[acme]` section (`domains`,
301        // `email`, ...), which the config-file reader prefixes to `acme-*`.
302        let long_only = [
303            ("http-redirect-port", Config::RWS_CONFIG_HTTP_REDIRECT_PORT,
304                "Plain-HTTP port that 301-redirects to HTTPS (and answers ACME HTTP-01 challenges), e.g. 80"),
305            ("acme-domains", Config::RWS_CONFIG_ACME_DOMAINS,
306                "Comma separated domains to get a Let's Encrypt certificate for; enables automatic HTTPS"),
307            ("acme-email", Config::RWS_CONFIG_ACME_EMAIL,
308                "Contact email for the ACME account"),
309            ("acme-staging", Config::RWS_CONFIG_ACME_STAGING,
310                "If set to true, uses the Let's Encrypt staging environment (untrusted test certificates)"),
311            ("acme-directory", Config::RWS_CONFIG_ACME_DIRECTORY,
312                "ACME directory URL of a CA other than Let's Encrypt"),
313            ("acme-ca-file", Config::RWS_CONFIG_ACME_CA_FILE,
314                "PEM file of extra root CAs to trust for the ACME directory (private ACME CAs)"),
315            ("acme-challenge-port", Config::RWS_CONFIG_ACME_CHALLENGE_PORT,
316                "Port the CA connects to for HTTP-01 challenges (default 80)"),
317            ("acme-cert-path", Config::RWS_CONFIG_ACME_CERT_PATH,
318                "Where to store the issued certificate (default: tls-cert-file, else .rws/acme/cert.pem)"),
319            ("acme-key-path", Config::RWS_CONFIG_ACME_KEY_PATH,
320                "Where to store the certificate's private key (default: tls-key-file, else .rws/acme/key.pem)"),
321            ("acme-profile", Config::RWS_CONFIG_ACME_PROFILE,
322                "Certificate profile to order, as the CA offers them (e.g. classic, tlsserver, shortlived)"),
323            ("acme-challenge", Config::RWS_CONFIG_ACME_CHALLENGE,
324                "How to prove control of the domains: http-01 (default), tls-alpn-01, dns-01 (wildcards) or dns-persist-01"),
325            ("acme-dns-provider", Config::RWS_CONFIG_ACME_DNS_PROVIDER,
326                "DNS-01: rfc2136 (DNS UPDATE), cloudflare, route53 or exec (a program)"),
327            ("acme-dns-server", Config::RWS_CONFIG_ACME_DNS_SERVER,
328                "DNS-01 rfc2136: the primary DNS server, host[:port]"),
329            ("acme-dns-zone", Config::RWS_CONFIG_ACME_DNS_ZONE,
330                "DNS-01: the zone of the records (found by SOA lookup when not set)"),
331            ("acme-dns-tsig-key", Config::RWS_CONFIG_ACME_DNS_TSIG_KEY,
332                "DNS-01 rfc2136: TSIG key name (the secret goes in RWS_CONFIG_ACME_DNS_TSIG_SECRET)"),
333            ("acme-dns-tsig-algorithm", Config::RWS_CONFIG_ACME_DNS_TSIG_ALGORITHM,
334                "DNS-01 rfc2136: hmac-sha256 (default) or hmac-sha512"),
335            ("acme-dns-exec", Config::RWS_CONFIG_ACME_DNS_EXEC,
336                "DNS-01 exec: program run as <program> present|cleanup <fqdn> <value>"),
337            ("acme-dns-propagation-secs", Config::RWS_CONFIG_ACME_DNS_PROPAGATION_SECS,
338                "DNS-01: seconds to wait for the record to be visible (default 120)"),
339            ("acme-dns-api-url", Config::RWS_CONFIG_ACME_DNS_API_URL,
340                "DNS-01 cloudflare/route53: API base URL instead of the provider's (the token goes in RWS_CONFIG_ACME_DNS_API_TOKEN)"),
341            ("acme-dns-zone-id", Config::RWS_CONFIG_ACME_DNS_ZONE_ID,
342                "DNS-01 cloudflare/route53: the zone's id, instead of looking it up"),
343            ("acme-redis", Config::RWS_CONFIG_ACME_REDIS,
344                "Redis host:port shared by replicas: one orders each certificate, all install it"),
345            ("acme-redis-prefix", Config::RWS_CONFIG_ACME_REDIS_PREFIX,
346                "Key prefix in that Redis (default rws:acme)"),
347            ("acme-on-demand", Config::RWS_CONFIG_ACME_ON_DEMAND,
348                "true: order a certificate at the first handshake for a name the ask endpoint allows"),
349            ("acme-on-demand-ask", Config::RWS_CONFIG_ACME_ON_DEMAND_ASK,
350                "On-demand TLS: URL asked ?domain=<name> before each order; 2xx allows it"),
351        ];
352        for (long_form, environment_variable, hint) in long_only {
353            argument_list.push(CommandLineArgument {
354                short_form: "".to_string(),
355                long_form: long_form.to_string(),
356                environment_variable: environment_variable.to_string(),
357                _hint: Some(hint.to_string()),
358            });
359        }
360
361        let argument = CommandLineArgument {
362            short_form: "".to_string(),
363            long_form: "tls".to_string(),
364            environment_variable: "RWS_CONFIG_TLS".to_string(),
365            _hint: Some("internal: HTTPS from rws's own CA (local development; see rws trust)".to_string())
366        };
367        argument_list.push(argument);
368
369        argument_list
370    }
371
372    pub fn _parse(args: Vec<String>, argument_list : Vec<CommandLineArgument>) -> Vec<CommandLineArgument> {
373        for unparsed_argument in args.iter() {
374
375            let boxed_split = unparsed_argument.split_once('=');
376            if boxed_split.is_some() {
377
378                let (parameter, value) = boxed_split.unwrap();
379                crate::entry_point::note(&format!("\n    {}={}", parameter, crate::entry_point::shown(parameter, value)));
380                let boxed_predefined_argument =
381                    argument_list
382                        .iter()
383                        .find(
384                            |predefined_argument| {
385                                let short_form = predefined_argument.short_form.to_string();
386                                let long_form = predefined_argument.long_form.to_string();
387                                let _param_short_form = ["-", &short_form].join("");
388                                let _param_long_form = ["--", &long_form].join("");
389
390                                (!short_form.is_empty() && parameter.eq(_param_short_form.as_str())) ||
391                                    parameter.eq(_param_long_form.as_str())
392                });
393                if boxed_predefined_argument.is_some() {
394                    let predefined_argument = boxed_predefined_argument.unwrap();
395                    CommandLineArgument::set_environment_variable(predefined_argument, value.to_string());
396                }
397
398            }
399        }
400        argument_list
401    }
402
403    pub fn set_environment_variable(argument: &CommandLineArgument, value: String) {
404        if value.contains('\0') {
405            // env::set_var panics on NUL; reachable from rws.config.toml values.
406            eprintln!("    Warning: value for --{} contains a NUL byte — ignored", argument.long_form);
407            return;
408        }
409        env::set_var(&argument.environment_variable, &value);
410        crate::server_config::invalidate();
411        crate::entry_point::note(&format!("    Set env variable '{}' to value '{}'", argument.environment_variable, crate::entry_point::shown(&argument.environment_variable, &value)));
412    }
413}