Skip to main content

telnetd/
sys.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//! Thin userspace helpers over the Strat9 VFS syscalls used by telnetd.
24
25use alloc::{string::String, vec::Vec};
26use strat9_syscall::{
27    call,
28    data::{FileStat, TimeSpec},
29    dirent::DirentIter,
30    error::Error,
31    flag::OpenFlags,
32    number,
33};
34
35pub const EAGAIN: usize = 11;
36pub const ECONNRESET: usize = 104;
37
38pub const S_IFMT: u32 = 0o170000;
39pub const S_IFDIR: u32 = 0o040000;
40pub const S_IFLNK: u32 = 0o120000;
41
42pub const DT_DIR: u8 = 4;
43pub const DT_LNK: u8 = 10;
44
45pub type Res<T> = Result<T, Error>;
46
47pub fn log(msg: &str) {
48    let _ = call::debug_log(msg.as_bytes());
49}
50
51pub fn sleep_ms(ms: u64) {
52    let req = TimeSpec {
53        tv_sec: (ms / 1000) as i64,
54        tv_nsec: ((ms % 1000) * 1_000_000) as i64,
55    };
56    // SAFETY: `req` is a valid TimeSpec for the duration of the call; the
57    // remaining-time pointer is optional (null).
58    let _ = unsafe {
59        strat9_syscall::syscall2(number::SYS_NANOSLEEP, &req as *const TimeSpec as usize, 0)
60    };
61}
62
63/// Write the whole buffer, retrying on `EAGAIN` (socket send window full).
64pub fn write_all(fd: usize, data: &[u8]) -> bool {
65    let mut off = 0usize;
66    let mut retries = 0u32;
67    while off < data.len() {
68        match call::write(fd, &data[off..]) {
69            Ok(0) => return false,
70            Ok(n) => {
71                off += n;
72                retries = 0;
73            }
74            Err(e) => {
75                if e.to_errno() == EAGAIN {
76                    retries += 1;
77                    if retries > 500 {
78                        return false;
79                    }
80                    sleep_ms(10);
81                    continue;
82                }
83                return false;
84            }
85        }
86    }
87    true
88}
89
90// ── Path helpers ────────────────────────────────────────────────────────────
91
92/// Collapse `.`, `..` and duplicate `/` in an absolute path.
93pub fn normalize(path: &str) -> String {
94    let mut parts: Vec<&str> = Vec::new();
95    for c in path.split('/') {
96        match c {
97            "" | "." => {}
98            ".." => {
99                let _ = parts.pop();
100            }
101            other => parts.push(other),
102        }
103    }
104    let mut out = String::from("/");
105    for (i, p) in parts.iter().enumerate() {
106        if i > 0 {
107            out.push('/');
108        }
109        out.push_str(p);
110    }
111    out
112}
113
114/// Resolve `path` against `cwd` into a normalized absolute path.
115pub fn resolve(cwd: &str, path: &str) -> String {
116    if path.is_empty() {
117        return normalize(cwd);
118    }
119    if path.starts_with('/') {
120        return normalize(path);
121    }
122    let mut joined = String::from(cwd);
123    if !joined.ends_with('/') {
124        joined.push('/');
125    }
126    joined.push_str(path);
127    normalize(&joined)
128}
129
130/// Last component of a path (`/` for the root).
131pub fn basename(path: &str) -> &str {
132    let t = path.trim_end_matches('/');
133    match t.rfind('/') {
134        Some(i) if i + 1 < t.len() => &t[i + 1..],
135        _ if t.is_empty() => "/",
136        _ => t,
137    }
138}
139
140pub fn join(dir: &str, name: &str) -> String {
141    let mut s = String::from(dir);
142    if !s.ends_with('/') {
143        s.push('/');
144    }
145    s.push_str(name);
146    s
147}
148
149// ── VFS wrappers ────────────────────────────────────────────────────────────
150
151pub fn open(path: &str, flags: OpenFlags) -> Res<usize> {
152    call::openat(0, path, flags.bits() as usize, 0)
153}
154
155pub fn stat(path: &str) -> Res<FileStat> {
156    let mut st = FileStat::zeroed();
157    call::stat(path, &mut st)?;
158    Ok(st)
159}
160
161pub fn is_dir(path: &str) -> bool {
162    match stat(path) {
163        Ok(st) => st.st_mode & S_IFMT == S_IFDIR,
164        Err(_) => match open(path, OpenFlags::READ | OpenFlags::DIRECTORY) {
165            Ok(fd) => {
166                let _ = call::close(fd);
167                true
168            }
169            Err(_) => false,
170        },
171    }
172}
173
174pub fn mkdir(path: &str, mode: usize) -> Res<()> {
175    // SAFETY: pointer/length describe a live `&str` for the whole call.
176    unsafe { strat9_syscall::syscall3(number::SYS_MKDIR, path.as_ptr() as usize, path.len(), mode) }
177        .map(|_| ())
178}
179
180pub fn unlink(path: &str) -> Res<()> {
181    // SAFETY: pointer/length describe a live `&str` for the whole call.
182    unsafe { strat9_syscall::syscall2(number::SYS_UNLINK, path.as_ptr() as usize, path.len()) }
183        .map(|_| ())
184}
185
186pub fn rmdir(path: &str) -> Res<()> {
187    // SAFETY: pointer/length describe a live `&str` for the whole call.
188    unsafe { strat9_syscall::syscall2(number::SYS_RMDIR, path.as_ptr() as usize, path.len()) }
189        .map(|_| ())
190}
191
192pub fn chmod(path: &str, mode: usize) -> Res<()> {
193    // SAFETY: pointer/length describe a live `&str` for the whole call.
194    unsafe { strat9_syscall::syscall3(number::SYS_CHMOD, path.as_ptr() as usize, path.len(), mode) }
195        .map(|_| ())
196}
197
198pub fn link(old: &str, new: &str) -> Res<()> {
199    // SAFETY: both pointer/length pairs describe live `&str`s for the call.
200    unsafe {
201        strat9_syscall::syscall4(
202            number::SYS_LINK,
203            old.as_ptr() as usize,
204            old.len(),
205            new.as_ptr() as usize,
206            new.len(),
207        )
208    }
209    .map(|_| ())
210}
211
212/// Set atime/mtime. `None` = both "now" (like `touch`).
213pub fn utimens(path: &str, times: Option<[TimeSpec; 2]>) -> Res<()> {
214    let ptr = times.as_ref().map_or(0, |t| t.as_ptr() as usize);
215    // SAFETY: `path` and (when present) `times` outlive the call; the kernel
216    // validates both user pointers.
217    unsafe {
218        strat9_syscall::syscall4(number::SYS_UTIMENSAT, path.as_ptr() as usize, path.len(), ptr, 0)
219    }
220    .map(|_| ())
221}
222
223/// Wall-clock time (`CLOCK_REALTIME`).
224pub fn now() -> TimeSpec {
225    let mut ts = TimeSpec { tv_sec: 0, tv_nsec: 0 };
226    let _ = call::clock_gettime(0, &mut ts);
227    ts
228}
229
230pub fn rename(old: &str, new: &str) -> Res<()> {
231    // SAFETY: both pointer/length pairs describe live `&str`s for the call.
232    unsafe {
233        strat9_syscall::syscall4(
234            number::SYS_RENAME,
235            old.as_ptr() as usize,
236            old.len(),
237            new.as_ptr() as usize,
238            new.len(),
239        )
240    }
241    .map(|_| ())
242}
243
244/// One decoded directory entry.
245pub struct DirEntry {
246    pub name: String,
247    pub file_type: u8,
248}
249
250/// List a directory (entries `.`/`..` removed, sorted by name).
251pub fn read_dir(path: &str) -> Res<Vec<DirEntry>> {
252    let fd = open(path, OpenFlags::READ | OpenFlags::DIRECTORY)?;
253    let mut buf = alloc::vec![0u8; 32 * 1024];
254    let res = call::getdents(fd, &mut buf);
255    let _ = call::close(fd);
256    let n = res?;
257    let mut entries: Vec<DirEntry> = DirentIter::new(&buf, n)
258        .filter_map(|d| {
259            let name = core::str::from_utf8(d.name()).ok()?;
260            if name == "." || name == ".." {
261                return None;
262            }
263            Some(DirEntry {
264                name: String::from(name),
265                file_type: d.type_,
266            })
267        })
268        .collect();
269    entries.sort_by(|a, b| a.name.cmp(&b.name));
270    Ok(entries)
271}
272
273/// Read up to `cap` bytes of a file.
274pub fn read_file(path: &str, cap: usize) -> Res<Vec<u8>> {
275    let fd = open(path, OpenFlags::READ)?;
276    let mut data = Vec::new();
277    let mut chunk = [0u8; 1024];
278    let mut empty_retries = 0u32;
279    loop {
280        if data.len() >= cap {
281            break;
282        }
283        match call::read(fd, &mut chunk) {
284            Ok(0) => break,
285            Ok(n) => {
286                empty_retries = 0;
287                let take = n.min(cap - data.len());
288                data.extend_from_slice(&chunk[..take]);
289            }
290            Err(e) if e.to_errno() == EAGAIN && empty_retries < 100 => {
291                empty_retries += 1;
292                sleep_ms(10);
293            }
294            Err(e) => {
295                let _ = call::close(fd);
296                return Err(e);
297            }
298        }
299    }
300    let _ = call::close(fd);
301    Ok(data)
302}
303
304/// Read a small text file, returning the byte count (0 on any error).
305pub fn read_text_file(path: &str, out: &mut [u8]) -> usize {
306    let fd = match open(path, OpenFlags::READ) {
307        Ok(fd) => fd,
308        Err(_) => return 0,
309    };
310    let n = call::read(fd, out).unwrap_or(0);
311    let _ = call::close(fd);
312    n
313}
314
315// ── Date formatting (UTC) ───────────────────────────────────────────────────
316
317/// Convert days since 1970-01-01 to (year, month 1-12, day 1-31).
318pub fn civil_from_days(days: i64) -> (i64, u32, u32) {
319    let z = days + 719_468;
320    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
321    let doe = (z - era * 146_097) as u64;
322    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
323    let y = yoe as i64 + era * 400;
324    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
325    let mp = (5 * doy + 2) / 153;
326    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
327    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
328    (if m <= 2 { y + 1 } else { y }, m, d)
329}
330
331/// `YYYY-MM-DD HH:MM` for a unix timestamp.
332pub fn format_time(secs: i64) -> String {
333    let days = secs.div_euclid(86_400);
334    let rem = secs.rem_euclid(86_400);
335    let (y, m, d) = civil_from_days(days);
336    alloc::format!("{:04}-{:02}-{:02} {:02}:{:02}", y, m, d, rem / 3600, (rem % 3600) / 60)
337}
338
339/// `YYYY-MM-DD HH:MM:SS.nnnnnnnnn` (UTC) for a timestamp.
340pub fn format_time_full(secs: i64, nsec: i64) -> String {
341    let days = secs.div_euclid(86_400);
342    let rem = secs.rem_euclid(86_400);
343    let (y, m, d) = civil_from_days(days);
344    alloc::format!(
345        "{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09}",
346        y,
347        m,
348        d,
349        rem / 3600,
350        (rem % 3600) / 60,
351        rem % 60,
352        nsec.clamp(0, 999_999_999)
353    )
354}
355
356/// `drwxr-xr-x` style mode string.
357pub fn format_mode(mode: u32) -> String {
358    let t = match mode & S_IFMT {
359        0o040000 => 'd',
360        0o120000 => 'l',
361        0o060000 => 'b',
362        0o020000 => 'c',
363        0o010000 => 'p',
364        0o140000 => 's',
365        _ => '-',
366    };
367    let mut s = String::with_capacity(10);
368    s.push(t);
369    for (shift, specials) in [(6u32, 0o4000u32), (3, 0o2000), (0, 0o1000)] {
370        let bits = (mode >> shift) & 7;
371        s.push(if bits & 4 != 0 { 'r' } else { '-' });
372        s.push(if bits & 2 != 0 { 'w' } else { '-' });
373        let x = bits & 1 != 0;
374        let sp = mode & specials != 0;
375        s.push(match (x, sp, shift) {
376            (true, true, 0) => 't',
377            (false, true, 0) => 'T',
378            (true, true, _) => 's',
379            (false, true, _) => 'S',
380            (true, false, _) => 'x',
381            _ => '-',
382        });
383    }
384    s
385}
386
387/// Short English description of an error.
388pub fn err_text(e: Error) -> String {
389    alloc::format!("{} (errno {})", e, e.to_errno())
390}