Skip to main content

telnetd/
shell.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Command interpreter for the telnet console: every VFS operation exposed
24//! to userspace (ls, cat, cd, mkdir, rm, mv, cp, stat, tree, ...), plus
25//! quoting, `>` / `>>` redirection and a few network helpers.
26
27use crate::{
28    out::{ColorMode, Out, Style},
29    sys::{self, DT_DIR, DT_LNK, EAGAIN, S_IFDIR, S_IFLNK, S_IFMT},
30    telnet::Session,
31};
32use alloc::{string::String, vec::Vec};
33use core::fmt::Write as _;
34use strat9_syscall::{call, error::Error, flag::OpenFlags};
35
36type CmdFn = fn(&mut Session, &mut Out, &[String]);
37
38struct Cmd {
39    name: &'static str,
40    usage: &'static str,
41    help: &'static str,
42    run: CmdFn,
43}
44
45const fn cmd(name: &'static str, usage: &'static str, help: &'static str, run: CmdFn) -> Cmd {
46    Cmd { name, usage, help, run }
47}
48
49/// Command table (also drives `help` and Tab completion).
50static COMMANDS: &[Cmd] = &[
51    cmd("help", "[cmd]", "show this help", cmd_help),
52    cmd("pwd", "", "print working directory", cmd_pwd),
53    cmd("cd", "[dir]", "change directory", cmd_cd),
54    cmd("ls", "[-l] [-a] [-1] [path...]", "list directory contents", cmd_ls),
55    cmd("cat", "<file...>", "print files", cmd_cat),
56    cmd("head", "[-n N] <file>", "first lines of a file", cmd_head),
57    cmd("tail", "[-n N] <file>", "last lines of a file", cmd_tail),
58    cmd("wc", "<file...>", "count lines, words and bytes", cmd_wc),
59    cmd("grep", "[-i] [-n] [-v] <pat> <file...>", "search for text", cmd_grep),
60    cmd("hexdump", "<file> [offset] [len]", "hex + ASCII dump", cmd_hexdump),
61    cmd("stat", "<path...>", "file metadata", cmd_stat),
62    cmd("tree", "[-a] [-L depth] [path]", "directory tree", cmd_tree),
63    cmd("mkdir", "[-p] <dir...>", "create directories", cmd_mkdir),
64    cmd("touch", "[-t unix-secs] <file...>", "create files / update their timestamps", cmd_touch),
65    cmd("date", "", "current UTC date and time", cmd_date),
66    cmd("rm", "[-r] [-f] <path...>", "remove files / directories", cmd_rm),
67    cmd("rmdir", "<dir...>", "remove empty directories", cmd_rmdir),
68    cmd("mv", "<src> <dst>", "move / rename", cmd_mv),
69    cmd("cp", "[-r] <src> <dst>", "copy files / directories", cmd_cp),
70    cmd("chmod", "<octal-mode> <path...>", "change permission bits", cmd_chmod),
71    cmd("ln", "<existing> <link>", "create a hard link", cmd_ln),
72    cmd("write", "<file> <text...>", "overwrite a file with text", cmd_write),
73    cmd("append", "<file> <text...>", "append text to a file", cmd_append),
74    cmd("echo", "[-n] [text...]", "print text (supports > and >>)", cmd_echo),
75    cmd("df", "", "mount points and their status", cmd_df),
76    cmd("mount", "", "list mount points", cmd_df),
77    cmd("ip", "", "show IPv4 address", cmd_ip),
78    cmd("net", "", "show network configuration", cmd_net),
79    cmd("history", "", "command history", cmd_history),
80    cmd("term", "", "terminal information", cmd_term),
81    cmd("color", "[auto|16|256|off]", "choose the color mode", cmd_color),
82    cmd("clear", "", "clear the screen", cmd_clear),
83    cmd("exit", "", "close the session (also: quit, logout)", cmd_noop),
84];
85
86fn cmd_noop(_: &mut Session, _: &mut Out, _: &[String]) {}
87
88// ── Parsing ─────────────────────────────────────────────────────────────────
89
90enum Tok {
91    Word(String),
92    Redir { append: bool },
93}
94
95fn tokenize(line: &str) -> Result<Vec<Tok>, &'static str> {
96    let mut toks = Vec::new();
97    let mut cur = String::new();
98    let mut have = false;
99    let mut quote: Option<char> = None;
100    let mut it = line.chars().peekable();
101    while let Some(c) = it.next() {
102        match quote {
103            Some(q) => {
104                if c == q {
105                    quote = None;
106                } else if c == '\\' && q == '"' {
107                    match it.next() {
108                        Some(n) if n == '"' || n == '\\' => cur.push(n),
109                        Some(n) => {
110                            cur.push('\\');
111                            cur.push(n);
112                        }
113                        None => cur.push('\\'),
114                    }
115                } else {
116                    cur.push(c);
117                }
118            }
119            None => match c {
120                '"' | '\'' => {
121                    quote = Some(c);
122                    have = true;
123                }
124                '\\' => {
125                    if let Some(n) = it.next() {
126                        cur.push(n);
127                        have = true;
128                    }
129                }
130                ' ' | '\t' => {
131                    if have {
132                        toks.push(Tok::Word(core::mem::take(&mut cur)));
133                        have = false;
134                    }
135                }
136                '>' => {
137                    if have {
138                        toks.push(Tok::Word(core::mem::take(&mut cur)));
139                        have = false;
140                    }
141                    let append = it.peek() == Some(&'>');
142                    if append {
143                        it.next();
144                    }
145                    toks.push(Tok::Redir { append });
146                }
147                _ => {
148                    cur.push(c);
149                    have = true;
150                }
151            },
152        }
153    }
154    if quote.is_some() {
155        return Err("unterminated quote");
156    }
157    if have {
158        toks.push(Tok::Word(cur));
159    }
160    Ok(toks)
161}
162
163/// Split `-abc` style flags from operands. `--` ends flag parsing.
164fn parse_flags(args: &[String]) -> (String, Vec<&str>) {
165    let mut flags = String::new();
166    let mut ops = Vec::new();
167    let mut done = false;
168    for a in args {
169        if !done && a == "--" {
170            done = true;
171        } else if !done && a.len() > 1 && a.starts_with('-') {
172            flags.push_str(&a[1..]);
173        } else {
174            ops.push(a.as_str());
175        }
176    }
177    (flags, ops)
178}
179
180/// Run one command line. Returns `false` when the session should end.
181pub fn run_line(sess: &mut Session, out: &mut Out, line: &str) -> bool {
182    let toks = match tokenize(line) {
183        Ok(t) => t,
184        Err(e) => {
185            out.error("shell", format_args!("{}", e));
186            return true;
187        }
188    };
189    let mut args: Vec<String> = Vec::new();
190    let mut redirect: Option<(String, bool)> = None;
191    let mut it = toks.into_iter();
192    while let Some(t) = it.next() {
193        match t {
194            Tok::Word(w) => args.push(w),
195            Tok::Redir { append } => match it.next() {
196                Some(Tok::Word(p)) => redirect = Some((p, append)),
197                _ => {
198                    out.error("shell", format_args!("syntax error: missing file after '>'"));
199                    return true;
200                }
201            },
202        }
203    }
204    if args.is_empty() {
205        return true;
206    }
207
208    let name = args[0].as_str();
209    if matches!(name, "exit" | "quit" | "logout") {
210        return false;
211    }
212    let Some(command) = COMMANDS.iter().find(|c| c.name == name) else {
213        out.error(name, format_args!("command not found (try 'help')"));
214        return true;
215    };
216
217    let mut redirect_fd = None;
218    if let Some((path, append)) = redirect {
219        let abs = sys::resolve(&sess.cwd, &path);
220        let mode = if append { OpenFlags::APPEND } else { OpenFlags::TRUNCATE };
221        match sys::open(&abs, OpenFlags::WRITE | OpenFlags::CREATE | mode) {
222            Ok(fd) => {
223                out.set_redirect(Some(fd));
224                redirect_fd = Some(fd);
225            }
226            Err(e) => {
227                out.error("shell", format_args!("{}: {}", abs, sys::err_text(e)));
228                return true;
229            }
230        }
231    }
232
233    (command.run)(sess, out, &args[1..]);
234
235    out.set_redirect(None);
236    if let Some(fd) = redirect_fd {
237        let _ = call::close(fd);
238    }
239    if out.interrupted {
240        out.styled(Style::Dim, "^C\n");
241    }
242    true
243}
244
245// ── Tab completion ──────────────────────────────────────────────────────────
246
247pub struct Cand {
248    /// Full replacement text for the token being completed.
249    pub name: String,
250    /// Short label shown when listing alternatives.
251    pub label: String,
252    pub is_dir: bool,
253}
254
255/// Returns `(token_start, candidates)` for the text before the cursor.
256pub fn complete(cwd: &str, line: &[u8]) -> (usize, Vec<Cand>) {
257    let start = line.iter().rposition(|&b| b == b' ').map(|i| i + 1).unwrap_or(0);
258    let Ok(token) = core::str::from_utf8(&line[start..]) else {
259        return (start, Vec::new());
260    };
261    let mut cands = Vec::new();
262
263    let first_word = !line[..start].iter().any(|&b| b != b' ');
264    if first_word && !token.contains('/') {
265        for c in COMMANDS.iter().filter(|c| c.name.starts_with(token)) {
266            cands.push(Cand {
267                name: String::from(c.name),
268                label: String::from(c.name),
269                is_dir: false,
270            });
271        }
272        for extra in ["quit", "logout"] {
273            if extra.starts_with(token) && !token.is_empty() {
274                cands.push(Cand {
275                    name: String::from(extra),
276                    label: String::from(extra),
277                    is_dir: false,
278                });
279            }
280        }
281        return (start, cands);
282    }
283
284    let (dir_part, base) = match token.rfind('/') {
285        Some(i) => (&token[..=i], &token[i + 1..]),
286        None => ("", token),
287    };
288    let dir_abs = if dir_part.is_empty() {
289        String::from(cwd)
290    } else {
291        sys::resolve(cwd, dir_part)
292    };
293    if let Ok(entries) = sys::read_dir(&dir_abs) {
294        for e in entries {
295            if !e.name.starts_with(base) || (e.name.starts_with('.') && !base.starts_with('.')) {
296                continue;
297            }
298            let is_dir = e.file_type == DT_DIR;
299            let mut full = String::from(dir_part);
300            full.push_str(&e.name);
301            if is_dir {
302                full.push('/');
303            }
304            let mut label = e.name.clone();
305            if is_dir {
306                label.push('/');
307            }
308            cands.push(Cand { name: full, label, is_dir });
309        }
310    }
311    (start, cands)
312}
313
314// ── Output helpers ──────────────────────────────────────────────────────────
315
316fn style_for_type(t: u8) -> Style {
317    match t {
318        DT_DIR => Style::Dir,
319        DT_LNK => Style::Link,
320        2 | 6 => Style::Device,
321        _ => Style::File,
322    }
323}
324
325fn style_for_mode(mode: u32) -> Style {
326    match mode & S_IFMT {
327        S_IFDIR => Style::Dir,
328        S_IFLNK => Style::Link,
329        0o020000 | 0o060000 => Style::Device,
330        _ => Style::File,
331    }
332}
333
334fn path_err(out: &mut Out, cmd: &str, path: &str, e: Error) {
335    out.error(cmd, format_args!("{}: {}", path, sys::err_text(e)));
336}
337
338fn usage(out: &mut Out, name: &str) {
339    if let Some(c) = COMMANDS.iter().find(|c| c.name == name) {
340        out.style(Style::Warn);
341        let _ = write!(out, "usage: {} {}", c.name, c.usage);
342        out.style(Style::Reset);
343        out.text("\n");
344    }
345}
346
347// ── Commands: navigation and listing ────────────────────────────────────────
348
349fn cmd_help(_: &mut Session, out: &mut Out, args: &[String]) {
350    if let Some(name) = args.first() {
351        match COMMANDS.iter().find(|c| c.name == name.as_str()) {
352            Some(c) => {
353                out.styled(Style::Head, c.name);
354                let _ = write!(out, " {}\n  {}\n", c.usage, c.help);
355            }
356            None => out.error("help", format_args!("no such command: {}", name)),
357        }
358        return;
359    }
360    out.styled(Style::Head, "Strat9 telnet shell");
361    out.text(" - commands:\n");
362    for c in COMMANDS {
363        out.text("  ");
364        out.style(Style::Ok);
365        let _ = write!(out, "{:<8}", c.name);
366        out.style(Style::Reset);
367        out.style(Style::Dim);
368        let _ = write!(out, " {:<34}", c.usage);
369        out.style(Style::Reset);
370        let _ = write!(out, " {}\n", c.help);
371    }
372    out.styled(
373        Style::Dim,
374        "\nQuotes ('..' \"..\") and \\ escapes work; use > file or >> file to redirect output.\n\
375         Keys: Tab complete, Up/Down history, Ctrl-A/E/K/U/W edit, Ctrl-C cancel, Ctrl-D logout.\n",
376    );
377}
378
379fn cmd_pwd(sess: &mut Session, out: &mut Out, _: &[String]) {
380    let cwd = sess.cwd.clone();
381    out.text(&cwd);
382    out.text("\n");
383}
384
385fn cmd_cd(sess: &mut Session, out: &mut Out, args: &[String]) {
386    let target = match args.first().map(|s| s.as_str()) {
387        None | Some("~") => String::from("/"),
388        Some(t) => sys::resolve(&sess.cwd, t),
389    };
390    match sys::open(&target, OpenFlags::READ | OpenFlags::DIRECTORY) {
391        Ok(fd) => {
392            let _ = call::close(fd);
393            sess.cwd = target;
394        }
395        Err(e) => path_err(out, "cd", &target, e),
396    }
397}
398
399struct Item {
400    name: String,
401    style: Style,
402    suffix: &'static str,
403}
404
405fn print_columns(out: &mut Out, items: &[Item], width: usize) {
406    if items.is_empty() {
407        return;
408    }
409    let colw = items
410        .iter()
411        .map(|i| i.name.chars().count() + i.suffix.len())
412        .max()
413        .unwrap_or(1)
414        + 2;
415    let cols = (width / colw).max(1);
416    let rows = (items.len() + cols - 1) / cols;
417    for r in 0..rows {
418        for c in 0..cols {
419            let idx = c * rows + r;
420            if idx >= items.len() {
421                break;
422            }
423            let it = &items[idx];
424            out.style(it.style);
425            out.text(&it.name);
426            out.text(it.suffix);
427            out.style(Style::Reset);
428            if idx + rows < items.len() {
429                let used = it.name.chars().count() + it.suffix.len();
430                for _ in used..colw {
431                    out.text(" ");
432                }
433            }
434        }
435        out.text("\n");
436    }
437}
438
439fn print_long(out: &mut Out, name: &str, full: &str, fallback_type: u8) {
440    match sys::stat(full) {
441        Ok(st) => {
442            let _ = write!(
443                out,
444                "{} {:>3} {:>4} {:>4} {:>9} {} ",
445                sys::format_mode(st.st_mode),
446                st.st_nlink,
447                st.st_uid,
448                st.st_gid,
449                st.st_size,
450                sys::format_time(st.st_mtime.tv_sec)
451            );
452            out.style(style_for_mode(st.st_mode));
453            out.text(name);
454            if st.st_mode & S_IFMT == S_IFDIR {
455                out.text("/");
456            }
457            out.style(Style::Reset);
458            out.text("\n");
459        }
460        Err(_) => {
461            let t = if fallback_type == DT_DIR { 'd' } else { '-' };
462            let _ = write!(out, "{}?????????  ?    ?    ?         ? ", t);
463            out.style(style_for_type(fallback_type));
464            out.text(name);
465            out.style(Style::Reset);
466            out.text("\n");
467        }
468    }
469}
470
471fn cmd_ls(sess: &mut Session, out: &mut Out, args: &[String]) {
472    let (flags, ops) = parse_flags(args);
473    let long = flags.contains('l');
474    let all = flags.contains('a');
475    let single = flags.contains('1') || out.redirected();
476    let width = sess.term.cols as usize;
477    let targets: Vec<&str> = if ops.is_empty() { alloc::vec!["."] } else { ops };
478    let multi = targets.len() > 1;
479
480    for (n, t) in targets.iter().enumerate() {
481        if out.stop() {
482            return;
483        }
484        let path = sys::resolve(&sess.cwd, t);
485        if multi {
486            if n > 0 {
487                out.text("\n");
488            }
489            out.styled(Style::Head, &path);
490            out.text(":\n");
491        }
492        match sys::read_dir(&path) {
493            Ok(entries) => {
494                let shown: Vec<&sys::DirEntry> = entries
495                    .iter()
496                    .filter(|e| all || !e.name.starts_with('.'))
497                    .collect();
498                if shown.is_empty() {
499                    out.styled(Style::Dim, "(empty)\n");
500                } else if long {
501                    for e in shown {
502                        if out.stop() {
503                            return;
504                        }
505                        print_long(out, &e.name, &sys::join(&path, &e.name), e.file_type);
506                    }
507                } else if single {
508                    for e in shown {
509                        out.styled(style_for_type(e.file_type), &e.name);
510                        out.text("\n");
511                    }
512                } else {
513                    let items: Vec<Item> = shown
514                        .iter()
515                        .map(|e| Item {
516                            name: e.name.clone(),
517                            style: style_for_type(e.file_type),
518                            suffix: if e.file_type == DT_DIR { "/" } else { "" },
519                        })
520                        .collect();
521                    print_columns(out, &items, width);
522                }
523            }
524            Err(dir_err) => match sys::stat(&path) {
525                Ok(st) if st.st_mode & S_IFMT != S_IFDIR => {
526                    if long {
527                        print_long(out, t, &path, 0);
528                    } else {
529                        out.styled(style_for_mode(st.st_mode), t);
530                        out.text("\n");
531                    }
532                }
533                _ => match sys::read_file(&path, 64 * 1024) {
534                    // Virtual scheme roots (e.g. /net) answer with plain text.
535                    Ok(d) if !d.is_empty() => {
536                        out.data(&d);
537                        if d.last() != Some(&b'\n') {
538                            out.text("\n");
539                        }
540                    }
541                    _ => path_err(out, "ls", &path, dir_err),
542                },
543            },
544        }
545    }
546}
547
548// ── Commands: reading files ─────────────────────────────────────────────────
549
550fn cmd_cat(sess: &mut Session, out: &mut Out, args: &[String]) {
551    if args.is_empty() {
552        return usage(out, "cat");
553    }
554    for a in args {
555        let path = sys::resolve(&sess.cwd, a);
556        let fd = match sys::open(&path, OpenFlags::READ) {
557            Ok(fd) => fd,
558            Err(e) => {
559                path_err(out, "cat", &path, e);
560                continue;
561            }
562        };
563        let mut buf = [0u8; 1024];
564        let mut last = b'\n';
565        let mut waits = 0u32;
566        loop {
567            if out.stop() {
568                break;
569            }
570            match call::read(fd, &mut buf) {
571                Ok(0) => break,
572                Ok(n) => {
573                    waits = 0;
574                    out.data(&buf[..n]);
575                    last = buf[n - 1];
576                }
577                Err(e) if e.to_errno() == EAGAIN && waits < 100 => {
578                    waits += 1;
579                    sys::sleep_ms(10);
580                }
581                Err(e) => {
582                    path_err(out, "cat", &path, e);
583                    break;
584                }
585            }
586        }
587        let _ = call::close(fd);
588        if last != b'\n' && !out.redirected() {
589            out.text("\n");
590        }
591    }
592}
593
594const READ_CAP: usize = 2 * 1024 * 1024;
595
596/// Parse `-n N` (or `-N`) for head/tail. Returns `(count, file)`.
597fn lines_args<'a>(args: &'a [String]) -> Option<(usize, &'a str)> {
598    let mut n = 10usize;
599    let mut file = None;
600    let mut i = 0;
601    while i < args.len() {
602        let a = args[i].as_str();
603        if a == "-n" {
604            i += 1;
605            n = args.get(i)?.parse().ok()?;
606        } else if a.len() > 1 && a.starts_with('-') && a[1..].chars().all(|c| c.is_ascii_digit()) {
607            n = a[1..].parse().ok()?;
608        } else {
609            file = Some(a);
610        }
611        i += 1;
612    }
613    file.map(|f| (n, f))
614}
615
616fn cmd_head(sess: &mut Session, out: &mut Out, args: &[String]) {
617    let Some((n, file)) = lines_args(args) else {
618        return usage(out, "head");
619    };
620    let path = sys::resolve(&sess.cwd, file);
621    match sys::read_file(&path, READ_CAP) {
622        Ok(d) => {
623            let mut count = 0;
624            let mut last = b'\n';
625            for line in d.split_inclusive(|&b| b == b'\n') {
626                if count >= n || out.stop() {
627                    break;
628                }
629                out.data(line);
630                last = line[line.len() - 1];
631                count += 1;
632            }
633            if last != b'\n' && !out.redirected() {
634                out.text("\n");
635            }
636        }
637        Err(e) => path_err(out, "head", &path, e),
638    }
639}
640
641fn cmd_tail(sess: &mut Session, out: &mut Out, args: &[String]) {
642    let Some((n, file)) = lines_args(args) else {
643        return usage(out, "tail");
644    };
645    let path = sys::resolve(&sess.cwd, file);
646    match sys::read_file(&path, READ_CAP) {
647        Ok(d) => {
648            let lines: Vec<&[u8]> = d.split_inclusive(|&b| b == b'\n').collect();
649            let skip = lines.len().saturating_sub(n);
650            for line in &lines[skip..] {
651                out.data(line);
652            }
653            if d.last().map_or(false, |&b| b != b'\n') && !out.redirected() && !d.is_empty() {
654                out.text("\n");
655            }
656        }
657        Err(e) => path_err(out, "tail", &path, e),
658    }
659}
660
661fn cmd_wc(sess: &mut Session, out: &mut Out, args: &[String]) {
662    if args.is_empty() {
663        return usage(out, "wc");
664    }
665    let mut totals = (0usize, 0usize, 0usize);
666    for a in args {
667        let path = sys::resolve(&sess.cwd, a);
668        match sys::read_file(&path, 64 * 1024 * 1024) {
669            Ok(d) => {
670                let lines = d.iter().filter(|&&b| b == b'\n').count();
671                let words = d
672                    .split(|b| b.is_ascii_whitespace())
673                    .filter(|w| !w.is_empty())
674                    .count();
675                totals = (totals.0 + lines, totals.1 + words, totals.2 + d.len());
676                let _ = write!(out, "{:>8} {:>8} {:>8} {}\n", lines, words, d.len(), a);
677            }
678            Err(e) => path_err(out, "wc", &path, e),
679        }
680    }
681    if args.len() > 1 {
682        let _ = write!(out, "{:>8} {:>8} {:>8} total\n", totals.0, totals.1, totals.2);
683    }
684}
685
686fn cmd_grep(sess: &mut Session, out: &mut Out, args: &[String]) {
687    let (flags, ops) = parse_flags(args);
688    if ops.len() < 2 {
689        return usage(out, "grep");
690    }
691    let icase = flags.contains('i');
692    let numbers = flags.contains('n');
693    let invert = flags.contains('v');
694    let pattern = if icase { ops[0].to_ascii_lowercase() } else { String::from(ops[0]) };
695    let files = &ops[1..];
696    let multi = files.len() > 1;
697
698    for f in files {
699        let path = sys::resolve(&sess.cwd, f);
700        let data = match sys::read_file(&path, READ_CAP) {
701            Ok(d) => d,
702            Err(e) => {
703                path_err(out, "grep", &path, e);
704                continue;
705            }
706        };
707        let text = String::from_utf8_lossy(&data);
708        for (i, line) in text.lines().enumerate() {
709            if out.stop() {
710                return;
711            }
712            let hay = if icase { line.to_ascii_lowercase() } else { String::from(line) };
713            let found = hay.contains(pattern.as_str());
714            if found == invert {
715                continue;
716            }
717            if multi {
718                out.styled(Style::Accent, f);
719                out.text(":");
720            }
721            if numbers {
722                out.styled(Style::Ok, &alloc::format!("{}", i + 1));
723                out.text(":");
724            }
725            if invert || pattern.is_empty() {
726                out.text(line);
727            } else {
728                // Highlight every match (to_ascii_lowercase keeps byte offsets).
729                let mut from = 0;
730                while let Some(p) = hay[from..].find(pattern.as_str()) {
731                    let s = from + p;
732                    let e = s + pattern.len();
733                    out.text(&line[from..s]);
734                    out.styled(Style::Error, &line[s..e]);
735                    from = e;
736                }
737                out.text(&line[from..]);
738            }
739            out.text("\n");
740        }
741    }
742}
743
744fn cmd_hexdump(sess: &mut Session, out: &mut Out, args: &[String]) {
745    let Some(file) = args.first() else {
746        return usage(out, "hexdump");
747    };
748    let offset: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
749    let len: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(256).min(64 * 1024);
750    let path = sys::resolve(&sess.cwd, file);
751    let data = match sys::read_file(&path, offset.saturating_add(len)) {
752        Ok(d) => d,
753        Err(e) => return path_err(out, "hexdump", &path, e),
754    };
755    let slice = data.get(offset..).unwrap_or(&[]);
756    for (row, chunk) in slice.chunks(16).enumerate() {
757        if out.stop() {
758            return;
759        }
760        out.style(Style::Dim);
761        let _ = write!(out, "{:08x}  ", offset + row * 16);
762        out.style(Style::Reset);
763        for i in 0..16 {
764            match chunk.get(i) {
765                Some(b) => {
766                    let _ = write!(out, "{:02x} ", b);
767                }
768                None => out.text("   "),
769            }
770            if i == 7 {
771                out.text(" ");
772            }
773        }
774        out.style(Style::Ok);
775        out.text(" |");
776        for &b in chunk {
777            let c = if (0x20..0x7f).contains(&b) { b as char } else { '.' };
778            let _ = out.write_char(c);
779        }
780        out.text("|");
781        out.style(Style::Reset);
782        out.text("\n");
783    }
784}
785
786fn cmd_stat(sess: &mut Session, out: &mut Out, args: &[String]) {
787    if args.is_empty() {
788        return usage(out, "stat");
789    }
790    for a in args {
791        let path = sys::resolve(&sess.cwd, a);
792        match sys::stat(&path) {
793            Ok(st) => {
794                let kind = match st.st_mode & S_IFMT {
795                    0o040000 => "directory",
796                    0o100000 => "regular file",
797                    0o120000 => "symbolic link",
798                    0o010000 => "FIFO",
799                    0o060000 => "block device",
800                    0o020000 => "character device",
801                    0o140000 => "socket",
802                    _ => "unknown",
803                };
804                let rows: [(&str, String); 10] = [
805                    ("File", path.clone()),
806                    ("Type", String::from(kind)),
807                    ("Size", alloc::format!("{} bytes ({} blocks)", st.st_size, st.st_blocks)),
808                    (
809                        "Mode",
810                        alloc::format!("{:04o} ({})", st.st_mode & 0o7777, sys::format_mode(st.st_mode)),
811                    ),
812                    ("Links", alloc::format!("{}", st.st_nlink)),
813                    ("Inode", alloc::format!("{}", st.st_ino)),
814                    ("Owner", alloc::format!("uid={} gid={}", st.st_uid, st.st_gid)),
815                    ("Access", sys::format_time_full(st.st_atime.tv_sec, st.st_atime.tv_nsec)),
816                    ("Modify", sys::format_time_full(st.st_mtime.tv_sec, st.st_mtime.tv_nsec)),
817                    ("Change", sys::format_time_full(st.st_ctime.tv_sec, st.st_ctime.tv_nsec)),
818                ];
819                for (k, v) in rows {
820                    out.styled(Style::Head, &alloc::format!("  {:<7}", k));
821                    out.text(&v);
822                    out.text("\n");
823                }
824            }
825            Err(e) => path_err(out, "stat", &path, e),
826        }
827    }
828}
829
830// ── tree ────────────────────────────────────────────────────────────────────
831
832struct TreeCtx {
833    all: bool,
834    max_depth: usize,
835    unicode: bool,
836    dirs: usize,
837    files: usize,
838}
839
840fn tree_walk(out: &mut Out, ctx: &mut TreeCtx, path: &str, prefix: &str, depth: usize) {
841    if depth >= ctx.max_depth {
842        return;
843    }
844    let Ok(entries) = sys::read_dir(path) else {
845        return;
846    };
847    let entries: Vec<&sys::DirEntry> = entries
848        .iter()
849        .filter(|e| ctx.all || !e.name.starts_with('.'))
850        .collect();
851    let n = entries.len();
852    for (i, e) in entries.iter().enumerate() {
853        if out.stop() {
854            return;
855        }
856        let last = i + 1 == n;
857        let (branch, cont) = match (ctx.unicode, last) {
858            (true, false) => ("\u{251c}\u{2500}\u{2500} ", "\u{2502}   "),
859            (true, true) => ("\u{2514}\u{2500}\u{2500} ", "    "),
860            (false, false) => ("|-- ", "|   "),
861            (false, true) => ("`-- ", "    "),
862        };
863        out.styled(Style::Dim, &alloc::format!("{}{}", prefix, branch));
864        out.styled(style_for_type(e.file_type), &e.name);
865        if e.file_type == DT_DIR {
866            out.text("/");
867            ctx.dirs += 1;
868        } else {
869            ctx.files += 1;
870        }
871        out.text("\n");
872        if e.file_type == DT_DIR {
873            let child = sys::join(path, &e.name);
874            let next_prefix = alloc::format!("{}{}", prefix, cont);
875            tree_walk(out, ctx, &child, &next_prefix, depth + 1);
876        }
877    }
878}
879
880fn cmd_tree(sess: &mut Session, out: &mut Out, args: &[String]) {
881    let mut ctx = TreeCtx {
882        all: false,
883        max_depth: 8,
884        unicode: out.color != ColorMode::None && !out.redirected(),
885        dirs: 0,
886        files: 0,
887    };
888    let mut target = ".";
889    let mut i = 0;
890    while i < args.len() {
891        match args[i].as_str() {
892            "-a" => ctx.all = true,
893            "-L" => {
894                i += 1;
895                match args.get(i).and_then(|s| s.parse().ok()) {
896                    Some(d) => ctx.max_depth = d,
897                    None => return usage(out, "tree"),
898                }
899            }
900            a => target = a,
901        }
902        i += 1;
903    }
904    let path = sys::resolve(&sess.cwd, target);
905    if !sys::is_dir(&path) {
906        out.error("tree", format_args!("{}: not a directory", path));
907        return;
908    }
909    out.styled(Style::Path, &path);
910    out.text("\n");
911    tree_walk(out, &mut ctx, &path, "", 0);
912    out.style(Style::Dim);
913    let _ = write!(out, "\n{} directories, {} files\n", ctx.dirs, ctx.files);
914    out.style(Style::Reset);
915}
916
917// ── Commands: modifying the filesystem ──────────────────────────────────────
918
919fn cmd_mkdir(sess: &mut Session, out: &mut Out, args: &[String]) {
920    let (flags, ops) = parse_flags(args);
921    if ops.is_empty() {
922        return usage(out, "mkdir");
923    }
924    let parents = flags.contains('p');
925    for o in ops {
926        let path = sys::resolve(&sess.cwd, o);
927        if parents {
928            let mut cur = String::new();
929            for comp in path.split('/').filter(|c| !c.is_empty()) {
930                cur.push('/');
931                cur.push_str(comp);
932                if sys::is_dir(&cur) {
933                    continue;
934                }
935                if let Err(e) = sys::mkdir(&cur, 0o755) {
936                    path_err(out, "mkdir", &cur, e);
937                    break;
938                }
939            }
940        } else if let Err(e) = sys::mkdir(&path, 0o755) {
941            path_err(out, "mkdir", &path, e);
942        }
943    }
944}
945
946fn cmd_touch(sess: &mut Session, out: &mut Out, args: &[String]) {
947    // `-t <unix-secs>` sets atime and mtime explicitly; otherwise "now".
948    let mut explicit: Option<i64> = None;
949    let mut files: Vec<&String> = Vec::new();
950    let mut i = 0;
951    while i < args.len() {
952        if args[i] == "-t" {
953            i += 1;
954            match args.get(i).and_then(|v| v.parse::<i64>().ok()) {
955                Some(v) => explicit = Some(v),
956                None => return usage(out, "touch"),
957            }
958        } else {
959            files.push(&args[i]);
960        }
961        i += 1;
962    }
963    if files.is_empty() {
964        return usage(out, "touch");
965    }
966    let times = explicit.map(|s| {
967        let t = strat9_syscall::data::TimeSpec { tv_sec: s, tv_nsec: 0 };
968        [t, t]
969    });
970    for a in files {
971        let path = sys::resolve(&sess.cwd, a);
972        if sys::stat(&path).is_err() {
973            match sys::open(&path, OpenFlags::WRITE | OpenFlags::CREATE) {
974                Ok(fd) => {
975                    let _ = call::close(fd);
976                }
977                Err(e) => {
978                    path_err(out, "touch", &path, e);
979                    continue;
980                }
981            }
982            if times.is_none() {
983                continue; // freshly created: already stamped "now"
984            }
985        }
986        if let Err(e) = sys::utimens(&path, times) {
987            path_err(out, "touch", &path, e);
988        }
989    }
990}
991
992fn cmd_date(_: &mut Session, out: &mut Out, _: &[String]) {
993    let t = sys::now();
994    let _ = write!(out, "{} UTC\n", sys::format_time_full(t.tv_sec, t.tv_nsec));
995}
996
997fn remove_tree(out: &mut Out, path: &str) -> Result<(), Error> {
998    if sys::is_dir(path) {
999        for e in sys::read_dir(path)? {
1000            if out.stop() {
1001                return Err(Error::Interrupted);
1002            }
1003            remove_tree(out, &sys::join(path, &e.name))?;
1004        }
1005        sys::rmdir(path).or_else(|_| sys::unlink(path))
1006    } else {
1007        sys::unlink(path)
1008    }
1009}
1010
1011fn cmd_rm(sess: &mut Session, out: &mut Out, args: &[String]) {
1012    let (flags, ops) = parse_flags(args);
1013    if ops.is_empty() {
1014        return usage(out, "rm");
1015    }
1016    let recursive = flags.contains('r') || flags.contains('R');
1017    let force = flags.contains('f');
1018    for o in ops {
1019        let path = sys::resolve(&sess.cwd, o);
1020        if path == "/" {
1021            out.error("rm", format_args!("refusing to remove '/'"));
1022            continue;
1023        }
1024        let res = if sys::is_dir(&path) {
1025            if recursive {
1026                remove_tree(out, &path)
1027            } else {
1028                out.error("rm", format_args!("{}: is a directory (use -r)", path));
1029                continue;
1030            }
1031        } else {
1032            sys::unlink(&path)
1033        };
1034        if let Err(e) = res {
1035            if !(force && e == Error::NotFound) {
1036                path_err(out, "rm", &path, e);
1037            }
1038        }
1039    }
1040}
1041
1042fn cmd_rmdir(sess: &mut Session, out: &mut Out, args: &[String]) {
1043    if args.is_empty() {
1044        return usage(out, "rmdir");
1045    }
1046    for a in args {
1047        let path = sys::resolve(&sess.cwd, a);
1048        if let Err(e) = sys::rmdir(&path) {
1049            path_err(out, "rmdir", &path, e);
1050        }
1051    }
1052}
1053
1054/// Stream-copy one file.
1055fn copy_file(out: &mut Out, src: &str, dst: &str) -> Result<(), Error> {
1056    let sfd = sys::open(src, OpenFlags::READ)?;
1057    let dfd = match sys::open(dst, OpenFlags::WRITE | OpenFlags::CREATE | OpenFlags::TRUNCATE) {
1058        Ok(fd) => fd,
1059        Err(e) => {
1060            let _ = call::close(sfd);
1061            return Err(e);
1062        }
1063    };
1064    let mut buf = [0u8; 1024];
1065    let mut res = Ok(());
1066    loop {
1067        if out.stop() {
1068            res = Err(Error::Interrupted);
1069            break;
1070        }
1071        match call::read(sfd, &mut buf) {
1072            Ok(0) => break,
1073            Ok(n) => {
1074                if !sys::write_all(dfd, &buf[..n]) {
1075                    res = Err(Error::IoError);
1076                    break;
1077                }
1078            }
1079            Err(e) => {
1080                res = Err(e);
1081                break;
1082            }
1083        }
1084    }
1085    let _ = call::close(sfd);
1086    let _ = call::close(dfd);
1087    res
1088}
1089
1090fn copy_tree(out: &mut Out, src: &str, dst: &str) -> Result<(), Error> {
1091    if sys::is_dir(src) {
1092        if !sys::is_dir(dst) {
1093            sys::mkdir(dst, 0o755)?;
1094        }
1095        for e in sys::read_dir(src)? {
1096            copy_tree(out, &sys::join(src, &e.name), &sys::join(dst, &e.name))?;
1097        }
1098        Ok(())
1099    } else {
1100        copy_file(out, src, dst)
1101    }
1102}
1103
1104/// `dst` itself, or `dst/<basename src>` if `dst` is an existing directory.
1105fn dest_path(src: &str, dst: String) -> String {
1106    if sys::is_dir(&dst) {
1107        sys::join(&dst, sys::basename(src))
1108    } else {
1109        dst
1110    }
1111}
1112
1113fn cmd_cp(sess: &mut Session, out: &mut Out, args: &[String]) {
1114    let (flags, ops) = parse_flags(args);
1115    if ops.len() != 2 {
1116        return usage(out, "cp");
1117    }
1118    let recursive = flags.contains('r') || flags.contains('R');
1119    let src = sys::resolve(&sess.cwd, ops[0]);
1120    let dst = dest_path(&src, sys::resolve(&sess.cwd, ops[1]));
1121    if sys::is_dir(&src) {
1122        if !recursive {
1123            return out.error("cp", format_args!("{}: is a directory (use -r)", src));
1124        }
1125        if dst == src || dst.starts_with(&alloc::format!("{}/", src.trim_end_matches('/'))) {
1126            return out.error("cp", format_args!("cannot copy a directory into itself"));
1127        }
1128    }
1129    match copy_tree(out, &src, &dst) {
1130        Ok(()) => {
1131            out.style(Style::Ok);
1132            let _ = write!(out, "{} -> {}", src, dst);
1133            out.style(Style::Reset);
1134            out.text("\n");
1135        }
1136        Err(e) => path_err(out, "cp", &dst, e),
1137    }
1138}
1139
1140fn cmd_mv(sess: &mut Session, out: &mut Out, args: &[String]) {
1141    let (_, ops) = parse_flags(args);
1142    if ops.len() != 2 {
1143        return usage(out, "mv");
1144    }
1145    let src = sys::resolve(&sess.cwd, ops[0]);
1146    let dst = dest_path(&src, sys::resolve(&sess.cwd, ops[1]));
1147    match sys::rename(&src, &dst) {
1148        Ok(()) => {}
1149        Err(Error::NotSupported) | Err(Error::NotImplemented) => {
1150            // Cross-mount move: copy then remove.
1151            let res = copy_tree(out, &src, &dst).and_then(|_| remove_tree(out, &src));
1152            if let Err(e) = res {
1153                path_err(out, "mv", &src, e);
1154            }
1155        }
1156        Err(e) => path_err(out, "mv", &src, e),
1157    }
1158}
1159
1160fn cmd_chmod(sess: &mut Session, out: &mut Out, args: &[String]) {
1161    if args.len() < 2 {
1162        return usage(out, "chmod");
1163    }
1164    let Ok(mode) = usize::from_str_radix(&args[0], 8) else {
1165        return out.error("chmod", format_args!("invalid octal mode '{}'", args[0]));
1166    };
1167    for a in &args[1..] {
1168        let path = sys::resolve(&sess.cwd, a);
1169        if let Err(e) = sys::chmod(&path, mode & 0o7777) {
1170            path_err(out, "chmod", &path, e);
1171        }
1172    }
1173}
1174
1175fn cmd_ln(sess: &mut Session, out: &mut Out, args: &[String]) {
1176    if args.len() != 2 {
1177        return usage(out, "ln");
1178    }
1179    let old = sys::resolve(&sess.cwd, &args[0]);
1180    let new = dest_path(&old, sys::resolve(&sess.cwd, &args[1]));
1181    if let Err(e) = sys::link(&old, &new) {
1182        path_err(out, "ln", &new, e);
1183    }
1184}
1185
1186fn write_text(sess: &Session, out: &mut Out, cmd: &str, args: &[String], append: bool) {
1187    if args.len() < 2 {
1188        return usage(out, cmd);
1189    }
1190    let path = sys::resolve(&sess.cwd, &args[0]);
1191    let text = args[1..].join(" ");
1192    let mode = if append { OpenFlags::APPEND } else { OpenFlags::TRUNCATE };
1193    match sys::open(&path, OpenFlags::WRITE | OpenFlags::CREATE | mode) {
1194        Ok(fd) => {
1195            if sys::write_all(fd, text.as_bytes()) {
1196                out.style(Style::Ok);
1197                let _ = write!(out, "{} bytes -> {}", text.len(), path);
1198                out.style(Style::Reset);
1199                out.text("\n");
1200            } else {
1201                out.error(cmd, format_args!("{}: write failed", path));
1202            }
1203            let _ = call::close(fd);
1204        }
1205        Err(e) => path_err(out, cmd, &path, e),
1206    }
1207}
1208
1209fn cmd_write(sess: &mut Session, out: &mut Out, args: &[String]) {
1210    write_text(sess, out, "write", args, false);
1211}
1212
1213fn cmd_append(sess: &mut Session, out: &mut Out, args: &[String]) {
1214    write_text(sess, out, "append", args, true);
1215}
1216
1217fn cmd_echo(_: &mut Session, out: &mut Out, args: &[String]) {
1218    let (newline, rest) = match args.first().map(|s| s.as_str()) {
1219        Some("-n") => (false, &args[1..]),
1220        _ => (true, args),
1221    };
1222    out.text(&rest.join(" "));
1223    if newline {
1224        out.text("\n");
1225    }
1226}
1227
1228// ── Commands: system / network / session ────────────────────────────────────
1229
1230fn cmd_df(_: &mut Session, out: &mut Out, _: &[String]) {
1231    let entries = match sys::read_dir("/") {
1232        Ok(e) => e,
1233        Err(e) => return path_err(out, "df", "/", e),
1234    };
1235    out.styled(Style::Head, &alloc::format!("{:<20} {}\n", "Mount", "Status"));
1236    for e in &entries {
1237        let path = sys::join("/", &e.name);
1238        out.style(Style::Dir);
1239        let _ = write!(out, "{:<20} ", path);
1240        out.style(Style::Reset);
1241        if sys::is_dir(&path) {
1242            out.styled(Style::Ok, "accessible\n");
1243        } else {
1244            out.styled(Style::Warn, "unavailable\n");
1245        }
1246    }
1247    out.style(Style::Dim);
1248    let _ = write!(out, "{} mount(s)\n", entries.len());
1249    out.style(Style::Reset);
1250}
1251
1252fn print_net_file(out: &mut Out, label: &str, path: &str) {
1253    let mut buf = [0u8; 128];
1254    let n = sys::read_text_file(path, &mut buf);
1255    out.styled(Style::Head, &alloc::format!("{:<6}", label));
1256    if n > 0 {
1257        out.data(&buf[..n]);
1258        if buf[n - 1] != b'\n' {
1259            out.text("\n");
1260        }
1261    } else {
1262        out.styled(Style::Dim, "n/a\n");
1263    }
1264}
1265
1266fn cmd_ip(_: &mut Session, out: &mut Out, _: &[String]) {
1267    print_net_file(out, "IP:", "/net/ip");
1268}
1269
1270fn cmd_net(_: &mut Session, out: &mut Out, _: &[String]) {
1271    print_net_file(out, "IP:", "/net/ip");
1272    print_net_file(out, "GW:", "/net/gateway");
1273    print_net_file(out, "DNS:", "/net/dns");
1274    print_net_file(out, "ROUTE:", "/net/route");
1275}
1276
1277fn cmd_history(sess: &mut Session, out: &mut Out, _: &[String]) {
1278    let lines: Vec<String> = sess
1279        .history()
1280        .map(|h| String::from_utf8_lossy(h).into_owned())
1281        .collect();
1282    for (i, l) in lines.iter().enumerate() {
1283        out.style(Style::Dim);
1284        let _ = write!(out, "{:>4}  ", i + 1);
1285        out.style(Style::Reset);
1286        out.text(l);
1287        out.text("\n");
1288    }
1289}
1290
1291fn cmd_term(sess: &mut Session, out: &mut Out, _: &[String]) {
1292    let name = if sess.term.name.is_empty() { "(not reported)" } else { sess.term.name.as_str() };
1293    let mode = match out.color {
1294        ColorMode::None => "off",
1295        ColorMode::Ansi => "16 colors",
1296        ColorMode::Xterm256 => "256 colors",
1297    };
1298    let _ = write!(
1299        out,
1300        "TERM={}  size={}x{}  color={}{}\n",
1301        name,
1302        sess.term.cols,
1303        sess.term.rows,
1304        mode,
1305        if sess.color_forced { " (forced)" } else { "" }
1306    );
1307    out.text("palette: ");
1308    for s in [
1309        Style::Dir,
1310        Style::Link,
1311        Style::Device,
1312        Style::Ok,
1313        Style::Warn,
1314        Style::Error,
1315        Style::Accent,
1316        Style::Head,
1317        Style::Dim,
1318    ] {
1319        out.styled(s, "\u{2588}\u{2588}");
1320        out.text(" ");
1321    }
1322    out.text("\n");
1323}
1324
1325fn cmd_color(sess: &mut Session, out: &mut Out, args: &[String]) {
1326    match args.first().map(|s| s.as_str()) {
1327        Some("auto") => {
1328            sess.color_forced = false;
1329            out.color = sess.term.detected;
1330        }
1331        Some("16") | Some("ansi") | Some("on") => {
1332            sess.color_forced = true;
1333            out.color = ColorMode::Ansi;
1334        }
1335        Some("256") => {
1336            sess.color_forced = true;
1337            out.color = ColorMode::Xterm256;
1338        }
1339        Some("off") | Some("none") => {
1340            sess.color_forced = true;
1341            out.color = ColorMode::None;
1342        }
1343        _ => return usage(out, "color"),
1344    }
1345    cmd_term(sess, out, &[]);
1346}
1347
1348fn cmd_clear(_: &mut Session, out: &mut Out, _: &[String]) {
1349    out.raw(b"\x1b[2J\x1b[H");
1350}