Skip to main content

rust_web_server/ctl/
mod.rs

1//! `rws ctl` (18.20.0, #70): the admin API from the command line.
2//!
3//! ```text
4//! rws ctl status                         # version, uptime, listeners, disks
5//! rws ctl reload                         # waits; prints the errors and exits 1 on a bad config
6//! rws ctl drain <upstream> <backend> [--undo]
7//! rws ctl maintenance [on|off]
8//! rws ctl block <ip> | unblock <ip> | blocklist
9//! rws ctl purge <cache> [--path /p | --prefix /p/]
10//! rws ctl caches | upstreams
11//! rws ctl certs [renew]
12//! rws ctl logs [-n 100] [-f]
13//! rws ctl traffic [--week | --month | --hours N] [--host example.com]
14//! ```
15//!
16//! The binary run as `rwsctl` (the packages install that symlink) acts as
17//! `rws ctl`. Where it connects: `--admin http://127.0.0.1:9901`, else
18//! `[admin] listen` of `RWS_CONFIG_FILE` / `rws.config.toml`, else
19//! `127.0.0.1:9901`. The token: `--token-file`, else the variable
20//! `[admin] token_env` names, else `RWS_ADMIN_TOKEN` — never an argument, so
21//! it can't show in `ps`. Output is for people; `--json` prints the API's
22//! JSON. Exit codes: 0 done, 1 refused or failed, 2 usage error, admin API
23//! unreachable or token refused.
24
25use std::io::{BufRead, BufReader, Read, Write};
26use std::net::TcpStream;
27use std::time::Duration;
28
29use crate::admin::{API_PREFIX, DEFAULT_TOKEN_ENV};
30use crate::entry_point::Config;
31use crate::mcp::json_rpc;
32
33/// Done.
34pub const EXIT_OK: i32 = 0;
35/// The server refused or the operation failed.
36pub const EXIT_FAILED: i32 = 1;
37/// Bad arguments, the admin API unreachable, or the token refused.
38pub const EXIT_UNUSABLE: i32 = 2;
39
40const DEFAULT_ADMIN: &str = "127.0.0.1:9901";
41
42const USAGE: &str = "\
43Usage: rws ctl [--admin <url>] [--token-file <path>] [--json] <command>
44
45Commands:
46  status                               version, uptime, listeners, disks
47  reload                               reload the configuration and wait for it
48  drain <upstream> <backend> [--undo]  stop sending new requests to a backend
49  maintenance [on|off]                 show or switch maintenance mode
50  block <ip> | unblock <ip>            change the IP blocklist
51  blocklist                            list blocked IPs
52  purge <cache> [--path P | --prefix P]  purge a cache (all of it by default)
53  caches | upstreams                   list caches / upstream backends
54  certs [renew]                        certificates and ACME state; renew orders now
55  logs [-n N] [-f]                     recent access-log lines; -f follows
56  traffic [--week|--month|--hours N] [--host H]  who visited
57
58The admin address comes from --admin, else [admin] listen in RWS_CONFIG_FILE or
59rws.config.toml, else 127.0.0.1:9901. The token from --token-file, else the
60variable [admin] token_env names, else RWS_ADMIN_TOKEN.
61Exit codes: 0 done, 1 refused or failed, 2 usage, unreachable or unauthorized.
62";
63
64/// What went wrong, and the exit code it means.
65#[derive(Debug)]
66struct Failure {
67    code: i32,
68    message: String,
69}
70
71fn usage(message: impl Into<String>) -> Failure {
72    Failure { code: EXIT_UNUSABLE, message: format!("{}\n\n{USAGE}", message.into()) }
73}
74
75fn failed(message: impl Into<String>) -> Failure {
76    Failure { code: EXIT_FAILED, message: message.into() }
77}
78
79fn unusable(message: impl Into<String>) -> Failure {
80    Failure { code: EXIT_UNUSABLE, message: message.into() }
81}
82
83/// Whether the program was started as `rwsctl` (its file name, any extension).
84pub fn invoked_as_rwsctl(argv0: &str) -> bool {
85    let name = argv0.rsplit(['/', '\\']).next().unwrap_or(argv0);
86    name == "rwsctl" || name.strip_suffix(".exe").is_some_and(|n| n.eq_ignore_ascii_case("rwsctl"))
87}
88
89/// The `rws ctl` arguments in `args` (a full `argv`): after `ctl`, or all
90/// of them when run as `rwsctl`. `None` for a normal server start.
91pub fn requested(args: &[String]) -> Option<&[String]> {
92    if args.first().is_some_and(|a| invoked_as_rwsctl(a)) {
93        return Some(&args[1..]);
94    }
95    (args.get(1).map(String::as_str) == Some("ctl")).then(|| &args[2..])
96}
97
98/// Run `rws ctl <args>`, writing to `out` and `err`; returns the exit code.
99pub fn run(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
100    match parse(args).and_then(|cmd| execute(&cmd, out)) {
101        Ok(()) => EXIT_OK,
102        Err(f) => {
103            let _ = writeln!(err, "{}", f.message.trim_end());
104            f.code
105        }
106    }
107}
108
109/// Parsed command line.
110#[derive(Debug, Default)]
111struct Command {
112    admin: Option<String>,
113    token_file: Option<String>,
114    json: bool,
115    words: Vec<String>,
116    undo: bool,
117    follow: bool,
118    lines: Option<usize>,
119    path: Option<String>,
120    prefix: Option<String>,
121    hours: Option<u64>,
122    host: Option<String>,
123}
124
125fn parse(args: &[String]) -> Result<Command, Failure> {
126    let mut cmd = Command::default();
127    let mut args = args.iter();
128    while let Some(arg) = args.next() {
129        let (flag, inline) = match arg.split_once('=') {
130            Some((f, v)) if f.starts_with("--") => (f, Some(v.to_string())),
131            _ => (arg.as_str(), None),
132        };
133        let mut value = |name: &str| inline.clone().or_else(|| args.next().cloned()).ok_or_else(|| usage(format!("{name} needs a value")));
134        match flag {
135            "--admin" => cmd.admin = Some(value("--admin")?),
136            "--token-file" => cmd.token_file = Some(value("--token-file")?),
137            "--json" => cmd.json = true,
138            "--undo" => cmd.undo = true,
139            "-f" | "--follow" => cmd.follow = true,
140            "-n" | "--lines" => cmd.lines = Some(value("-n")?.parse().map_err(|_| usage("-n takes a number"))?),
141            "--path" => cmd.path = Some(value("--path")?),
142            "--prefix" => cmd.prefix = Some(value("--prefix")?),
143            "--hours" => cmd.hours = Some(value("--hours")?.parse().map_err(|_| usage("--hours takes a number"))?),
144            "--week" => cmd.hours = Some(24 * 7),
145            "--month" => cmd.hours = Some(24 * 30),
146            "--host" => cmd.host = Some(value("--host")?),
147            "--token" => return Err(usage("the token is read from --token-file or RWS_ADMIN_TOKEN, never the command line (it would show in ps)")),
148            "-h" | "--help" | "help" if cmd.words.is_empty() => cmd.words.push("help".to_string()),
149            f if f.starts_with('-') && f.len() > 1 && f.parse::<f64>().is_err() => return Err(usage(format!("unknown option {f}"))),
150            _ => cmd.words.push(arg.clone()),
151        }
152    }
153    Ok(cmd)
154}
155
156/// Where the admin API is: `http://host:port`, no trailing slash.
157fn admin_base(cmd: &Command) -> String {
158    let configured = cmd.admin.clone().or_else(|| config_value(Config::RWS_CONFIG_ADMIN_LISTEN)).filter(|a| !a.trim().is_empty());
159    let address = configured.unwrap_or_else(|| DEFAULT_ADMIN.to_string());
160    let address = address.trim().trim_end_matches('/');
161    if address.starts_with("https://") {
162        return address.to_string(); // refused when connecting
163    }
164    let address = address.strip_prefix("http://").unwrap_or(address);
165    // A wildcard listen address is reached over loopback.
166    let address = match address.rsplit_once(':') {
167        Some(("0.0.0.0", port)) => format!("127.0.0.1:{port}"),
168        Some(("[::]", port)) => format!("[::1]:{port}"),
169        _ => address.to_string(),
170    };
171    format!("http://{address}")
172}
173
174/// A setting from the environment or the config file (`RWS_CONFIG_FILE`,
175/// else `rws.config.toml` here), without changing the environment.
176fn config_value(name: &str) -> Option<String> {
177    if let Ok(v) = std::env::var(name) {
178        if !v.trim().is_empty() {
179            return Some(v.trim().to_string());
180        }
181    }
182    let file = std::env::var("RWS_CONFIG_FILE").ok().filter(|f| !f.trim().is_empty()).unwrap_or_else(|| "rws.config.toml".to_string());
183    let text = std::fs::read(file).ok()?;
184    let settings = crate::entry_point::config_file::collect_settings(std::io::Cursor::new(&text[..]), String::new()).ok()?;
185    settings.settings.into_iter().rev().find(|(k, _)| k == name).map(|(_, v)| v.trim().to_string()).filter(|v| !v.is_empty())
186}
187
188fn token(cmd: &Command) -> Result<String, Failure> {
189    if let Some(path) = &cmd.token_file {
190        let token = std::fs::read_to_string(path).map_err(|e| unusable(format!("can't read the token file {path}: {e}")))?;
191        return Some(token.trim().to_string()).filter(|t| !t.is_empty()).ok_or_else(|| unusable(format!("the token file {path} is empty")));
192    }
193    let mut names = Vec::new();
194    if let Some(name) = config_value(Config::RWS_CONFIG_ADMIN_TOKEN_ENV) {
195        names.push(name);
196    }
197    names.push(DEFAULT_TOKEN_ENV.to_string());
198    for name in &names {
199        if let Ok(t) = std::env::var(name) {
200            if !t.trim().is_empty() {
201                return Ok(t.trim().to_string());
202            }
203        }
204    }
205    Err(unusable(format!("no admin token: set {} or pass --token-file", names.join(" or "))))
206}
207
208/// The admin API's answer.
209struct Reply {
210    status: u16,
211    body: String,
212}
213
214/// One request to the admin API (`path` under [`API_PREFIX`]).
215struct Api {
216    base: String,
217    token: String,
218}
219
220impl Api {
221    fn connect(&self, method: &str, path: &str, body: Option<&str>) -> Result<BufReader<TcpStream>, Failure> {
222        let host = self.base.trim_start_matches("http://");
223        if self.base.starts_with("https://") {
224            return Err(unusable("the admin API speaks plain HTTP: use http:// (an SSH tunnel for remote servers)"));
225        }
226        let addrs: Vec<std::net::SocketAddr> =
227            std::net::ToSocketAddrs::to_socket_addrs(host).map_err(|e| unusable(format!("admin API at {}: {e}", self.base)))?.collect();
228        let mut last = None;
229        let stream = addrs.iter().find_map(|a| match TcpStream::connect_timeout(a, Duration::from_secs(5)) {
230            Ok(s) => Some(s),
231            Err(e) => {
232                last = Some(e);
233                None
234            }
235        });
236        let mut stream = stream.ok_or_else(|| {
237            unusable(format!("can't reach the admin API at {}: {}", self.base, last.map_or("no address".to_string(), |e| e.to_string())))
238        })?;
239        let _ = stream.set_read_timeout(Some(Duration::from_secs(30)));
240        let body = body.unwrap_or("");
241        let content = if body.is_empty() { String::new() } else { format!("Content-Type: application/json\r\nContent-Length: {}\r\n", body.len()) };
242        let head = format!(
243            "{method} {API_PREFIX}{path} HTTP/1.1\r\nHost: {host}\r\nAuthorization: Bearer {}\r\nUser-Agent: rws-ctl/{}\r\nAccept: application/json, text/event-stream\r\n{content}Connection: close\r\n\r\n",
244            self.token,
245            env!("CARGO_PKG_VERSION"),
246        );
247        stream.write_all(head.as_bytes()).and_then(|_| stream.write_all(body.as_bytes())).map_err(|e| unusable(format!("admin API at {}: {e}", self.base)))?;
248        Ok(BufReader::new(stream))
249    }
250
251    /// Send, read the whole answer; 401/403 are [`EXIT_UNUSABLE`].
252    fn call(&self, method: &str, path: &str, body: Option<&str>) -> Result<Reply, Failure> {
253        let mut reader = self.connect(method, path, body)?;
254        let (status, chunked) = read_head(&mut reader).map_err(|e| unusable(format!("admin API at {}: {e}", self.base)))?;
255        let mut bytes = Vec::new();
256        if chunked {
257            Dechunk::new(reader).read_to_end(&mut bytes)
258        } else {
259            reader.read_to_end(&mut bytes)
260        }
261        .map_err(|e| unusable(format!("admin API at {}: {e}", self.base)))?;
262        let reply = Reply { status, body: String::from_utf8_lossy(&bytes).into_owned() };
263        match status {
264            401 | 403 => Err(unusable(format!("the admin API refused the token ({status})"))),
265            200..=299 => Ok(reply),
266            _ => Err(failed(api_error(&reply))),
267        }
268    }
269}
270
271/// `{"error":"…"}` of a refusal, else the status and body.
272fn api_error(reply: &Reply) -> String {
273    json_rpc::extract_str(&reply.body, "error").unwrap_or_else(|| format!("admin API answered {}: {}", reply.status, reply.body.trim()))
274}
275
276/// The status line and headers; whether the body is chunked.
277fn read_head(reader: &mut impl BufRead) -> std::io::Result<(u16, bool)> {
278    let mut line = String::new();
279    reader.read_line(&mut line)?;
280    let status = line.split_whitespace().nth(1).and_then(|s| s.parse().ok()).ok_or_else(|| std::io::Error::other(format!("not an HTTP response: {:?}", line.trim())))?;
281    let mut chunked = false;
282    loop {
283        line.clear();
284        if reader.read_line(&mut line)? == 0 || line.trim().is_empty() {
285            break;
286        }
287        if let Some((name, value)) = line.split_once(':') {
288            if name.trim().eq_ignore_ascii_case("transfer-encoding") && value.to_ascii_lowercase().contains("chunked") {
289                chunked = true;
290            }
291        }
292    }
293    Ok((status, chunked))
294}
295
296/// A chunked body as plain bytes.
297struct Dechunk<R> {
298    inner: R,
299    left: usize,
300    done: bool,
301}
302
303impl<R: BufRead> Dechunk<R> {
304    fn new(inner: R) -> Self {
305        Dechunk { inner, left: 0, done: false }
306    }
307}
308
309impl<R: BufRead> Read for Dechunk<R> {
310    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
311        while self.left == 0 {
312            if self.done {
313                return Ok(0);
314            }
315            let mut line = String::new();
316            if self.inner.read_line(&mut line)? == 0 {
317                self.done = true;
318                return Ok(0);
319            }
320            let line = line.trim();
321            if line.is_empty() {
322                continue; // the CRLF after a chunk
323            }
324            let size = line.split(';').next().unwrap_or("");
325            self.left = usize::from_str_radix(size.trim(), 16).map_err(|_| std::io::Error::other("bad chunk size"))?;
326            if self.left == 0 {
327                self.done = true;
328                return Ok(0);
329            }
330        }
331        let want = buf.len().min(self.left);
332        let n = self.inner.read(&mut buf[..want])?;
333        if n == 0 {
334            self.done = true;
335        }
336        self.left -= n;
337        Ok(n)
338    }
339}
340
341// ── JSON helpers (the API's JSON is rws's own, so small helpers do) ──────────
342
343fn members(json: &str) -> Vec<(String, String)> {
344    json_rpc::object_members(json).unwrap_or_default()
345}
346
347fn member(json: &str, key: &str) -> String {
348    members(json).into_iter().find(|(k, _)| k == key).map(|(_, v)| v).unwrap_or_default()
349}
350
351/// A raw JSON value as text: strings decoded, others as written.
352fn text(raw: &str) -> String {
353    let raw = raw.trim();
354    if raw.starts_with('"') {
355        json_rpc::extract_str(&format!(r#"{{"v":{raw}}}"#), "v").unwrap_or_default()
356    } else {
357        raw.to_string()
358    }
359}
360
361fn field(json: &str, key: &str) -> String {
362    text(&member(json, key))
363}
364
365fn elements(json: &str) -> Vec<String> {
366    json_rpc::split_array_elements(json.trim())
367}
368
369fn quoted(s: &str) -> String {
370    format!("\"{}\"", crate::mcp::json_escape(s))
371}
372
373fn percent_encode(s: &str) -> String {
374    let mut out = String::new();
375    for b in s.bytes() {
376        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
377            out.push(b as char);
378        } else {
379            out.push_str(&format!("%{b:02X}"));
380        }
381    }
382    out
383}
384
385/// Rows as aligned columns.
386fn table(out: &mut dyn Write, header: &[&str], rows: &[Vec<String>]) -> std::io::Result<()> {
387    let mut widths: Vec<usize> = header.iter().map(|h| h.len()).collect();
388    for row in rows {
389        for (i, cell) in row.iter().enumerate() {
390            widths[i] = widths[i].max(cell.chars().count());
391        }
392    }
393    let line = |cells: Vec<String>| {
394        let last = cells.len() - 1;
395        cells.iter().enumerate().map(|(i, c)| if i == last { c.clone() } else { format!("{c:<w$}", w = widths[i]) }).collect::<Vec<_>>().join("  ")
396    };
397    writeln!(out, "{}", line(header.iter().map(|h| h.to_string()).collect()))?;
398    for row in rows {
399        writeln!(out, "{}", line(row.clone()))?;
400    }
401    Ok(())
402}
403
404fn duration(secs: u64) -> String {
405    match secs {
406        s if s < 60 => format!("{s}s"),
407        s if s < 3600 => format!("{}m {}s", s / 60, s % 60),
408        s if s < 86_400 => format!("{}h {}m", s / 3600, s % 3600 / 60),
409        s => format!("{}d {}h", s / 86_400, s % 86_400 / 3600),
410    }
411}
412
413fn bytes(n: u64) -> String {
414    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
415    let mut v = n as f64;
416    let mut unit = 0;
417    while v >= 1024.0 && unit < UNITS.len() - 1 {
418        v /= 1024.0;
419        unit += 1;
420    }
421    if unit == 0 { format!("{n} B") } else { format!("{v:.1} {}", UNITS[unit]) }
422}
423
424// ── Commands ─────────────────────────────────────────────────────────────────
425
426fn execute(cmd: &Command, out: &mut dyn Write) -> Result<(), Failure> {
427    let words: Vec<&str> = cmd.words.iter().map(String::as_str).collect();
428    if matches!(words.as_slice(), [] | ["help"]) {
429        let _ = write!(out, "{USAGE}");
430        return if words.is_empty() { Err(Failure { code: EXIT_UNUSABLE, message: String::new() }) } else { Ok(()) };
431    }
432    let api = Api { base: admin_base(cmd), token: token(cmd)? };
433    let io = |e: std::io::Error| failed(e.to_string());
434    let json_out = |out: &mut dyn Write, reply: &Reply| writeln!(out, "{}", reply.body.trim()).map_err(io);
435    match words.as_slice() {
436        ["status"] => {
437            let r = api.call("GET", "/status", None)?;
438            if cmd.json {
439                return json_out(out, &r);
440            }
441            print_status(out, &r.body).map_err(io)
442        }
443        ["reload"] => {
444            let r = api.call("POST", "/reload", None)?;
445            if cmd.json {
446                json_out(out, &r)?;
447            }
448            let errors: Vec<String> = elements(&member(&r.body, "errors")).iter().map(|e| text(e)).collect();
449            if member(&r.body, "applied") == "true" {
450                if !cmd.json {
451                    writeln!(out, "reloaded").map_err(io)?;
452                }
453                Ok(())
454            } else {
455                Err(failed(format!("reload refused, the old configuration stays:\n  {}", errors.join("\n  "))))
456            }
457        }
458        ["drain", upstream, backend] => {
459            let body = format!(r#"{{"backend":{},"drained":{}}}"#, quoted(backend), !cmd.undo);
460            let r = api.call("PUT", &format!("/upstreams/{}/drain", percent_encode(upstream)), Some(&body))?;
461            if cmd.json {
462                return json_out(out, &r);
463            }
464            writeln!(out, "{} {backend} of {upstream}", if cmd.undo { "undrained" } else { "drained" }).map_err(io)
465        }
466        ["maintenance"] => {
467            let r = api.call("GET", "/maintenance", None)?;
468            if cmd.json {
469                return json_out(out, &r);
470            }
471            writeln!(out, "maintenance {}", if member(&r.body, "active") == "true" { "on" } else { "off" }).map_err(io)
472        }
473        ["maintenance", state @ ("on" | "off")] => {
474            let r = api.call("PUT", "/maintenance", Some(&format!(r#"{{"active":{}}}"#, *state == "on")))?;
475            if cmd.json {
476                return json_out(out, &r);
477            }
478            writeln!(out, "maintenance {}", if member(&r.body, "active") == "true" { "on" } else { "off" }).map_err(io)
479        }
480        ["block", ip] => {
481            let r = api.call("POST", "/blocklist", Some(&format!(r#"{{"ip":{}}}"#, quoted(ip))))?;
482            if cmd.json {
483                return json_out(out, &r);
484            }
485            writeln!(out, "blocked {}", field(&r.body, "blocked")).map_err(io)
486        }
487        ["unblock", ip] => {
488            let r = api.call("DELETE", &format!("/blocklist/{}", percent_encode(ip)), None)?;
489            if cmd.json {
490                return json_out(out, &r);
491            }
492            writeln!(out, "unblocked {}", field(&r.body, "unblocked")).map_err(io)
493        }
494        ["blocklist"] => {
495            let r = api.call("GET", "/blocklist", None)?;
496            if cmd.json {
497                return json_out(out, &r);
498            }
499            let ips = elements(&r.body);
500            if ips.is_empty() {
501                return writeln!(out, "no blocked IPs").map_err(io);
502            }
503            ips.iter().try_for_each(|ip| writeln!(out, "{}", text(ip))).map_err(io)
504        }
505        ["purge", cache] => {
506            let mut path = format!("/caches/{}", percent_encode(cache));
507            if let Some(p) = &cmd.path {
508                path.push_str(&format!("?path={}", percent_encode(p)));
509            } else if let Some(p) = &cmd.prefix {
510                path.push_str(&format!("?prefix={}", percent_encode(p)));
511            }
512            let r = api.call("DELETE", &path, None)?;
513            if cmd.json {
514                return json_out(out, &r);
515            }
516            writeln!(out, "purged {} entries from {cache}", field(&r.body, "purged")).map_err(io)
517        }
518        ["caches"] => {
519            let r = api.call("GET", "/caches", None)?;
520            if cmd.json {
521                return json_out(out, &r);
522            }
523            let rows: Vec<Vec<String>> = elements(&r.body)
524                .iter()
525                .map(|c| {
526                    let size = field(c, "bytes").parse::<u64>().map(bytes).unwrap_or_else(|_| "-".to_string());
527                    vec![field(c, "name"), field(c, "kind"), field(c, "entries"), size, field(c, "hits"), field(c, "misses")]
528                })
529                .collect();
530            if rows.is_empty() {
531                return writeln!(out, "no caches").map_err(io);
532            }
533            table(out, &["NAME", "KIND", "ENTRIES", "SIZE", "HITS", "MISSES"], &rows).map_err(io)
534        }
535        ["upstreams"] => {
536            let r = api.call("GET", "/upstreams", None)?;
537            if cmd.json {
538                return json_out(out, &r);
539            }
540            let mut rows = Vec::new();
541            for u in elements(&r.body) {
542                for b in elements(&member(&u, "backends")) {
543                    let breaker = field(&b, "breaker");
544                    rows.push(vec![
545                        field(&u, "name"),
546                        field(&b, "url"),
547                        field(&b, "weight"),
548                        if field(&b, "healthy") == "true" { "yes" } else { "no" }.to_string(),
549                        if breaker == "null" { "-".to_string() } else { breaker },
550                        if field(&b, "drained") == "true" { "yes" } else { "no" }.to_string(),
551                    ]);
552                }
553            }
554            if rows.is_empty() {
555                return writeln!(out, "no upstreams").map_err(io);
556            }
557            table(out, &["UPSTREAM", "BACKEND", "WEIGHT", "HEALTHY", "BREAKER", "DRAINED"], &rows).map_err(io)
558        }
559        ["certs"] => {
560            let r = api.call("GET", "/certificates", None)?;
561            if cmd.json {
562                return json_out(out, &r);
563            }
564            print_certificates(out, &r.body).map_err(io)
565        }
566        ["certs", "renew"] => {
567            let r = api.call("POST", "/certificates/renew", None)?;
568            if cmd.json {
569                return json_out(out, &r);
570            }
571            writeln!(out, "renewal requested; `rws ctl certs` shows the outcome").map_err(io)
572        }
573        ["logs"] if cmd.follow => follow_logs(&api, out),
574        ["logs"] => {
575            let r = api.call("GET", &format!("/logs?n={}", cmd.lines.unwrap_or(100)), None)?;
576            if cmd.json {
577                return json_out(out, &r);
578            }
579            elements(&r.body).iter().try_for_each(|l| writeln!(out, "{}", text(l))).map_err(io)
580        }
581        ["traffic"] => {
582            let mut path = format!("/traffic?hours={}", cmd.hours.unwrap_or(24));
583            if let Some(h) = &cmd.host {
584                path.push_str(&format!("&host={}", percent_encode(h)));
585            }
586            let r = api.call("GET", &path, None)?;
587            if cmd.json {
588                return json_out(out, &r);
589            }
590            print_traffic(out, &r.body).map_err(io)
591        }
592        _ => Err(usage(format!("unknown command: {}", words.join(" ")))),
593    }
594}
595
596fn print_status(out: &mut dyn Write, body: &str) -> std::io::Result<()> {
597    let uptime = field(body, "uptime_secs").parse().map(duration).unwrap_or_default();
598    let ready = if field(body, "ready") == "true" { "ready" } else { "not ready" };
599    writeln!(out, "rws {}  pid {}  up {uptime}  {ready}", field(body, "version"), field(body, "pid"))?;
600    let listeners = member(body, "listeners");
601    let main = member(&listeners, "main");
602    writeln!(out, "main      {}{}", field(&main, "address"), if field(&main, "tls") == "true" { " (TLS)" } else { "" })?;
603    let redirect = field(&listeners, "redirect");
604    if redirect != "null" && !redirect.is_empty() {
605        writeln!(out, "redirect  :{redirect}")?;
606    }
607    writeln!(out, "admin     {}", field(&listeners, "admin"))?;
608    let features: Vec<String> = elements(&member(body, "features")).iter().map(|f| text(f)).collect();
609    writeln!(out, "features  {}", features.join(" "))?;
610    for d in elements(&member(body, "disk")) {
611        let free = field(&d, "free_bytes").parse().map(bytes).unwrap_or_default();
612        let total = field(&d, "total_bytes").parse().map(bytes).unwrap_or_default();
613        let low = if field(&d, "low") == "true" { "  LOW" } else { "" };
614        writeln!(out, "disk      {}  {free} free of {total}{low}", field(&d, "dir"))?;
615    }
616    Ok(())
617}
618
619fn print_certificates(out: &mut dyn Write, body: &str) -> std::io::Result<()> {
620    let rows: Vec<Vec<String>> = elements(&member(body, "certificates"))
621        .iter()
622        .map(|c| vec![field(c, "name"), field(c, "expires"), field(c, "days_left"), field(c, "source")])
623        .collect();
624    if rows.is_empty() {
625        writeln!(out, "no certificates")?;
626    } else {
627        table(out, &["NAME", "EXPIRES", "DAYS LEFT", "SOURCE"], &rows)?;
628    }
629    let acme = member(body, "acme");
630    if field(&acme, "running") == "true" {
631        let last = member(&acme, "last_check");
632        if last.trim() == "null" || last.is_empty() {
633            writeln!(out, "ACME renewal: running, not checked yet")?;
634        } else {
635            writeln!(out, "ACME renewal: running, last check: {}", field(&last, "outcome"))?;
636        }
637    } else {
638        writeln!(out, "ACME renewal: off")?;
639    }
640    Ok(())
641}
642
643fn print_traffic(out: &mut dyn Write, body: &str) -> std::io::Result<()> {
644    let hours = field(body, "hours");
645    let host = field(body, "host");
646    let scope = if host == "null" || host.is_empty() { String::new() } else { format!(" for {host}") };
647    writeln!(out, "last {hours} h{scope}")?;
648    let totals = member(body, "totals");
649    let rows: Vec<Vec<String>> = [("people", "people"), ("ai", "AI agents"), ("bots", "bots")]
650        .iter()
651        .map(|(key, label)| {
652            let g = member(&totals, key);
653            vec![label.to_string(), field(&g, "requests"), field(&g, "pages"), field(&g, "visitors")]
654        })
655        .collect();
656    table(out, &["", "REQUESTS", "PAGES", "VISITORS"], &rows)?;
657    let pages = elements(&member(body, "people_pages"));
658    if !pages.is_empty() {
659        writeln!(out, "\ntop pages")?;
660        for pair in pages.iter().take(10) {
661            let pair = elements(pair);
662            if let [page, n] = pair.as_slice() {
663                writeln!(out, "  {:>8}  {}", n.trim(), text(page))?;
664            }
665        }
666    }
667    Ok(())
668}
669
670/// `logs -f`: the SSE stream's `data:` lines until the server goes away.
671fn follow_logs(api: &Api, out: &mut dyn Write) -> Result<(), Failure> {
672    let mut reader = api.connect("GET", "/logs/stream", None)?;
673    let (status, chunked) = read_head(&mut reader).map_err(|e| unusable(e.to_string()))?;
674    if status == 401 || status == 403 {
675        return Err(unusable(format!("the admin API refused the token ({status})")));
676    }
677    // Keep-alive comments arrive every 15 s; wait for them, not 30 s.
678    let _ = reader.get_ref().set_read_timeout(Some(Duration::from_secs(60)));
679    let body: Box<dyn BufRead> = if chunked { Box::new(BufReader::new(Dechunk::new(reader))) } else { Box::new(reader) };
680    if status != 200 {
681        let mut text = String::new();
682        let mut body = body;
683        let _ = body.read_to_string(&mut text);
684        return Err(failed(api_error(&Reply { status, body: text })));
685    }
686    for line in body.lines() {
687        let line = line.map_err(|e| failed(format!("log stream ended: {e}")))?;
688        // Pings are events with empty data; comments start with ':'.
689        if let Some(data) = line.strip_prefix("data:") {
690            let data = data.strip_prefix(' ').unwrap_or(data);
691            if !data.is_empty() {
692                writeln!(out, "{data}").map_err(|e| failed(e.to_string()))?;
693                let _ = out.flush();
694            }
695        }
696    }
697    Ok(())
698}
699
700#[cfg(test)]
701mod tests;