garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /programs/src/bin/admin.rs

raw

//! The system's commands, one program told apart by the name it was started
//! as (`pinnacle_ui::command::ADMIN_COMMANDS`): what a person looking after
//! a device asks of it. `ps`, `kill` and `services` (the programs that run
//! and the names they registered), `log` (what the kernel and the programs
//! wrote), `apps`, `net`, `lookup`, `ping` and `fetch` (the network),
//! `date`, `env` and `restart`. Each answers with a table or text, its
//! failures in the status; ending a system program or restarting asks
//! first.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_records::start::{PWD, resolve};
use pinnacle_rt::net::{self, HttpError, IpAddr};
use pinnacle_rt::output::{AskKind, Output};
use pinnacle_rt::{Running, fs};
use pinnacle_ui::command::{home, size};

/// The most of a body `fetch` shows as text.
const SHOWN: usize = 64 * 1024;

/// A duration of `ms`, said the short way: `3 s`, `4 min`, `2 h 5 min`,
/// `3 d 4 h`.
fn took(ms: u64) -> String {
    let s = ms / 1000;
    match s {
        0..60 => alloc::format!("{s} s"),
        60..3600 => alloc::format!("{} min", s / 60),
        3600..86_400 => alloc::format!("{} h {} min", s / 3600, s / 60 % 60),
        _ => alloc::format!("{} d {} h", s / 86_400, s / 3600 % 24),
    }
}

/// What went wrong over HTTP, said.
fn said(e: &HttpError) -> String {
    match e {
        HttpError::BadUrl => "Not a URL: http:// or https://, then a host".into(),
        HttpError::NoAddress => "The name has no address: lookup says more".into(),
        HttpError::NoConnection => "The host could not be reached".into(),
        HttpError::TimedOut => "The host did not answer in time".into(),
        HttpError::BadResponse => "The answer was not HTTP".into(),
        HttpError::Status(code) => alloc::format!("The server answered {code}"),
        HttpError::Moved(to) => alloc::format!("Moved to {to}"),
        HttpError::TooManyRedirects => "Sent on too many times".into(),
        HttpError::NoRoots => "No certificates to check the host's against".into(),
        HttpError::Tls(e) => alloc::format!("The secure connection failed: {e:?}"),
        HttpError::Stopped => "Stopped".into(),
        HttpError::Http2(e) => alloc::format!("HTTP/2 failed: {e:?}"),
    }
}

struct Admin {
    out: Output,
    cwd: String,
    failed: Vec<String>,
}

impl Admin {
    fn fail(&mut self, why: impl Into<String>) {
        self.failed.push(why.into());
    }

    fn yes(&self, prompt: &str) -> bool {
        self.out.ask(AskKind::YesNo, prompt, &[]).as_deref() == Some("Yes")
    }

    /// `ps`: every program that runs, oldest first.
    fn ps(&mut self) {
        let all = pinnacle_rt::processes();
        if all.is_empty() {
            return self.fail("The kernel said nothing of its programs");
        }
        let now = pinnacle_rt::time();
        let mut memory = 0;
        let rows = all
            .iter()
            .map(|p| {
                memory += p.memory;
                alloc::vec![
                    alloc::format!("{}", p.id),
                    if p.name.is_empty() {
                        "(a check)".into()
                    } else {
                        p.name.clone()
                    },
                    p.kind.clone(),
                    alloc::format!("{}", p.threads),
                    size(p.memory),
                    took(now.saturating_sub(p.started)),
                ]
            })
            .collect();
        self.out
            .table(&["Id", "Program", "Kind", "Threads", "Memory", "Up"], rows);
        self.out.text(&alloc::format!(
            "{} programs, {} of memory between them",
            all.len(),
            size(memory)
        ));
    }

    /// `kill`: programs by number or name; a system one (not an app) only
    /// once the person says yes, for the device leans on those.
    fn kill(&mut self, args: &[&str]) {
        if args.is_empty() {
            return self.fail("kill and a program's number or name: ps lists them");
        }
        let all = pinnacle_rt::processes();
        let me = all
            .iter()
            .find(|p| p.name == "admin" && p.started == own_start(&all))
            .map(|p| p.id);
        for &arg in args {
            let found: Vec<&Running> = match arg.parse::<u64>() {
                Ok(id) => all.iter().filter(|p| p.id == id).collect(),
                Err(_) => all.iter().filter(|p| p.name == arg).collect(),
            };
            if found.is_empty() {
                self.fail(alloc::format!("No program {arg}: ps lists them"));
                continue;
            }
            for p in found {
                if p.kind == "display" {
                    self.fail(alloc::format!(
                        "{} draws the screen and takes input: not ended",
                        p.name
                    ));
                    continue;
                }
                if Some(p.id) == me {
                    continue;
                }
                if p.kind != "app" {
                    let prompt = alloc::format!(
                        "{} ({}) is part of the system: what it does stops until it is started again. End it?",
                        p.name,
                        p.id
                    );
                    if !self.yes(&prompt) {
                        self.fail(alloc::format!("{} kept", p.name));
                        continue;
                    }
                }
                match pinnacle_rt::kill_id(p.id) {
                    true => {
                        self.out.text(&alloc::format!("Ended {} ({})", p.name, p.id));
                    }
                    false => self.fail(alloc::format!("{} ({}) could not be ended", p.name, p.id)),
                }
            }
        }
    }

    /// `services`: the names registered, with what describes itself.
    fn services(&mut self) {
        let names = pinnacle_rt::services();
        if names.is_empty() {
            return self.fail("The kernel said nothing of its services");
        }
        let rows = names
            .into_iter()
            .map(|name| {
                let what = pinnacle_ui::verbs::SERVICES
                    .iter()
                    .find(|(s, _)| *s == name)
                    .map_or_else(String::new, |(_, what)| String::from(*what));
                alloc::vec![name, what]
            })
            .collect();
        self.out.table(&["Service", "What it does"], rows);
    }

    /// `log`: the last lines (50, or the number given), or those holding a
    /// word.
    fn log(&mut self, args: &[&str]) {
        let mut count = 50usize;
        let mut wanted = Vec::new();
        for &arg in args {
            match arg.parse() {
                Ok(n) => count = n,
                Err(_) => wanted.push(arg.to_lowercase()),
            }
        }
        let text = pinnacle_rt::log();
        let lines: Vec<&str> = text
            .lines()
            .map(|l| l.trim_end_matches('\r'))
            .filter(|l| wanted.iter().all(|w| l.to_lowercase().contains(w.as_str())))
            .collect();
        if lines.is_empty() {
            return self.fail("Nothing in the log matches");
        }
        let shown = &lines[lines.len().saturating_sub(count)..];
        self.out.text(&shown.join("\n"));
    }

    /// `apps`: each installed app, its version and what its manifest grants.
    fn apps(&mut self) {
        let mut rows = Vec::new();
        for name in pinnacle_ui::command::apps() {
            let manifest =
                fs::read_string(&alloc::format!("system:/apps/{name}/manifest")).unwrap_or_default();
            let field = |key: &str| fs::field(&manifest, key).unwrap_or("").trim();
            let rights: Vec<&str> = ["network", "gpu"]
                .into_iter()
                .filter(|k| field(k) == "yes")
                .collect();
            let size = fs::stat(&alloc::format!("system:/apps/{name}/program")).map_or(0, |s| s.size);
            rows.push(alloc::vec![
                name.clone(),
                String::from(field("title")),
                String::from(field("version")),
                pinnacle_ui::command::size(size),
                rights.join(" "),
            ]);
        }
        if rows.is_empty() {
            self.out.text("No apps installed");
            return;
        }
        self.out
            .table(&["App", "Title", "Version", "Size", "Rights"], rows);
    }

    /// `net`: where the network is; `net on` and `net off` switch it.
    fn net(&mut self, args: &[&str]) {
        match args {
            [] => {}
            ["on" | "off"] => {
                if net::switch(args[0] == "on").is_none() {
                    return self.fail("The network could not be switched");
                }
            }
            _ => return self.fail("net alone says where the network is; net on, net off"),
        }
        let state = match net::state() {
            pinnacle_rt::abi::net::NONE => "No network device",
            pinnacle_rt::abi::net::OFF => "Off",
            pinnacle_rt::abi::net::CONNECTING => "On, waiting for an address",
            pinnacle_rt::abi::net::ONLINE => "Online",
            _ => "Not known",
        };
        let row = |what: &str, value: String| alloc::vec![String::from(what), value];
        let mut rows = alloc::vec![row("State", state.into())];
        if let Some((ip, router, dns)) = net::info() {
            rows.push(row("Address", alloc::format!("{}", IpAddr::V4(ip))));
            rows.push(row("Router", alloc::format!("{}", IpAddr::V4(router))));
            rows.push(row("Name server", alloc::format!("{}", IpAddr::V4(dns))));
        }
        if let Some((ip, router, dns)) = net::info6() {
            rows.push(row("IPv6 address", alloc::format!("{}", IpAddr::V6(ip))));
            if let Some(router) = router {
                rows.push(row("IPv6 router", alloc::format!("{}", IpAddr::V6(router))));
            }
            if let Some(dns) = dns {
                rows.push(row("IPv6 name server", alloc::format!("{}", IpAddr::V6(dns))));
            }
        }
        self.out.table(&["", ""], rows);
    }

    /// `lookup`: each name's address.
    fn lookup(&mut self, args: &[&str]) {
        if args.is_empty() {
            return self.fail("lookup and a name: lookup example.org");
        }
        let mut rows = Vec::new();
        for &name in args {
            let start = pinnacle_rt::time();
            match net::resolve(name) {
                Some(ip) => rows.push(alloc::vec![
                    String::from(name),
                    alloc::format!("{ip}"),
                    alloc::format!("{} ms", pinnacle_rt::time() - start),
                ]),
                None => self.fail(alloc::format!("{name} has no address")),
            }
        }
        if !rows.is_empty() {
            self.out.table(&["Name", "Address", "Took"], rows);
        }
    }

    /// `ping`: four HTTP requests for a host's `/` (HTTPS on port 443, the
    /// default; plain HTTP on another port given), each one's answer and
    /// time. A program sends no ICMP, and the kernel does not say when a
    /// bare TCP connection opens, so the time is a request's: connection,
    /// TLS, answer.
    fn ping(&mut self, args: &[&str]) {
        let (host, port) = match args {
            [host] => (*host, 443u16),
            [host, port] => match port.parse() {
                Ok(p) => (*host, p),
                Err(_) => return self.fail(alloc::format!("A port is a number: not “{port}”")),
            },
            _ => return self.fail("ping, a host, and a port if not 443: ping example.org 80"),
        };
        let Some(ip) = net::parse_ip(host).or_else(|| net::resolve(host)) else {
            return self.fail(alloc::format!("{host} has no address"));
        };
        let url = match port {
            443 => alloc::format!("https://{host}/"),
            80 => alloc::format!("http://{host}/"),
            _ => alloc::format!("http://{host}:{port}/"),
        };
        self.out.text(&alloc::format!("{url} at {ip}"));
        let mut rows = Vec::new();
        let mut answered = 0;
        for n in 1..=4 {
            let start = pinnacle_rt::time();
            let head = net::request("HEAD", &url, &[], &[], 5000, |_| true);
            let ms = pinnacle_rt::time() - start;
            let answer = match &head {
                Ok(head) => {
                    answered += 1;
                    alloc::format!("{}", head.status)
                }
                Err(e) => said(e),
            };
            let took = if head.is_ok() {
                alloc::format!("{ms} ms")
            } else {
                String::new()
            };
            rows.push(alloc::vec![alloc::format!("{n}"), answer, took]);
            if n < 4 {
                pinnacle_rt::sleep(500);
            }
        }
        self.out.table(&["", "Answer", "Took"], rows);
        if answered == 0 {
            self.fail(alloc::format!("{host} did not answer on port {port}"));
        }
    }

    /// `fetch`: a URL's body as text, or written to the file given.
    fn fetch(&mut self, args: &[&str]) {
        let (url, file) = match args {
            [url] => (*url, None),
            [url, file] => (*url, Some(resolve(&self.cwd, home(), file))),
            _ => {
                return self
                    .fail("fetch, a URL, and a file to save it to if not shown: fetch https://example.org");
            }
        };
        let url = match url.contains("://") {
            true => String::from(url),
            false => alloc::format!("https://{url}"),
        };
        let start = pinnacle_rt::time();
        let mut body = Vec::new();
        let mut written = 0u64;
        let mut broke = false;
        if let Some(file) = &file
            && !fs::write(file, &[])
        {
            return self.fail(alloc::format!("{file} could not be written"));
        }
        let head = net::request("GET", &url, &[], &[], 15_000, |piece| match &file {
            Some(file) => {
                broke |= !fs::write_at(file, written, piece);
                written += piece.len() as u64;
                !broke
            }
            None => {
                body.extend_from_slice(piece);
                body.len() < 16 << 20
            }
        });
        let ms = pinnacle_rt::time() - start;
        let head = match head {
            Ok(head) => head,
            Err(e) => return self.fail(said(&e)),
        };
        let got = file.as_ref().map_or(body.len() as u64, |_| written);
        let kind = head.header("content-type").unwrap_or("").trim();
        self.out.text(&alloc::format!(
            "{} {} · {} · {kind} · {} ms",
            head.status,
            if head.http2 { "HTTP/2" } else { "HTTP/1.1" },
            size(got),
            ms
        ));
        if let Some(to) = head.header("location") {
            self.out.text(&alloc::format!("Sent on to {}", to.trim()));
        }
        match file {
            Some(file) if broke => self.fail(alloc::format!("{file} could not be written")),
            Some(file) => {
                self.out.text(&alloc::format!("Saved to {file}"));
            }
            None if body.contains(&0) => {
                self.out.text("Not text: fetch url file saves it");
            }
            None => {
                let text = String::from_utf8_lossy(&body[..body.len().min(SHOWN)]);
                self.out.text(text.trim_end());
                if body.len() > SHOWN {
                    self.out.text(&alloc::format!(
                        "… the first {} of {} shown",
                        size(SHOWN as u64),
                        size(got)
                    ));
                }
            }
        }
        if head.status >= 400 {
            self.fail(alloc::format!("The server answered {}", head.status));
        }
    }

    /// `date`: here and in UTC, and where the clock comes from.
    fn date(&mut self) {
        let (ms, source) = pinnacle_rt::clock_ms();
        if source == pinnacle_rt::ClockSource::None {
            return self.fail(alloc::format!(
                "The time of day is not known yet: up {}",
                took(pinnacle_rt::time())
            ));
        }
        const DAYS: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
        let show = |t: &pinnacle_rt::tz::DateTime, zone: &str| {
            alloc::format!(
                "{} {}-{:02}-{:02} {:02}:{:02}:{:02} {zone}",
                DAYS[t.weekday as usize % 7],
                t.year,
                t.month,
                t.day,
                t.hour,
                t.minute,
                t.second
            )
        };
        let zone = pinnacle_rt::locale::zone();
        let row = |what: &str, value: String| alloc::vec![String::from(what), value];
        let mut rows = Vec::new();
        if let Some((t, local)) = pinnacle_rt::locale::now_in(&zone) {
            let name = pinnacle_rt::locale::zone_name().unwrap_or_else(|| "UTC".into());
            rows.push(row("Here", show(&t, &local.name)));
            rows.push(row(
                "Zone",
                alloc::format!("{name}{}", if local.dst { ", summer time" } else { "" }),
            ));
        }
        let utc = pinnacle_rt::tz::DateTime::from_seconds((ms / 1000) as i64);
        rows.push(row("UTC", show(&utc, "UTC")));
        let from = match source {
            pinnacle_rt::ClockSource::Network => "the network (NTP)",
            _ => "the board's clock",
        };
        rows.push(row("From", from.into()));
        rows.push(row("Up", took(pinnacle_rt::time())));
        self.out.table(&["", ""], rows);
    }

    /// `env`: what this command was started with, as every command is.
    fn env(&mut self) {
        let rows = self
            .out
            .env
            .iter()
            .map(|(k, v)| alloc::vec![k.clone(), v.clone()])
            .collect();
        self.out.table(&["Name", "Value"], rows);
    }

    /// `restart`: once the person says yes.
    fn restart(&mut self) {
        if !self.yes("Restart the device now? What runs is ended, the disks' writes finished first") {
            return self.fail("Not restarted");
        }
        self.out.text("Restarting…");
        pinnacle_rt::restart();
        self.fail("The restart was refused");
    }
}

/// When the newest `admin` started: this one, which `kill admin` leaves.
fn own_start(all: &[Running]) -> u64 {
    all.iter()
        .filter(|p| p.name == "admin")
        .map(|p| p.started)
        .max()
        .unwrap_or(0)
}

#[unsafe(no_mangle)]
fn main(argument: u64) -> u64 {
    let out = Output::start(argument);
    let cwd = out
        .env
        .iter()
        .find(|(k, _)| k == PWD)
        .map_or_else(|| String::from(home()), |(_, v)| v.clone());
    let args = out.args.clone();
    let words: Vec<&str> = args.iter().skip(1).map(String::as_str).collect();
    let mut admin = Admin {
        out,
        cwd,
        failed: Vec::new(),
    };
    match args.first().map(String::as_str) {
        Some("ps") => admin.ps(),
        Some("kill") => admin.kill(&words),
        Some("services") => admin.services(),
        Some("log") => admin.log(&words),
        Some("apps") => admin.apps(),
        Some("net") => admin.net(&words),
        Some("lookup") => admin.lookup(&words),
        Some("ping") => admin.ping(&words),
        Some("fetch") => admin.fetch(&words),
        Some("date") => admin.date(),
        Some("env") => admin.env(),
        Some("restart") => admin.restart(),
        _ => admin.fail("admin is started as one of the system's commands: help lists them"),
    }
    let code = u64::from(!admin.failed.is_empty());
    admin.out.status(code, &admin.failed.join("\n"))
}