Skip to main content

strat9_kernel/shell/commands/vfs/
mod.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//! VFS management commands
24mod cat;
25mod cd;
26mod cp;
27mod df;
28mod ls;
29mod mkdir;
30mod mount;
31mod mv;
32mod rm;
33mod scheme;
34mod stat;
35mod touch;
36mod umount;
37mod write;
38
39use crate::{
40    shell::ShellError,
41    shell_println,
42    vfs::{self, scheme::DT_DIR, OpenFlags},
43};
44use alloc::{string::String, vec::Vec};
45use spin::Lazy;
46
47pub use cat::cmd_cat;
48pub use cd::cmd_cd;
49pub use cp::cmd_cp;
50pub use df::cmd_df;
51pub use ls::cmd_ls;
52pub use mkdir::cmd_mkdir;
53pub use mount::cmd_mount;
54pub use mv::cmd_mv;
55pub use rm::cmd_rm;
56pub use scheme::cmd_scheme;
57pub use stat::cmd_stat;
58pub use touch::cmd_touch;
59pub use umount::cmd_umount;
60pub use write::cmd_write;
61
62// ========== Shell CWD ==============================
63
64/// Current working directory for the chevron shell.
65///
66/// Stored as a global because `CommandRegistry` uses plain function pointers
67/// (no `&mut self`) so state cannot be threaded through call arguments.
68static SHELL_CWD: Lazy<crate::sync::SpinLock<String>> =
69    Lazy::new(|| crate::sync::SpinLock::new(String::from("/")));
70
71/// Read the current working directory.
72pub fn get_cwd() -> String {
73    SHELL_CWD.lock().clone()
74}
75
76/// Sets cwd.
77fn set_cwd(path: String) {
78    *SHELL_CWD.lock() = path;
79}
80
81/// Collapse `..`, `.` and redundant `/` in an absolute path.
82fn normalize_path(path: &str) -> String {
83    let mut parts: Vec<&str> = Vec::new();
84    for component in path.split('/') {
85        match component {
86            "" | "." => {}
87            ".." => {
88                let _ = parts.pop();
89            }
90            other => parts.push(other),
91        }
92    }
93    if parts.is_empty() {
94        return String::from("/");
95    }
96    let mut result = String::from("/");
97    for (i, part) in parts.iter().enumerate() {
98        if i > 0 {
99            result.push('/');
100        }
101        result.push_str(part);
102    }
103    result
104}
105
106/// Resolve `path` relative to the shell CWD.
107///
108/// - Empty or `""` => current directory.
109/// - Starts with `/` => treated as absolute (normalized).
110/// - Otherwise => joined with CWD and normalized.
111pub fn resolve_shell_path(path: &str) -> String {
112    if path.is_empty() {
113        return get_cwd();
114    }
115    if path.starts_with('/') {
116        return normalize_path(path);
117    }
118    let cwd = get_cwd();
119    let combined = if cwd.ends_with('/') {
120        alloc::format!("{}{}", cwd, path)
121    } else {
122        alloc::format!("{}/{}", cwd, path)
123    };
124    normalize_path(&combined)
125}
126
127// ========== cd ============================================================
128
129/// Change the shell working directory.
130pub(super) fn cmd_cd_impl(args: &[String]) -> Result<(), ShellError> {
131    let target = if args.is_empty() {
132        String::from("/")
133    } else {
134        resolve_shell_path(&args[0])
135    };
136
137    // Verify the path exists and is a directory.
138    match vfs::open(&target, OpenFlags::READ | OpenFlags::DIRECTORY) {
139        Ok(fd) => {
140            let _ = vfs::close(fd);
141            set_cwd(target);
142        }
143        Err(e) => {
144            let arg = args.first().map(|s| s.as_str()).unwrap_or("/");
145            shell_println!("cd: {}: {:?}", arg, e);
146        }
147    }
148    Ok(())
149}
150
151// ========== ls ============================================================
152
153/// List directory contents or mount points.
154pub(super) fn cmd_ls_impl(args: &[String]) -> Result<(), ShellError> {
155    let long = args.iter().any(|a| a == "-l");
156    let path = args
157        .iter()
158        .find(|a| !a.starts_with('-'))
159        .map(|a| resolve_shell_path(a))
160        .unwrap_or_else(|| resolve_shell_path(""));
161
162    // Root special-case: show mount points (until overlays are implemented).
163    if path == "/" && !long {
164        shell_println!("Mount points:");
165        for m in vfs::list_mounts() {
166            shell_println!("  {}", m);
167        }
168        return Ok(());
169    }
170
171    match vfs::open(&path, OpenFlags::READ | OpenFlags::DIRECTORY) {
172        Ok(fd) => {
173            match vfs::getdents(fd) {
174                Ok(entries) => {
175                    if entries.is_empty() {
176                        shell_println!("(empty)");
177                    } else if long {
178                        for e in &entries {
179                            let full_path = if path.ends_with('/') {
180                                alloc::format!("{}{}", path, e.name)
181                            } else {
182                                alloc::format!("{}/{}", path, e.name)
183                            };
184                            let suffix = if e.file_type == DT_DIR { "/" } else { "" };
185                            match vfs::stat_path(&full_path) {
186                                Ok(st) => {
187                                    let mode_str = format_mode(st.st_mode);
188                                    shell_println!(
189                                        "{} {:>3} {:>4} {:>4} {:>8} {} {}{}",
190                                        mode_str,
191                                        st.st_nlink,
192                                        st.st_uid,
193                                        st.st_gid,
194                                        st.st_size,
195                                        format_mtime(st.st_mtime),
196                                        e.name,
197                                        suffix
198                                    );
199                                }
200                                Err(_) => {
201                                    let type_char = if e.file_type == DT_DIR { 'd' } else { '-' };
202                                    shell_println!("  {}{}", type_char, e.name);
203                                }
204                            }
205                        }
206                    } else {
207                        for e in &entries {
208                            let type_char = if e.file_type == DT_DIR { 'd' } else { '-' };
209                            shell_println!("  {}{}", type_char, e.name);
210                        }
211                    }
212                }
213                Err(_) => {
214                    let mut buf = [0u8; 4096];
215                    match vfs::read(fd, &mut buf) {
216                        Ok(n) if n > 0 => {
217                            let s = core::str::from_utf8(&buf[..n]).unwrap_or("(binary)");
218                            shell_println!("{}", s.trim_end());
219                        }
220                        _ => shell_println!("(empty)"),
221                    }
222                }
223            }
224            let _ = vfs::close(fd);
225        }
226        Err(e) => shell_println!("ls: {}: {:?}", path, e),
227    }
228
229    Ok(())
230}
231
232/// Format st_mode into a 10-char permission string like `drwxr-xr-x`.
233fn format_mode(mode: u32) -> alloc::string::String {
234    let ft = mode & 0o170000;
235    let type_char = match ft {
236        0o040000 => 'd',
237        0o120000 => 'l',
238        0o060000 => 'b',
239        0o020000 => 'c',
240        0o010000 => 'p',
241        0o140000 => 's',
242        _ => '-',
243    };
244    let perms = mode & 0o7777;
245    let mut buf = [0u8; 10];
246    buf[0] = type_char as u8;
247    // Owner
248    buf[1] = if perms & 0o400 != 0 { b'r' } else { b'-' };
249    buf[2] = if perms & 0o200 != 0 { b'w' } else { b'-' };
250    buf[3] = if perms & 0o100 != 0 {
251        if perms & 0o4000 != 0 {
252            b's'
253        } else {
254            b'x'
255        }
256    } else {
257        if perms & 0o4000 != 0 {
258            b'S'
259        } else {
260            b'-'
261        }
262    };
263    // Group
264    buf[4] = if perms & 0o40 != 0 { b'r' } else { b'-' };
265    buf[5] = if perms & 0o20 != 0 { b'w' } else { b'-' };
266    buf[6] = if perms & 0o10 != 0 {
267        if perms & 0o2000 != 0 {
268            b's'
269        } else {
270            b'x'
271        }
272    } else {
273        if perms & 0o2000 != 0 {
274            b'S'
275        } else {
276            b'-'
277        }
278    };
279    // Other
280    buf[7] = if perms & 0o4 != 0 { b'r' } else { b'-' };
281    buf[8] = if perms & 0o2 != 0 { b'w' } else { b'-' };
282    buf[9] = if perms & 0o1 != 0 {
283        if perms & 0o1000 != 0 {
284            b't'
285        } else {
286            b'x'
287        }
288    } else {
289        if perms & 0o1000 != 0 {
290            b'T'
291        } else {
292            b'-'
293        }
294    };
295    unsafe { alloc::string::String::from_utf8_unchecked(buf.to_vec()) }
296}
297
298/// Format mtime (seconds since epoch) into `Mon DD HH:MM`.
299fn format_mtime(mtime: strat9_abi::data::TimeSpec) -> alloc::string::String {
300    let secs = mtime.tv_sec as u64;
301    let days = secs / 86400;
302    let rem = secs % 86400;
303    let hours = rem / 3600;
304    let mins = (rem % 3600) / 60;
305
306    // Simple day-of-year calculation (no leap year handling : good enough)
307    let month_days: &[(u32, &str)] = &[
308        (31, "Jan"),
309        (28, "Feb"),
310        (31, "Mar"),
311        (30, "Apr"),
312        (31, "May"),
313        (30, "Jun"),
314        (31, "Jul"),
315        (31, "Aug"),
316        (30, "Sep"),
317        (31, "Oct"),
318        (30, "Nov"),
319        (31, "Dec"),
320    ];
321    let mut day_of_year = (days % 365) as u32;
322    let mut month_idx = 0;
323    for &(days_in_month, _) in month_days {
324        if day_of_year < days_in_month {
325            break;
326        }
327        day_of_year -= days_in_month;
328        month_idx += 1;
329    }
330    if month_idx >= 12 {
331        month_idx = 11;
332        day_of_year = 30;
333    }
334    let month_name = month_days[month_idx].1;
335
336    alloc::format!(
337        "{} {:>2} {:02}:{:02}",
338        month_name,
339        day_of_year + 1,
340        hours,
341        mins
342    )
343}
344
345// ========== cat ==================================================
346
347/// Display file contents.
348/// Display file contents or piped input.
349///
350/// When invoked without arguments and pipe input is available,
351/// prints the piped data. Otherwise reads from the specified path.
352pub(super) fn cmd_cat_impl(args: &[String]) -> Result<(), ShellError> {
353    if let Some(piped) = crate::shell::output::take_pipe_input() {
354        if args.is_empty() {
355            let s = core::str::from_utf8(&piped).unwrap_or("(non-UTF8 data)");
356            crate::shell_print!("{}", s);
357            if !s.ends_with('\n') {
358                shell_println!();
359            }
360            return Ok(());
361        }
362    }
363
364    if args.is_empty() {
365        shell_println!("Usage: cat <path>");
366        return Ok(());
367    }
368
369    let path = resolve_shell_path(&args[0]);
370    match vfs::open(&path, OpenFlags::READ) {
371        Ok(fd) => {
372            let mut buf = [0u8; 1024];
373            loop {
374                match vfs::read(fd, &mut buf) {
375                    Ok(0) => break,
376                    Ok(n) => {
377                        let s = core::str::from_utf8(&buf[..n]).unwrap_or("(non-UTF8 data)");
378                        crate::shell_print!("{}", s);
379                    }
380                    Err(e) => {
381                        shell_println!("\nError reading file: {:?}", e);
382                        break;
383                    }
384                }
385            }
386            shell_println!("");
387            let _ = vfs::close(fd);
388        }
389        Err(e) => shell_println!("cat: {}: {:?}", path, e),
390    }
391    Ok(())
392}
393
394// ========== scheme ========================================
395
396/// List registered schemes.
397pub(super) fn cmd_scheme_impl(args: &[String]) -> Result<(), ShellError> {
398    if args.is_empty() || args[0] != "ls" {
399        shell_println!("Usage: scheme ls");
400        return Ok(());
401    }
402
403    shell_println!("Registered schemes:");
404    shell_println!("{:<14} {}", "Name", "Type");
405    shell_println!("======================================================");
406    for scheme in vfs::list_schemes() {
407        shell_println!("  {:<12} Kernel/IPC", scheme);
408    }
409    shell_println!("");
410    Ok(())
411}
412
413/// Performs the cmd mount operation.
414pub(super) fn cmd_mount_impl(args: &[String]) -> Result<(), ShellError> {
415    if args.is_empty() || args[0] == "ls" {
416        shell_println!("Mount points:");
417        for m in vfs::list_mounts() {
418            shell_println!("  {}", m);
419        }
420        shell_println!("");
421        shell_println!("Usage: mount <source> <target>");
422        return Ok(());
423    }
424    if args.len() != 2 {
425        shell_println!("Usage: mount <source> <target>");
426        return Ok(());
427    }
428
429    let source = resolve_shell_path(&args[0]);
430    let target = resolve_shell_path(&args[1]);
431
432    let (scheme, rel) = match vfs::resolve(&source) {
433        Ok(v) => v,
434        Err(e) => {
435            shell_println!("mount: source {} unavailable: {:?}", source, e);
436            return Ok(());
437        }
438    };
439    if !rel.is_empty() {
440        shell_println!("mount: source must be a mount root: {}", source);
441        return Ok(());
442    }
443
444    match vfs::mount(&target, scheme, None) {
445        Ok(()) => shell_println!("mount: {} mounted on {}", source, target),
446        Err(e) => shell_println!("mount: {} -> {} failed: {:?}", source, target, e),
447    }
448    Ok(())
449}
450
451/// Performs the cmd umount operation.
452pub(super) fn cmd_umount_impl(args: &[String]) -> Result<(), ShellError> {
453    if args.len() != 1 {
454        shell_println!("Usage: umount <target>");
455        return Ok(());
456    }
457
458    let target = resolve_shell_path(&args[0]);
459    match vfs::unmount(&target) {
460        Ok(()) => shell_println!("umount: {}", target),
461        Err(e) => shell_println!("umount: {}: {:?}", target, e),
462    }
463    Ok(())
464}
465
466// ========== mkdir ==================================================
467
468/// Create a new directory.
469pub(super) fn cmd_mkdir_impl(args: &[String]) -> Result<(), ShellError> {
470    if args.is_empty() {
471        shell_println!("Usage: mkdir <path>");
472        return Ok(());
473    }
474    let path = resolve_shell_path(&args[0]);
475    match vfs::mkdir(&path, 0o755) {
476        Ok(()) => shell_println!("mkdir: {}", path),
477        Err(e) => shell_println!("mkdir: {}: {:?}", path, e),
478    }
479    Ok(())
480}
481
482// ========== touch ==================================================
483
484/// Create a new empty file.
485pub(super) fn cmd_touch_impl(args: &[String]) -> Result<(), ShellError> {
486    if args.is_empty() {
487        shell_println!("Usage: touch <path>");
488        return Ok(());
489    }
490    let path = resolve_shell_path(&args[0]);
491    match vfs::create_file(&path, 0o644) {
492        Ok(()) => shell_println!("touch: {}", path),
493        Err(e) => shell_println!("touch: {}: {:?}", path, e),
494    }
495    Ok(())
496}
497
498// ========== rm ============================================================
499
500/// Remove a file or directory.
501pub(super) fn cmd_rm_impl(args: &[String]) -> Result<(), ShellError> {
502    if args.is_empty() {
503        shell_println!("Usage: rm <path>");
504        return Ok(());
505    }
506    let path = resolve_shell_path(&args[0]);
507    match vfs::unlink(&path) {
508        Ok(()) => shell_println!("rm: {}", path),
509        Err(e) => shell_println!("rm: {}: {:?}", path, e),
510    }
511    Ok(())
512}
513
514// ========== write ==================================================
515
516pub(super) fn cmd_write_impl(args: &[String]) -> Result<(), ShellError> {
517    if args.len() < 2 {
518        shell_println!("Usage: write <path> <text>");
519        return Ok(());
520    }
521    let path = resolve_shell_path(&args[0]);
522    let text = &args[1];
523
524    match vfs::open(&path, OpenFlags::WRITE | OpenFlags::CREATE) {
525        Ok(fd) => {
526            match vfs::write(fd, text.as_bytes()) {
527                Ok(n) => shell_println!("write: {} bytes -> {}", n, path),
528                Err(e) => shell_println!("write: {}: {:?}", path, e),
529            }
530            let _ = vfs::close(fd);
531        }
532        Err(e) => shell_println!("write: {}: {:?}", path, e),
533    }
534    Ok(())
535}
536
537// ========== stat ==================================================
538
539pub(super) fn cmd_stat_impl(args: &[String]) -> Result<(), ShellError> {
540    if args.is_empty() {
541        shell_println!("Usage: stat <path>");
542        return Err(ShellError::InvalidArguments);
543    }
544    let path = resolve_shell_path(&args[0]);
545    match vfs::stat_path(&path) {
546        Ok(st) => {
547            let ftype = match st.st_mode & 0xF000 {
548                0x4000 => "directory",
549                0x8000 => "regular file",
550                0xA000 => "symbolic link",
551                0x1000 => "FIFO",
552                0x6000 => "block device",
553                0x2000 => "character device",
554                _ => "unknown",
555            };
556            shell_println!("  File: {}", path);
557            shell_println!("  Type: {}", ftype);
558            shell_println!("  Size: {} bytes", st.st_size);
559            shell_println!("  Mode: {:04o}", st.st_mode & 0o7777);
560            shell_println!("  Links: {}", st.st_nlink);
561            shell_println!("  Inode: {}", st.st_ino);
562        }
563        Err(e) => shell_println!("stat: {}: {:?}", path, e),
564    }
565    Ok(())
566}
567
568// ========== cp ==================================================
569
570pub(super) fn cmd_cp_impl(args: &[String]) -> Result<(), ShellError> {
571    if args.len() < 2 {
572        shell_println!("Usage: cp <src> <dst>");
573        return Err(ShellError::InvalidArguments);
574    }
575    let src = resolve_shell_path(&args[0]);
576    let dst = resolve_shell_path(&args[1]);
577
578    let fd_src = vfs::open(&src, OpenFlags::READ).map_err(|e| {
579        shell_println!("cp: cannot open '{}': {:?}", src, e);
580        ShellError::ExecutionFailed
581    })?;
582    let data = match vfs::read_all(fd_src) {
583        Ok(d) => d,
584        Err(e) => {
585            let _ = vfs::close(fd_src);
586            shell_println!("cp: cannot read '{}': {:?}", src, e);
587            return Err(ShellError::ExecutionFailed);
588        }
589    };
590    let _ = vfs::close(fd_src);
591
592    let fd_dst = vfs::open(
593        &dst,
594        OpenFlags::WRITE | OpenFlags::CREATE | OpenFlags::TRUNCATE,
595    )
596    .map_err(|e| {
597        shell_println!("cp: cannot create '{}': {:?}", dst, e);
598        ShellError::ExecutionFailed
599    })?;
600    match vfs::write(fd_dst, &data) {
601        Ok(n) => shell_println!("cp: {} -> {} ({} bytes)", src, dst, n),
602        Err(e) => shell_println!("cp: write to '{}': {:?}", dst, e),
603    }
604    let _ = vfs::close(fd_dst);
605    Ok(())
606}
607
608// ========== mv ==================================================
609
610pub(super) fn cmd_mv_impl(args: &[String]) -> Result<(), ShellError> {
611    if args.len() < 2 {
612        shell_println!("Usage: mv <src> <dst>");
613        return Err(ShellError::InvalidArguments);
614    }
615    let src = resolve_shell_path(&args[0]);
616    let dst = resolve_shell_path(&args[1]);
617
618    match vfs::rename(&src, &dst) {
619        Ok(()) => {
620            shell_println!("mv: {} -> {}", src, dst);
621            return Ok(());
622        }
623        Err(crate::syscall::error::SyscallError::NotSupported)
624        | Err(crate::syscall::error::SyscallError::NotImplemented) => {
625            // Cross-mount: fallback to cp + rm
626        }
627        Err(e) => {
628            shell_println!("mv: {:?}", e);
629            return Err(ShellError::ExecutionFailed);
630        }
631    }
632
633    cmd_cp(args)?;
634    match vfs::unlink(&src) {
635        Ok(()) => shell_println!("mv: removed {}", src),
636        Err(e) => shell_println!("mv: could not remove source '{}': {:?}", src, e),
637    }
638    Ok(())
639}
640
641// ========== df ==================================================
642
643pub(super) fn cmd_df_impl(_args: &[String]) -> Result<(), ShellError> {
644    let mounts = vfs::list_mounts();
645    shell_println!("{:<20} {}", "Mount", "Status");
646    shell_println!("=======================================================================================================");
647    for m in &mounts {
648        let status = if vfs::open(m, OpenFlags::READ | OpenFlags::DIRECTORY)
649            .map(|fd| {
650                let _ = vfs::close(fd);
651            })
652            .is_ok()
653        {
654            "accessible"
655        } else {
656            "unavailable"
657        };
658        shell_println!("{:<20} {}", m, status);
659    }
660    shell_println!("{} mount(s)", mounts.len());
661    Ok(())
662}