1use crate::{
27 out::{ColorMode, Out, Style},
28 shell, sys,
29};
30use alloc::{string::String, vec::Vec};
31
32const IAC: u8 = 255;
33const DONT: u8 = 254;
34const DO: u8 = 253;
35const WONT: u8 = 252;
36const WILL: u8 = 251;
37const SB: u8 = 250;
38const SE: u8 = 240;
39
40const OPT_ECHO: u8 = 1;
41const OPT_SGA: u8 = 3;
42const OPT_TTYPE: u8 = 24;
43const OPT_NAWS: u8 = 31;
44
45const TTYPE_IS: u8 = 0;
46const TTYPE_SEND: u8 = 1;
47
48const NEGOTIATION: [u8; 15] = [
50 IAC, WILL, OPT_ECHO, IAC, WILL, OPT_SGA, IAC, DO, OPT_SGA, IAC, DO, OPT_NAWS, IAC, DO, OPT_TTYPE, ];
56
57pub fn probe_connect(fd: usize) -> bool {
62 match strat9_syscall::call::write(fd, &NEGOTIATION) {
63 Ok(0) => false,
64 Ok(n) => n >= NEGOTIATION.len() || sys::write_all(fd, &NEGOTIATION[n..]),
65 Err(_) => false,
66 }
67}
68
69const HISTORY_MAX: usize = 64;
70const LINE_MAX: usize = 1024;
71
72#[derive(Clone, Copy, PartialEq, Eq)]
73enum Parser {
74 Normal,
75 Iac,
76 Neg(u8),
77 Sb,
78 SbIac,
79 AfterCr,
80 Esc,
81 Csi,
82 Ss3,
83}
84
85pub struct Term {
87 pub name: String,
88 pub cols: u16,
89 pub rows: u16,
90 pub detected: ColorMode,
92}
93
94pub struct Session {
95 pub connected: bool,
96 parser: Parser,
97 sb: Vec<u8>,
98 csi: Vec<u8>,
99 line: Vec<u8>,
100 pos: usize,
101 history: Vec<Vec<u8>>,
102 hist_idx: usize,
103 saved_line: Vec<u8>,
104 pub term: Term,
105 pub cwd: String,
106 pub color_forced: bool,
108}
109
110fn color_from_term(name: &str) -> ColorMode {
112 let n = name.to_ascii_lowercase();
113 if n.is_empty() {
114 return ColorMode::Ansi;
115 }
116 if n.contains("dumb") || n == "unknown" || n.contains("vt52") || n.contains("network") {
117 return ColorMode::None;
118 }
119 if n.contains("256") || n.contains("truecolor") || n.contains("direct") || n.contains("kitty")
120 || n.contains("alacritty") || n.contains("wezterm") || n.contains("foot")
121 || n.contains("tmux") || n.contains("screen-256")
122 {
123 return ColorMode::Xterm256;
124 }
125 ColorMode::Ansi
126}
127
128impl Session {
129 pub fn new() -> Self {
130 Self {
131 connected: false,
132 parser: Parser::Normal,
133 sb: Vec::new(),
134 csi: Vec::new(),
135 line: Vec::new(),
136 pos: 0,
137 history: Vec::new(),
138 hist_idx: 0,
139 saved_line: Vec::new(),
140 term: Term {
141 name: String::new(),
142 cols: 80,
143 rows: 24,
144 detected: ColorMode::Ansi,
145 },
146 cwd: String::from("/"),
147 color_forced: false,
148 }
149 }
150
151 pub fn reset(&mut self) {
153 self.connected = false;
154 self.parser = Parser::Normal;
155 self.sb.clear();
156 self.csi.clear();
157 self.line.clear();
158 self.pos = 0;
159 self.history.clear();
160 self.hist_idx = 0;
161 self.saved_line.clear();
162 self.term = Term {
163 name: String::new(),
164 cols: 80,
165 rows: 24,
166 detected: ColorMode::Ansi,
167 };
168 self.cwd = String::from("/");
169 self.color_forced = false;
170 }
171
172 pub fn history(&self) -> impl Iterator<Item = &[u8]> {
173 self.history.iter().map(|h| h.as_slice())
174 }
175
176 pub fn send_negotiation(&self, out: &mut Out) {
180 out.raw(&NEGOTIATION);
181 out.flush();
182 }
183
184 pub fn send_banner(&mut self, out: &mut Out) {
185 out.style(Style::Accent);
186 out.text("\nStrat9-OS telnet shell");
187 out.style(Style::Reset);
188 out.style(Style::Dim);
189 out.text(" (dev/test console)\n");
190 out.style(Style::Reset);
191 out.text("Type ");
192 out.styled(Style::Ok, "help");
193 out.text(" for commands. Tab completes, \u{2191}/\u{2193} browse history, Ctrl-C cancels.\n\n");
194 self.draw_prompt(out);
195 out.flush();
196 }
197
198 fn draw_prompt(&self, out: &mut Out) {
201 out.style(Style::Prompt);
202 out.text("strat9");
203 out.style(Style::Reset);
204 out.text(":");
205 out.styled(Style::Path, &self.cwd);
206 out.styled(Style::Prompt, "# ");
207 }
208
209 fn redraw(&self, out: &mut Out) {
211 out.raw(b"\r");
212 self.draw_prompt(out);
213 out.raw(&self.line);
214 out.raw(b"\x1b[K");
215 let after = chars_in(&self.line[self.pos..]);
216 if after > 0 {
217 let seq = alloc::format!("\x1b[{}D", after);
218 out.raw(seq.as_bytes());
219 }
220 out.flush();
221 }
222
223 fn new_prompt(&mut self, out: &mut Out) {
224 self.line.clear();
225 self.pos = 0;
226 self.draw_prompt(out);
227 out.flush();
228 }
229
230 pub fn feed(&mut self, out: &mut Out, bytes: &[u8]) -> bool {
234 for &b in bytes {
235 if !self.feed_byte(out, b) {
236 return false;
237 }
238 }
239 self.apply_color(out);
240 out.flush();
241 true
242 }
243
244 fn feed_byte(&mut self, out: &mut Out, b: u8) -> bool {
245 match self.parser {
246 Parser::Iac => {
247 self.parser = match b {
248 WILL | WONT | DO | DONT => Parser::Neg(b),
249 SB => {
250 self.sb.clear();
251 Parser::Sb
252 }
253 IAC => {
254 self.insert(out, IAC);
255 Parser::Normal
256 }
257 _ => Parser::Normal, };
259 return true;
260 }
261 Parser::Neg(cmd) => {
262 self.parser = Parser::Normal;
263 self.negotiate(out, cmd, b);
264 return true;
265 }
266 Parser::Sb => {
267 if b == IAC {
268 self.parser = Parser::SbIac;
269 } else if self.sb.len() < 128 {
270 self.sb.push(b);
271 }
272 return true;
273 }
274 Parser::SbIac => {
275 if b == SE {
276 self.parser = Parser::Normal;
277 self.subnegotiation();
278 } else {
279 if b == IAC && self.sb.len() < 128 {
280 self.sb.push(IAC);
281 }
282 self.parser = Parser::Sb;
283 }
284 return true;
285 }
286 Parser::AfterCr => {
287 self.parser = Parser::Normal;
288 if b == b'\n' || b == 0 {
289 return true; }
291 }
292 Parser::Esc => {
293 self.parser = match b {
294 b'[' => {
295 self.csi.clear();
296 Parser::Csi
297 }
298 b'O' => Parser::Ss3,
299 _ => Parser::Normal,
300 };
301 return true;
302 }
303 Parser::Csi => {
304 if (0x40..=0x7e).contains(&b) {
305 self.parser = Parser::Normal;
306 self.csi_key(out, b);
307 } else if self.csi.len() < 16 {
308 self.csi.push(b);
309 }
310 return true;
311 }
312 Parser::Ss3 => {
313 self.parser = Parser::Normal;
314 self.csi.clear();
315 self.csi_key(out, b);
316 return true;
317 }
318 Parser::Normal => {}
319 }
320
321 match b {
322 IAC => self.parser = Parser::Iac,
323 0x1b => self.parser = Parser::Esc,
324 b'\r' => {
325 self.parser = Parser::AfterCr;
326 return self.submit(out);
327 }
328 b'\n' => return self.submit(out),
329 0x08 | 0x7f => self.backspace(out),
330 0x03 => {
331 out.styled(Style::Dim, "^C");
333 out.text("\n");
334 self.new_prompt(out);
335 }
336 0x04 => {
337 if self.line.is_empty() {
339 out.text("logout\n");
340 return false;
341 }
342 self.delete(out);
343 }
344 0x01 => {
345 self.pos = 0;
346 self.redraw(out);
347 }
348 0x05 => {
349 self.pos = self.line.len();
350 self.redraw(out);
351 }
352 0x0b => {
353 self.line.truncate(self.pos);
354 self.redraw(out);
355 }
356 0x15 => {
357 self.line.drain(..self.pos);
358 self.pos = 0;
359 self.redraw(out);
360 }
361 0x17 => self.kill_word(out),
362 0x0c => {
363 out.raw(b"\x1b[2J\x1b[H");
364 self.redraw(out);
365 }
366 b'\t' => self.tab(out),
367 0x20..=0x7e | 0x80..=0xfe => self.insert(out, b),
368 _ => {}
369 }
370 true
371 }
372
373 fn negotiate(&mut self, out: &mut Out, cmd: u8, opt: u8) {
374 match (cmd, opt) {
375 (DO, OPT_ECHO) | (DO, OPT_SGA) | (WILL, OPT_SGA) | (WILL, OPT_NAWS) => {}
377 (DONT, _) | (WONT, _) => {}
378 (WILL, OPT_TTYPE) => {
379 out.raw(&[IAC, SB, OPT_TTYPE, TTYPE_SEND, IAC, SE]);
380 out.flush();
381 }
382 (DO, o) => {
384 out.raw(&[IAC, WONT, o]);
385 out.flush();
386 }
387 (WILL, o) => {
388 out.raw(&[IAC, DONT, o]);
389 out.flush();
390 }
391 _ => {}
392 }
393 }
394
395 fn subnegotiation(&mut self) {
396 match self.sb.first().copied() {
397 Some(OPT_NAWS) if self.sb.len() >= 5 => {
398 let cols = u16::from_be_bytes([self.sb[1], self.sb[2]]);
399 let rows = u16::from_be_bytes([self.sb[3], self.sb[4]]);
400 if cols > 0 {
401 self.term.cols = cols;
402 }
403 if rows > 0 {
404 self.term.rows = rows;
405 }
406 }
407 Some(OPT_TTYPE) if self.sb.len() >= 2 && self.sb[1] == TTYPE_IS => {
408 let name = String::from_utf8_lossy(&self.sb[2..]).into_owned();
409 self.term.detected = color_from_term(&name);
410 self.term.name = name;
411 }
412 _ => {}
413 }
414 }
415
416 pub fn apply_color(&self, out: &mut Out) {
418 if !self.color_forced {
419 out.color = self.term.detected;
420 }
421 }
422
423 fn insert(&mut self, out: &mut Out, b: u8) {
426 if self.line.len() >= LINE_MAX {
427 return;
428 }
429 self.line.insert(self.pos, b);
430 self.pos += 1;
431 if self.pos == self.line.len() {
432 out.raw(&[b]);
433 if b == IAC {
435 out.raw(&[IAC]);
436 }
437 } else {
438 self.redraw(out);
439 }
440 }
441
442 fn backspace(&mut self, out: &mut Out) {
443 if self.pos == 0 {
444 return;
445 }
446 let mut start = self.pos - 1;
447 while start > 0 && (self.line[start] & 0xc0) == 0x80 {
448 start -= 1;
449 }
450 self.line.drain(start..self.pos);
451 let at_end = start == self.line.len();
452 self.pos = start;
453 if at_end {
454 out.raw(b"\x08 \x08");
455 } else {
456 self.redraw(out);
457 }
458 }
459
460 fn delete(&mut self, out: &mut Out) {
461 if self.pos >= self.line.len() {
462 return;
463 }
464 let mut end = self.pos + 1;
465 while end < self.line.len() && (self.line[end] & 0xc0) == 0x80 {
466 end += 1;
467 }
468 self.line.drain(self.pos..end);
469 self.redraw(out);
470 }
471
472 fn kill_word(&mut self, out: &mut Out) {
473 let mut i = self.pos;
474 while i > 0 && self.line[i - 1] == b' ' {
475 i -= 1;
476 }
477 while i > 0 && self.line[i - 1] != b' ' {
478 i -= 1;
479 }
480 self.line.drain(i..self.pos);
481 self.pos = i;
482 self.redraw(out);
483 }
484
485 fn move_left(&mut self, out: &mut Out) {
486 if self.pos == 0 {
487 return;
488 }
489 self.pos -= 1;
490 while self.pos > 0 && (self.line[self.pos] & 0xc0) == 0x80 {
491 self.pos -= 1;
492 }
493 out.raw(b"\x1b[D");
494 }
495
496 fn move_right(&mut self, out: &mut Out) {
497 if self.pos >= self.line.len() {
498 return;
499 }
500 self.pos += 1;
501 while self.pos < self.line.len() && (self.line[self.pos] & 0xc0) == 0x80 {
502 self.pos += 1;
503 }
504 out.raw(b"\x1b[C");
505 }
506
507 fn set_line(&mut self, out: &mut Out, new: Vec<u8>) {
508 self.line = new;
509 self.pos = self.line.len();
510 self.redraw(out);
511 }
512
513 fn csi_key(&mut self, out: &mut Out, fin: u8) {
514 let param = self.csi.iter().take_while(|c| c.is_ascii_digit()).fold(0u32, |a, &c| {
515 a.saturating_mul(10).saturating_add((c - b'0') as u32)
516 });
517 match fin {
518 b'A' => {
519 if self.history.is_empty() || self.hist_idx == 0 {
520 return;
521 }
522 if self.hist_idx == self.history.len() {
523 self.saved_line = self.line.clone();
524 }
525 self.hist_idx -= 1;
526 let h = self.history[self.hist_idx].clone();
527 self.set_line(out, h);
528 }
529 b'B' => {
530 if self.hist_idx >= self.history.len() {
531 return;
532 }
533 self.hist_idx += 1;
534 let l = if self.hist_idx == self.history.len() {
535 core::mem::take(&mut self.saved_line)
536 } else {
537 self.history[self.hist_idx].clone()
538 };
539 self.set_line(out, l);
540 }
541 b'C' => self.move_right(out),
542 b'D' => self.move_left(out),
543 b'H' => {
544 self.pos = 0;
545 self.redraw(out);
546 }
547 b'F' => {
548 self.pos = self.line.len();
549 self.redraw(out);
550 }
551 b'~' => match param {
552 1 | 7 => {
553 self.pos = 0;
554 self.redraw(out);
555 }
556 4 | 8 => {
557 self.pos = self.line.len();
558 self.redraw(out);
559 }
560 3 => self.delete(out),
561 _ => {}
562 },
563 _ => {}
564 }
565 }
566
567 fn tab(&mut self, out: &mut Out) {
570 let (start, cands) = shell::complete(&self.cwd, &self.line[..self.pos]);
571 if cands.is_empty() {
572 out.raw(b"\x07");
573 return;
574 }
575 let typed = &self.line[start..self.pos];
576 let typed_len = typed.len();
577 let first = cands[0].name.as_bytes();
579 let mut common = first.len();
580 for c in &cands[1..] {
581 let b = c.name.as_bytes();
582 let mut i = 0;
583 while i < common && i < b.len() && first[i] == b[i] {
584 i += 1;
585 }
586 common = i;
587 }
588 while common > 0 && common < first.len() && (first[common] & 0xc0) == 0x80 {
590 common -= 1;
591 }
592 if cands.len() == 1 {
593 let c = &cands[0];
594 let mut text: Vec<u8> = c.name.as_bytes().to_vec();
595 if !c.is_dir {
596 text.push(b' ');
597 }
598 self.replace_tail(out, start, text);
599 } else if common > typed_len {
600 let text = first[..common].to_vec();
601 self.replace_tail(out, start, text);
602 } else {
603 out.text("\n");
604 for c in &cands {
605 out.style(if c.is_dir { Style::Dir } else { Style::File });
606 out.text(&c.label);
607 out.style(Style::Reset);
608 out.text(" ");
609 }
610 out.text("\n");
611 self.redraw(out);
612 }
613 }
614
615 fn replace_tail(&mut self, out: &mut Out, start: usize, text: Vec<u8>) {
616 self.line.splice(start..self.pos, text.iter().copied());
617 self.pos = start + text.len();
618 self.redraw(out);
619 }
620
621 fn submit(&mut self, out: &mut Out) -> bool {
624 out.text("\n");
625 let line_bytes = core::mem::take(&mut self.line);
626 self.pos = 0;
627 let line = String::from_utf8_lossy(&line_bytes).into_owned();
628 let trimmed = line.trim();
629
630 if !trimmed.is_empty() {
631 if self.history.last().map(|h| h.as_slice()) != Some(trimmed.as_bytes()) {
632 if self.history.len() >= HISTORY_MAX {
633 self.history.remove(0);
634 }
635 self.history.push(trimmed.as_bytes().to_vec());
636 }
637 }
638 self.hist_idx = self.history.len();
639 self.saved_line.clear();
640
641 let keep_going = if trimmed.is_empty() {
642 true
643 } else {
644 out.interrupted = false;
645 let r = shell::run_line(self, out, trimmed);
646 self.apply_color(out);
647 r
648 };
649 out.set_redirect(None);
650 if !keep_going {
651 out.styled(Style::Dim, "Bye.\n");
652 out.flush();
653 return false;
654 }
655 if out.peer_closed {
656 return false;
657 }
658 self.draw_prompt(out);
659 out.flush();
660
661 if !out.pending.is_empty() {
663 let pending = core::mem::take(&mut out.pending);
664 return self.feed(out, &pending);
665 }
666 true
667 }
668}
669
670fn chars_in(b: &[u8]) -> usize {
672 b.iter().filter(|&&c| (c & 0xc0) != 0x80).count()
673}