Skip to main content

strat9_kernel/shell/commands/net/
telnet.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
23use super::*;
24
25/// Open a TCP connection and send/receive data interactively.
26///
27/// Usage: `telnet <ip> <port> [--http]`
28///
29/// With `--http`, sends an HTTP GET and prints the response.
30pub fn cmd_telnet(args: &[String]) -> Result<(), ShellError> {
31    if args.len() < 2 {
32        shell_println!("Usage: telnet <ip> <port> [--http]");
33        return Err(ShellError::InvalidArguments);
34    }
35    let ip = &args[0];
36    let port = &args[1];
37    let http_mode = args.get(2).map(|s| s.as_str()) == Some("--http");
38
39    let path = alloc::format!("/net/tcp/connect/{}/{}", ip, port);
40    let fd = match vfs::open(&path, OpenFlags::RDWR) {
41        Ok(fd) => fd,
42        Err(e) => {
43            shell_println!("telnet: connect failed: {:?}", e);
44            return Err(ShellError::ExecutionFailed);
45        }
46    };
47
48    shell_println!("Connected to {}:{}", ip, port);
49
50    for _ in 0..50 {
51        shell_sleep_ms(100);
52        if crate::shell::is_interrupted() {
53            shell_println!("^C");
54            let _ = vfs::close(fd);
55            return Ok(());
56        }
57    }
58
59    if http_mode {
60        let req = alloc::format!("GET / HTTP/1.0\r\nHost: {}\r\n\r\n", ip);
61        let _ = vfs::write(fd, req.as_bytes());
62    }
63
64    let mut buf = [0u8; 256];
65    let mut total = 0usize;
66    for _ in 0..100 {
67        if crate::shell::is_interrupted() {
68            shell_println!("^C");
69            break;
70        }
71        match vfs::read(fd, &mut buf) {
72            Ok(0) => break,
73            Ok(n) => {
74                if let Ok(s) = core::str::from_utf8(&buf[..n]) {
75                    crate::shell_print!("{}", s);
76                }
77                total += n;
78            }
79            Err(_) => {
80                shell_sleep_ms(100);
81            }
82        }
83    }
84    shell_println!("\nConnection closed ({} bytes received)", total);
85    let _ = vfs::close(fd);
86    Ok(())
87}