Skip to main content

telnetd/
out.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//! Buffered, telnet-safe output with ANSI/256-color styling and `>` redirection.
24
25use crate::sys;
26use alloc::vec::Vec;
27use core::fmt;
28use strat9_syscall::call;
29
30/// How many colors the remote terminal can display.
31#[derive(Clone, Copy, PartialEq, Eq, Debug)]
32pub enum ColorMode {
33    /// Plain text (dumb terminal or user opted out).
34    None,
35    /// Classic 8/16 ANSI colors.
36    Ansi,
37    /// xterm 256-color palette.
38    Xterm256,
39}
40
41/// Semantic styles; mapped to escape sequences according to [`ColorMode`].
42#[derive(Clone, Copy, PartialEq, Eq)]
43pub enum Style {
44    Reset,
45    Dir,
46    File,
47    Link,
48    Device,
49    Error,
50    Ok,
51    Warn,
52    Dim,
53    Prompt,
54    Path,
55    Accent,
56    Head,
57}
58
59pub struct Out {
60    pub fd: usize,
61    buf: Vec<u8>,
62    /// Set once a network write failed: commands should stop producing output.
63    pub failed: bool,
64    pub color: ColorMode,
65    /// When set, output goes (raw) to this file fd instead of the socket.
66    redirect: Option<usize>,
67    /// Raw bytes received from the client while a command was running.
68    pub pending: Vec<u8>,
69    /// `Ctrl-C` seen while a command was running.
70    pub interrupted: bool,
71    pub peer_closed: bool,
72    poll_tick: u32,
73}
74
75impl Out {
76    pub fn new(fd: usize) -> Self {
77        Self {
78            fd,
79            buf: Vec::with_capacity(2048),
80            failed: false,
81            color: ColorMode::Ansi,
82            redirect: None,
83            pending: Vec::new(),
84            interrupted: false,
85            peer_closed: false,
86            poll_tick: 0,
87        }
88    }
89
90    pub fn set_redirect(&mut self, fd: Option<usize>) {
91        self.flush();
92        self.redirect = fd;
93    }
94
95    pub fn redirected(&self) -> bool {
96        self.redirect.is_some()
97    }
98
99    /// True if output should stop (client gone, write failed or Ctrl-C).
100    pub fn stop(&mut self) -> bool {
101        if self.failed || self.peer_closed {
102            return true;
103        }
104        self.poll_input();
105        self.interrupted
106    }
107
108    /// Cheaply look for `Ctrl-C` (and stash anything else as type-ahead).
109    fn poll_input(&mut self) {
110        self.poll_tick = self.poll_tick.wrapping_add(1);
111        if self.poll_tick % 8 != 0 {
112            return;
113        }
114        let mut tmp = [0u8; 64];
115        match call::read(self.fd, &mut tmp) {
116            Ok(0) => self.peer_closed = true,
117            Ok(n) => {
118                for &b in &tmp[..n] {
119                    if b == 0x03 {
120                        self.interrupted = true;
121                    } else if self.pending.len() < 1024 {
122                        self.pending.push(b);
123                    }
124                }
125            }
126            Err(_) => {}
127        }
128    }
129
130    pub fn flush(&mut self) {
131        if self.buf.is_empty() {
132            return;
133        }
134        let ok = match self.redirect {
135            Some(fd) => sys::write_all(fd, &self.buf),
136            None => sys::write_all(self.fd, &self.buf),
137        };
138        if !ok {
139            self.failed = true;
140        }
141        self.buf.clear();
142    }
143
144    fn push(&mut self, b: u8) {
145        self.buf.push(b);
146        if self.buf.len() >= 1536 {
147            self.flush();
148        }
149    }
150
151    /// Terminal text: `\n` becomes CRLF, 0xFF is IAC-escaped.
152    pub fn text(&mut self, s: &str) {
153        if self.failed {
154            return;
155        }
156        for &b in s.as_bytes() {
157            self.byte(b);
158        }
159    }
160
161    fn byte(&mut self, b: u8) {
162        if self.redirect.is_some() {
163            self.push(b);
164            return;
165        }
166        match b {
167            b'\n' => {
168                self.push(b'\r');
169                self.push(b'\n');
170            }
171            255 => {
172                self.push(255);
173                self.push(255);
174            }
175            _ => self.push(b),
176        }
177    }
178
179    /// Raw protocol bytes (telnet commands, escape sequences): no translation.
180    pub fn raw(&mut self, bytes: &[u8]) {
181        if self.failed {
182            return;
183        }
184        for &b in bytes {
185            self.push(b);
186        }
187    }
188
189    /// File content: control characters (including ESC) are neutralised so a
190    /// binary file cannot corrupt the terminal. Redirected output is raw.
191    pub fn data(&mut self, bytes: &[u8]) {
192        if self.failed {
193            return;
194        }
195        if self.redirect.is_some() {
196            for &b in bytes {
197                self.push(b);
198            }
199            return;
200        }
201        for &b in bytes {
202            match b {
203                b'\n' | b'\t' | 0x20..=0x7e | 0x80..=0xfe => self.byte(b),
204                b'\r' => {}
205                _ => self.byte(b'.'),
206            }
207        }
208    }
209
210    pub fn style(&mut self, s: Style) {
211        if self.redirect.is_some() || self.color == ColorMode::None {
212            return;
213        }
214        let c256 = self.color == ColorMode::Xterm256;
215        let seq: &str = match (s, c256) {
216            (Style::Reset, _) => "\x1b[0m",
217            (Style::Dir, false) => "\x1b[1;34m",
218            (Style::Dir, true) => "\x1b[1;38;5;75m",
219            (Style::File, _) => "\x1b[0m",
220            (Style::Link, false) => "\x1b[36m",
221            (Style::Link, true) => "\x1b[38;5;44m",
222            (Style::Device, false) => "\x1b[33m",
223            (Style::Device, true) => "\x1b[38;5;215m",
224            (Style::Error, false) => "\x1b[1;31m",
225            (Style::Error, true) => "\x1b[1;38;5;203m",
226            (Style::Ok, false) => "\x1b[32m",
227            (Style::Ok, true) => "\x1b[38;5;114m",
228            (Style::Warn, false) => "\x1b[33m",
229            (Style::Warn, true) => "\x1b[38;5;221m",
230            (Style::Dim, false) => "\x1b[2m",
231            (Style::Dim, true) => "\x1b[38;5;245m",
232            (Style::Prompt, false) => "\x1b[1;32m",
233            (Style::Prompt, true) => "\x1b[1;38;5;114m",
234            (Style::Path, false) => "\x1b[1;34m",
235            (Style::Path, true) => "\x1b[1;38;5;111m",
236            (Style::Accent, false) => "\x1b[1;35m",
237            (Style::Accent, true) => "\x1b[1;38;5;177m",
238            (Style::Head, false) => "\x1b[1;33m",
239            (Style::Head, true) => "\x1b[1;38;5;221m",
240        };
241        self.raw(seq.as_bytes());
242    }
243
244    /// Print `s` in style `st`, then reset.
245    pub fn styled(&mut self, st: Style, s: &str) {
246        self.style(st);
247        self.text(s);
248        self.style(Style::Reset);
249    }
250
251    /// `cmd: detail` error line in red.
252    pub fn error(&mut self, cmd: &str, detail: fmt::Arguments<'_>) {
253        // Errors always go to the terminal, even under `> file`.
254        self.flush();
255        let saved = self.redirect.take();
256        self.style(Style::Error);
257        let _ = fmt::write(self, format_args!("{}: ", cmd));
258        let _ = fmt::write(self, detail);
259        self.style(Style::Reset);
260        self.text("\n");
261        self.flush();
262        self.redirect = saved;
263    }
264}
265
266impl fmt::Write for Out {
267    fn write_str(&mut self, s: &str) -> fmt::Result {
268        self.text(s);
269        Ok(())
270    }
271}