Skip to main content

strat9_kernel/shell/commands/net/
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//! Network commands (ping, ifconfig)
24mod ifconfig;
25mod netcmd;
26mod nslookup;
27mod ping_userspace;
28mod telnet;
29
30use crate::{
31    shell::ShellError,
32    shell_println,
33    vfs::{self, OpenFlags},
34};
35use alloc::string::String;
36pub use ifconfig::cmd_ifconfig;
37pub use netcmd::cmd_net;
38pub use nslookup::cmd_nslookup;
39pub use ping_userspace::cmd_ping;
40use strat9_abi::ip::{is_ipv4_literal_candidate, parse_ipv4_literal};
41pub use telnet::cmd_telnet;
42
43/// Read an ELF binary from a VFS path into a Vec<u8>.
44/// Shared helper used by ping and other commands that spawn userspace binaries.
45///
46/// The image installs modules at `/initfs/<name>` (see
47/// `tools/uefi-modules.manifest`), while some shell paths historically used
48/// `/initfs/bin/<name>`. Both layouts are accepted so a path change cannot
49/// make a userspace tool silently unlaunchable.
50pub(super) fn read_elf(path: &str) -> Result<alloc::vec::Vec<u8>, ShellError> {
51    let alternate = if let Some(name) = path.strip_prefix("/initfs/bin/") {
52        Some(alloc::format!("/initfs/{}", name))
53    } else if let Some(name) = path.strip_prefix("/initfs/") {
54        Some(alloc::format!("/initfs/bin/{}", name))
55    } else {
56        None
57    };
58    let candidates = [Some(alloc::string::String::from(path)), alternate];
59
60    for candidate in candidates.iter().flatten() {
61        let Ok(fd) = vfs::open(candidate, OpenFlags::READ) else {
62            continue;
63        };
64        let data = match vfs::read_all(fd) {
65            Ok(data) => data,
66            Err(_) => {
67                let _ = vfs::close(fd);
68                shell_println!("{}: read error", candidate);
69                return Err(ShellError::ExecutionFailed);
70            }
71        };
72        let _ = vfs::close(fd);
73        return Ok(data);
74    }
75
76    shell_println!("{}: not found", path);
77    Err(ShellError::ExecutionFailed)
78}
79
80/// Spawn a userspace ELF binary from `/initfs/<name>` (or the legacy
81/// `/initfs/bin/<name>`) with the given shell arguments as `argv[1..]`.
82/// Returns immediately after scheduling.
83pub(super) fn spawn_elf_with_args(
84    bin_path: &str,
85    task_name: &'static str,
86    args: &[String],
87) -> Result<(), ShellError> {
88    let data = read_elf(bin_path)?;
89    let arg_strs: alloc::vec::Vec<&str> = args.iter().map(|s| s.as_str()).collect();
90    match crate::process::elf::load_and_run_elf_with_args(&data, task_name, &arg_strs) {
91        Ok(task_id) => {
92            shell_println!("{}: started (task={})", task_name, task_id);
93            Ok(())
94        }
95        Err(e) => {
96            shell_println!("{}: failed to launch: {}", task_name, e);
97            Err(ShellError::ExecutionFailed)
98        }
99    }
100}
101
102/// Performs the cmd ping spawn operation (launches /initfs/ping with args).
103pub(super) fn cmd_ping_spawn_impl(args: &[String]) -> Result<(), ShellError> {
104    // Early IPv4 validation : same behaviour as kping
105    if let Some(target) = args.first() {
106        if is_ipv4_literal_candidate(target) && parse_ipv4_literal(target).is_none() {
107            shell_println!("ping: invalid IPv4 address: {}", target);
108            return Ok(());
109        }
110    }
111    spawn_elf_with_args("/initfs/ping", "ping", args)
112}
113
114/// Busy-wait for approximately `ms` milliseconds, yielding to other tasks.
115/// Scheduler ticks are 10ms each.
116pub(super) fn shell_sleep_ms(ms: u64) {
117    let ticks_to_wait = (ms + 9) / 10; // round up
118    let start = crate::process::scheduler::ticks();
119    loop {
120        crate::process::yield_task();
121        if crate::process::scheduler::ticks().wrapping_sub(start) >= ticks_to_wait {
122            break;
123        }
124    }
125}
126
127/// Performs the cmd ifconfig operation.
128pub(super) fn cmd_ifconfig_impl(args: &[String]) -> Result<(), ShellError> {
129    if !args.is_empty() {
130        match args[0].as_str() {
131            "inet" => {
132                if args.len() != 2 {
133                    shell_println!("Usage: ifconfig inet <ipv4/prefix>");
134                    return Err(ShellError::InvalidArguments);
135                }
136                let path = alloc::format!("/net/ip/set/{}", args[1]);
137                write_path(&path, b"1")?;
138                shell_println!("ifconfig: inet set to {}", args[1]);
139                return Ok(());
140            }
141            "gateway" => {
142                if args.len() == 2 && args[1].as_str() == "clear" {
143                    write_path("/net/route/default/clear", b"1")?;
144                    shell_println!("ifconfig: default gateway cleared");
145                    return Ok(());
146                }
147                if args.len() != 2 {
148                    shell_println!("Usage: ifconfig gateway <ipv4|clear>");
149                    return Err(ShellError::InvalidArguments);
150                }
151                let path = alloc::format!("/net/route/default/set/{}", args[1]);
152                write_path(&path, b"1")?;
153                shell_println!("ifconfig: default gateway set to {}", args[1]);
154                return Ok(());
155            }
156            "dns" => {
157                if args.len() < 2 || args.len() > 4 {
158                    shell_println!("Usage: ifconfig dns <ipv4> [ipv4] [ipv4]");
159                    shell_println!("       ifconfig dns clear");
160                    return Err(ShellError::InvalidArguments);
161                }
162                if args.len() == 2 && args[1].as_str() == "clear" {
163                    write_path("/net/dns/set/0/0.0.0.0", b"1")?;
164                    write_path("/net/dns/set/1/0.0.0.0", b"1")?;
165                    write_path("/net/dns/set/2/0.0.0.0", b"1")?;
166                    shell_println!("ifconfig: DNS cleared");
167                    return Ok(());
168                }
169                write_path("/net/dns/set/0/0.0.0.0", b"1")?;
170                write_path("/net/dns/set/1/0.0.0.0", b"1")?;
171                write_path("/net/dns/set/2/0.0.0.0", b"1")?;
172                for (idx, ip) in args[1..].iter().enumerate() {
173                    let path = alloc::format!("/net/dns/set/{}/{}", idx, ip);
174                    write_path(&path, b"1")?;
175                }
176                shell_println!("ifconfig: DNS updated");
177                return Ok(());
178            }
179            "dhcp" => {
180                if args.len() != 2 {
181                    shell_println!("Usage: ifconfig dhcp <on|off>");
182                    return Err(ShellError::InvalidArguments);
183                }
184                match args[1].as_str() {
185                    "on" => {
186                        write_path("/net/dhcp/enable", b"1")?;
187                        shell_println!("ifconfig: DHCP enabled");
188                        return Ok(());
189                    }
190                    "off" => {
191                        write_path("/net/dhcp/disable", b"1")?;
192                        shell_println!("ifconfig: DHCP disabled");
193                        return Ok(());
194                    }
195                    _ => {
196                        shell_println!("Usage: ifconfig dhcp <on|off>");
197                        return Err(ShellError::InvalidArguments);
198                    }
199                }
200            }
201            _ => {
202                shell_println!("Usage: ifconfig");
203                shell_println!("       ifconfig inet <ipv4/prefix>");
204                shell_println!("       ifconfig gateway <ipv4|clear>");
205                shell_println!("       ifconfig dns <ipv4> [ipv4] [ipv4]");
206                shell_println!("       ifconfig dns clear");
207                shell_println!("       ifconfig dhcp <on|off>");
208                return Err(ShellError::InvalidArguments);
209            }
210        }
211    }
212
213    let read_file = |path: &str| -> String {
214        match vfs::open(path, OpenFlags::READ) {
215            Ok(fd) => {
216                let mut buf = [0u8; 96];
217                let n = vfs::read(fd, &mut buf).unwrap_or(0);
218                let _ = vfs::close(fd);
219                let s = core::str::from_utf8(&buf[..n]).unwrap_or("").trim();
220                String::from(s)
221            }
222            Err(_) => String::from("(unavailable)"),
223        }
224    };
225
226    let ip = read_file("/net/ip");
227    let ip6 = read_file("/net/ip6");
228    let gw = read_file("/net/gateway");
229    let gw6 = read_file("/net/ip6/gateway");
230    let route = read_file("/net/route");
231    let routes = read_file("/net/routes");
232    let dns = read_file("/net/dns");
233    let dhcp = read_file("/net/dhcp");
234
235    // Link state and media come from the kernel NIC registry, not /net: the
236    // scheme is served by the strate-net silo and is absent until it binds.
237    let ifaces = crate::hardware::nic::list_interfaces();
238    if ifaces.is_empty() {
239        shell_println!("(no network interface registered)");
240    }
241
242    for name in &ifaces {
243        let (link, media, mac, driver) = match crate::hardware::nic::get_device(name) {
244            Some(dev) => {
245                let m = dev.mac_address();
246                (
247                    if dev.link_up() { "up" } else { "down" },
248                    dev.media().as_str(),
249                    alloc::format!(
250                        "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
251                        m[0],
252                        m[1],
253                        m[2],
254                        m[3],
255                        m[4],
256                        m[5]
257                    ),
258                    String::from(dev.name()),
259                )
260            }
261            None => (
262                "unknown",
263                "other",
264                String::from("(unavailable)"),
265                String::from("unknown"),
266            ),
267        };
268
269        shell_println!("{}:", name);
270        shell_println!("  driver   {}", driver);
271        shell_println!("  media    {}", media);
272        shell_println!("  link     {}", link);
273        shell_println!("  hwaddr   {}", mac);
274        shell_println!("  inet     {}", ip);
275        shell_println!("  inet6    {}", ip6);
276        shell_println!("  dhcp     {}", dhcp);
277        shell_println!("  gateway  {}", gw);
278        shell_println!("  gateway6 {}", gw6);
279        shell_println!("  route    {}", route);
280        shell_println!("  routes   {}", routes);
281        shell_println!("  dns      {}", dns);
282    }
283
284    Ok(())
285}
286
287/// Writes path.
288fn write_path(path: &str, data: &[u8]) -> Result<(), ShellError> {
289    let fd = vfs::open(path, OpenFlags::WRITE).map_err(|_| ShellError::ExecutionFailed)?;
290    let res = vfs::write(fd, data).map(|_| ());
291    let _ = vfs::close(fd);
292    res.map_err(|_| ShellError::ExecutionFailed)
293}
294
295/// Performs the cmd net operation.
296pub(super) fn cmd_net_impl(args: &[String]) -> Result<(), ShellError> {
297    if args.is_empty() {
298        shell_println!("Usage: net route <show|add|del|default> ...");
299        return Err(ShellError::InvalidArguments);
300    }
301
302    match args[0].as_str() {
303        "route" => {
304            if args.len() < 2 {
305                shell_println!("Usage: net route <show|add|del|default> ...");
306                return Err(ShellError::InvalidArguments);
307            }
308
309            match args[1].as_str() {
310                "show" => {
311                    let routes = match vfs::open("/net/routes", OpenFlags::READ) {
312                        Ok(fd) => {
313                            let mut buf = [0u8; 256];
314                            let n = vfs::read(fd, &mut buf).unwrap_or(0);
315                            let _ = vfs::close(fd);
316                            String::from(core::str::from_utf8(&buf[..n]).unwrap_or("").trim())
317                        }
318                        Err(_) => String::from("(unavailable)"),
319                    };
320                    shell_println!("routes:");
321                    shell_println!("{}", routes);
322                    Ok(())
323                }
324                "add" => {
325                    if args.len() != 4 {
326                        shell_println!("Usage: net route add <cidr> <gateway>");
327                        return Err(ShellError::InvalidArguments);
328                    }
329                    let path = alloc::format!("/net/route/add/{}/{}", args[2], args[3]);
330                    write_path(&path, b"1")?;
331                    shell_println!("net route add: ok ({} via {})", args[2], args[3]);
332                    Ok(())
333                }
334                "del" => {
335                    if args.len() != 3 {
336                        shell_println!("Usage: net route del <cidr>");
337                        return Err(ShellError::InvalidArguments);
338                    }
339                    let path = alloc::format!("/net/route/del/{}", args[2]);
340                    write_path(&path, b"1")?;
341                    shell_println!("net route del: ok ({})", args[2]);
342                    Ok(())
343                }
344                "default" => {
345                    if args.len() == 4 && args[2].as_str() == "set" {
346                        let path = alloc::format!("/net/route/default/set/{}", args[3]);
347                        write_path(&path, b"1")?;
348                        shell_println!("net route default: ok (via {})", args[3]);
349                        return Ok(());
350                    }
351                    if args.len() == 3 && args[2].as_str() == "clear" {
352                        write_path("/net/route/default/clear", b"1")?;
353                        shell_println!("net route default: cleared");
354                        return Ok(());
355                    }
356                    shell_println!("Usage: net route default <set <gateway>|clear>");
357                    Err(ShellError::InvalidArguments)
358                }
359                _ => {
360                    shell_println!("Usage: net route <show|add|del|default> ...");
361                    Err(ShellError::InvalidArguments)
362                }
363            }
364        }
365        _ => {
366            shell_println!("Usage: net route <show|add|del|default> ...");
367            Err(ShellError::InvalidArguments)
368        }
369    }
370}