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 println!("\n Start of Reading Command Line Arguments Section");
9
10 let args = env::args().collect();
11 let params = CommandLineArgument::get_command_line_arg_list();
12 CommandLineArgument::_parse(args, params);
13
14 println!(" End of Reading Command Line Arguments\n");
15}
16
17pub fn informational_flag_output(args: &[String]) -> Option<String> {
23 let flags = args.iter().skip(1);
24 for arg in flags {
25 match arg.as_str() {
26 "--version" | "-V" => {
27 return Some(format!("rws {}\n", env!("CARGO_PKG_VERSION")));
28 }
29 "--help" => return Some(help_text()),
30 _ => {}
31 }
32 }
33 None
34}
35
36fn help_text() -> String {
37 let mut text = format!(
38 "rws {} — HTTP/1.1, HTTP/2 and HTTP/3 web server and reverse proxy\n\n\
39 Usage: rws [OPTIONS]\n\n\
40 Serves the current directory on http://0.0.0.0:7878 by default. Drop an\n\
41 rws.config.toml with [[route]]/[[upstream]] sections in the working\n\
42 directory to run as a config-driven reverse proxy instead.\n\n\
43 Options (each also settable via the environment variable shown):\n",
44 env!("CARGO_PKG_VERSION")
45 );
46 for argument in CommandLineArgument::get_command_line_arg_list() {
47 let flag = if argument.short_form.is_empty() {
48 format!(" --{}=<value>", argument.long_form)
49 } else {
50 format!("-{}, --{}=<value>", argument.short_form, argument.long_form)
51 };
52 let hint = argument._hint.unwrap_or_default();
53 text.push_str(&format!(" {:<44} {}\n {:<44} [env: {}]\n", flag, hint, "", argument.environment_variable));
54 }
55 text.push_str(" --check[=<file>] Validate rws.config.toml (or <file>) and exit:\n");
56 text.push_str(" 0 if it has no errors, 1 otherwise\n");
57 text.push_str(" ctl <command> Drive a running server's admin API\n");
58 text.push_str(" (rws ctl help; also installed as rwsctl)\n");
59 text.push_str(" -V, --version Print version and exit\n");
60 text.push_str(" --help Print this help and exit\n");
61 text.push_str(" --windows-service=<dir> (Windows) Run as a service serving <dir>\n\n");
62 text.push_str("Docs: https://rws8.tech\n");
63 text
64}
65
66pub struct CommandLineArgument {
67 pub short_form: String,
68 pub long_form: String,
69 pub environment_variable: String,
70 pub _hint: Option<String>,
71}
72
73impl CommandLineArgument {
74 pub fn get_command_line_arg_list() -> Vec<CommandLineArgument> {
75 let mut argument_list : Vec<CommandLineArgument> = vec![];
76
77 let argument = CommandLineArgument {
78 short_form: "p".to_string(),
79 long_form: "port".to_string(),
80 environment_variable: Config::RWS_CONFIG_PORT.to_string(),
81 _hint: Some("Port".to_string())
82 };
83 argument_list.push(argument);
84
85 let argument = CommandLineArgument {
86 short_form: "i".to_string(),
87 long_form: "ip".to_string(),
88 environment_variable: Config::RWS_CONFIG_IP.to_string(),
89 _hint: Some("IP or domain".to_string())
90 };
91 argument_list.push(argument);
92
93 let argument = CommandLineArgument {
94 short_form: "t".to_string(),
95 long_form: "thread-count".to_string(),
96 environment_variable: Config::RWS_CONFIG_THREAD_COUNT.to_string(),
97 _hint: Some("Number of threads".to_string())
98 };
99 argument_list.push(argument);
100
101
102 let argument = CommandLineArgument {
103 short_form: "a".to_string(),
104 long_form: "cors-allow-all".to_string(),
105 environment_variable: Config::RWS_CONFIG_CORS_ALLOW_ALL.to_string(),
106 _hint: Some("If set to true, will allow all CORS requests, other CORS properties will be ignored".to_string())
107 };
108 argument_list.push(argument);
109
110 let argument = CommandLineArgument {
111 short_form: "o".to_string(),
112 long_form: "cors-allow-origins".to_string(),
113 environment_variable: Config::RWS_CONFIG_CORS_ALLOW_ORIGINS.to_string(),
114 _hint: Some("Comma separated list of allowed origins, example: https://foo.example,https://bar.example".to_string())
115 };
116 argument_list.push(argument);
117
118 let argument = CommandLineArgument {
119 short_form: "m".to_string(),
120 long_form: "cors-allow-methods".to_string(),
121 environment_variable: Config::RWS_CONFIG_CORS_ALLOW_METHODS.to_string(),
122 _hint: Some("Comma separated list of allowed methods, example: POST,PUT".to_string())
123 };
124 argument_list.push(argument);
125
126 let argument = CommandLineArgument {
127 short_form: "h".to_string(),
128 long_form: "cors-allow-headers".to_string(),
129 environment_variable: Config::RWS_CONFIG_CORS_ALLOW_HEADERS.to_string(),
130 _hint: Some("Comma separated list of allowed request headers, in lowercase, example: content-type,x-custom-header".to_string())
131 };
132 argument_list.push(argument);
133
134 let argument = CommandLineArgument {
135 short_form: "c".to_string(),
136 long_form: "cors-allow-credentials".to_string(),
137 environment_variable: Config::RWS_CONFIG_CORS_ALLOW_CREDENTIALS.to_string(),
138 _hint: Some("If set to true, will allow to transmit credentials via CORS requests".to_string())
139 };
140 argument_list.push(argument);
141
142 let argument = CommandLineArgument {
143 short_form: "e".to_string(),
144 long_form: "cors-expose-headers".to_string(),
145 environment_variable: Config::RWS_CONFIG_CORS_EXPOSE_HEADERS.to_string(),
146 _hint: Some("Comma separated list of allowed response headers, in lowercase, example: content-type,x-custom-header".to_string())
147 };
148 argument_list.push(argument);
149
150 let argument = CommandLineArgument {
151 short_form: "g".to_string(),
152 long_form: "cors-max-age".to_string(),
153 environment_variable: Config::RWS_CONFIG_CORS_MAX_AGE.to_string(),
154 _hint: Some("How long results of preflight requests can be cached (in seconds)".to_string())
155 };
156 argument_list.push(argument);
157
158 let argument = CommandLineArgument {
159 short_form: "r".to_string(),
160 long_form: "request-allocation-size-in-bytes".to_string(),
161 environment_variable: Config::RWS_CONFIG_REQUEST_ALLOCATION_SIZE_IN_BYTES.to_string(),
162 _hint: Some("In bytes, how much memory to allocate for each request".to_string())
163 };
164 argument_list.push(argument);
165
166 let argument = CommandLineArgument {
167 short_form: "s".to_string(),
168 long_form: "tls-cert-file".to_string(),
169 environment_variable: Config::RWS_CONFIG_TLS_CERT_FILE.to_string(),
170 _hint: Some("Path to TLS certificate PEM file (enables HTTPS and HTTP/2)".to_string())
171 };
172 argument_list.push(argument);
173
174 let argument = CommandLineArgument {
175 short_form: "k".to_string(),
176 long_form: "tls-key-file".to_string(),
177 environment_variable: Config::RWS_CONFIG_TLS_KEY_FILE.to_string(),
178 _hint: Some("Path to TLS private key PEM file (enables HTTPS and HTTP/2)".to_string())
179 };
180 argument_list.push(argument);
181
182 let long_only = [
187 ("http-redirect-port", Config::RWS_CONFIG_HTTP_REDIRECT_PORT,
188 "Plain-HTTP port that 301-redirects to HTTPS (and answers ACME HTTP-01 challenges), e.g. 80"),
189 ("acme-domains", Config::RWS_CONFIG_ACME_DOMAINS,
190 "Comma separated domains to get a Let's Encrypt certificate for; enables automatic HTTPS"),
191 ("acme-email", Config::RWS_CONFIG_ACME_EMAIL,
192 "Contact email for the ACME account"),
193 ("acme-staging", Config::RWS_CONFIG_ACME_STAGING,
194 "If set to true, uses the Let's Encrypt staging environment (untrusted test certificates)"),
195 ("acme-directory", Config::RWS_CONFIG_ACME_DIRECTORY,
196 "ACME directory URL of a CA other than Let's Encrypt"),
197 ("acme-ca-file", Config::RWS_CONFIG_ACME_CA_FILE,
198 "PEM file of extra root CAs to trust for the ACME directory (private ACME CAs)"),
199 ("acme-challenge-port", Config::RWS_CONFIG_ACME_CHALLENGE_PORT,
200 "Port the CA connects to for HTTP-01 challenges (default 80)"),
201 ("acme-cert-path", Config::RWS_CONFIG_ACME_CERT_PATH,
202 "Where to store the issued certificate (default: tls-cert-file, else .rws/acme/cert.pem)"),
203 ("acme-key-path", Config::RWS_CONFIG_ACME_KEY_PATH,
204 "Where to store the certificate's private key (default: tls-key-file, else .rws/acme/key.pem)"),
205 ("acme-profile", Config::RWS_CONFIG_ACME_PROFILE,
206 "Certificate profile to order, as the CA offers them (e.g. classic, tlsserver, shortlived)"),
207 ("acme-challenge", Config::RWS_CONFIG_ACME_CHALLENGE,
208 "How to prove control of the domains: http-01 (default), tls-alpn-01, dns-01 (wildcards) or dns-persist-01"),
209 ("acme-dns-provider", Config::RWS_CONFIG_ACME_DNS_PROVIDER,
210 "DNS-01: rfc2136 (DNS UPDATE), cloudflare, route53 or exec (a program)"),
211 ("acme-dns-server", Config::RWS_CONFIG_ACME_DNS_SERVER,
212 "DNS-01 rfc2136: the primary DNS server, host[:port]"),
213 ("acme-dns-zone", Config::RWS_CONFIG_ACME_DNS_ZONE,
214 "DNS-01: the zone of the records (found by SOA lookup when not set)"),
215 ("acme-dns-tsig-key", Config::RWS_CONFIG_ACME_DNS_TSIG_KEY,
216 "DNS-01 rfc2136: TSIG key name (the secret goes in RWS_CONFIG_ACME_DNS_TSIG_SECRET)"),
217 ("acme-dns-tsig-algorithm", Config::RWS_CONFIG_ACME_DNS_TSIG_ALGORITHM,
218 "DNS-01 rfc2136: hmac-sha256 (default) or hmac-sha512"),
219 ("acme-dns-exec", Config::RWS_CONFIG_ACME_DNS_EXEC,
220 "DNS-01 exec: program run as <program> present|cleanup <fqdn> <value>"),
221 ("acme-dns-propagation-secs", Config::RWS_CONFIG_ACME_DNS_PROPAGATION_SECS,
222 "DNS-01: seconds to wait for the record to be visible (default 120)"),
223 ("acme-dns-api-url", Config::RWS_CONFIG_ACME_DNS_API_URL,
224 "DNS-01 cloudflare/route53: API base URL instead of the provider's (the token goes in RWS_CONFIG_ACME_DNS_API_TOKEN)"),
225 ("acme-dns-zone-id", Config::RWS_CONFIG_ACME_DNS_ZONE_ID,
226 "DNS-01 cloudflare/route53: the zone's id, instead of looking it up"),
227 ("acme-redis", Config::RWS_CONFIG_ACME_REDIS,
228 "Redis host:port shared by replicas: one orders each certificate, all install it"),
229 ("acme-redis-prefix", Config::RWS_CONFIG_ACME_REDIS_PREFIX,
230 "Key prefix in that Redis (default rws:acme)"),
231 ("acme-on-demand", Config::RWS_CONFIG_ACME_ON_DEMAND,
232 "true: order a certificate at the first handshake for a name the ask endpoint allows"),
233 ("acme-on-demand-ask", Config::RWS_CONFIG_ACME_ON_DEMAND_ASK,
234 "On-demand TLS: URL asked ?domain=<name> before each order; 2xx allows it"),
235 ];
236 for (long_form, environment_variable, hint) in long_only {
237 argument_list.push(CommandLineArgument {
238 short_form: "".to_string(),
239 long_form: long_form.to_string(),
240 environment_variable: environment_variable.to_string(),
241 _hint: Some(hint.to_string()),
242 });
243 }
244
245 argument_list
246 }
247
248 pub fn _parse(args: Vec<String>, argument_list : Vec<CommandLineArgument>) -> Vec<CommandLineArgument> {
249 for unparsed_argument in args.iter() {
250
251 let boxed_split = unparsed_argument.split_once('=');
252 if boxed_split.is_some() {
253
254 let (parameter, value) = boxed_split.unwrap();
255 println!("\n {}={}", parameter, crate::entry_point::shown(parameter, value));
256 let boxed_predefined_argument =
257 argument_list
258 .iter()
259 .find(
260 |predefined_argument| {
261 let short_form = predefined_argument.short_form.to_string();
262 let long_form = predefined_argument.long_form.to_string();
263 let _param_short_form = ["-", &short_form].join("");
264 let _param_long_form = ["--", &long_form].join("");
265
266 (!short_form.is_empty() && parameter.eq(_param_short_form.as_str())) ||
267 parameter.eq(_param_long_form.as_str())
268 });
269 if boxed_predefined_argument.is_some() {
270 let predefined_argument = boxed_predefined_argument.unwrap();
271 CommandLineArgument::set_environment_variable(predefined_argument, value.to_string());
272 }
273
274 }
275 }
276 argument_list
277 }
278
279 pub fn set_environment_variable(argument: &CommandLineArgument, value: String) {
280 if value.contains('\0') {
281 eprintln!(" Warning: value for --{} contains a NUL byte — ignored", argument.long_form);
283 return;
284 }
285 env::set_var(&argument.environment_variable, &value);
286 crate::server_config::invalidate();
287 println!(" Set env variable '{}' to value '{}'", argument.environment_variable, crate::entry_point::shown(&argument.environment_variable, &value));
288 }
289}