Skip to main content

ping/
main.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//! ping : ICMP echo utility for strat9-os
24//!
25//! Sends ICMP echo requests by writing to `/net/ping/<target_ip>` and reads
26//! replies from the same scheme path.  The actual ICMP socket is driven by
27//! the `strate-net` silo via smoltcp; this tool is a thin userspace wrapper.
28//!
29//! Usage:  ping [-6] [-c count] [ip|hostname] [count]
30//!
31//! All I/O is done through Plan 9–style schemes (no BSD sockets).
32
33#![no_std]
34#![no_main]
35#![feature(alloc_error_handler)]
36
37extern crate alloc;
38
39use core::{alloc::Layout, fmt::Write, panic::PanicInfo};
40use strat9_abi::ip::{
41    is_ipv4_literal_candidate, is_ipv6_literal_candidate, parse_ipv4_literal, parse_ipv6_literal,
42};
43use strat9_syscall::{call, data::TimeSpec, number};
44
45// ===========================================================================
46// Minimal bump allocator
47// ===========================================================================
48
49alloc_freelist::define_freelist_allocator!(pub struct BumpAllocator; heap_size = 64 * 1024;);
50
51#[global_allocator]
52static GLOBAL_ALLOCATOR: BumpAllocator = BumpAllocator;
53
54#[alloc_error_handler]
55/// Implements alloc error.
56fn alloc_error(_layout: Layout) -> ! {
57    log("[ping] OOM\n");
58    call::exit(12)
59}
60
61#[panic_handler]
62fn panic(info: &PanicInfo) -> ! {
63    call::handle_panic("ping", info)
64}
65
66// ===========================================================================
67// Helpers
68// ===========================================================================
69
70/// Implements log.
71fn log(msg: &str) {
72    let _ = call::write(1, msg.as_bytes());
73}
74
75/// Implements log u32.
76fn log_u32(val: u32) {
77    let mut buf = [0u8; 12];
78    let s = u32_to_str(val, &mut buf);
79    log(s);
80}
81
82/// Implements u32 to str.
83fn u32_to_str(mut val: u32, buf: &mut [u8; 12]) -> &str {
84    if val == 0 {
85        return "0";
86    }
87    let mut i = buf.len();
88    while val > 0 {
89        i -= 1;
90        buf[i] = b'0' + (val % 10) as u8;
91        val /= 10;
92    }
93    unsafe { core::str::from_utf8_unchecked(&buf[i..]) }
94}
95
96struct BufWriter<'a> {
97    buf: &'a mut [u8],
98    pos: usize,
99}
100impl core::fmt::Write for BufWriter<'_> {
101    /// Writes str.
102    fn write_str(&mut self, s: &str) -> core::fmt::Result {
103        let bytes = s.as_bytes();
104        let avail = self.buf.len().saturating_sub(self.pos);
105        let n = bytes.len().min(avail);
106        self.buf[self.pos..self.pos + n].copy_from_slice(&bytes[..n]);
107        self.pos += n;
108        Ok(())
109    }
110}
111
112/// Implements clock ns.
113fn clock_ns() -> u64 {
114    unsafe { strat9_syscall::syscall0(number::SYS_CLOCK_GETTIME) }
115        .map(|v| v as u64)
116        .unwrap_or(0)
117}
118
119/// Implements sleep ms.
120fn sleep_ms(ms: u64) {
121    let req = TimeSpec {
122        tv_sec: (ms / 1000) as i64,
123        tv_nsec: ((ms % 1000) * 1_000_000) as i64,
124    };
125    let _ = unsafe {
126        strat9_syscall::syscall2(number::SYS_NANOSLEEP, &req as *const TimeSpec as usize, 0)
127    };
128}
129
130/// Open a scheme file, return fd.
131fn scheme_open(path: &str) -> Result<usize, ()> {
132    call::openat(0, path, 0x3, 0).map(|fd| fd).map_err(|_| ())
133}
134
135/// Write to an open scheme fd, return bytes written.
136fn scheme_write_fd(fd: usize, data: &[u8]) -> Result<usize, ()> {
137    call::write(fd, data).map_err(|_| ())
138}
139
140/// Read from an open scheme fd, return bytes read.
141fn scheme_read_fd(fd: usize, buf: &mut [u8]) -> Result<usize, ()> {
142    call::read(fd, buf).map_err(|_| ())
143}
144
145/// Close a scheme fd.
146fn scheme_close(fd: usize) {
147    let _ = call::close(fd);
148}
149
150#[derive(Clone, Copy, PartialEq, Eq)]
151enum AddressFamily {
152    Ipv4,
153    Ipv6,
154}
155
156struct ResolvedTarget<'a> {
157    addr: &'a str,
158    family: AddressFamily,
159}
160
161enum ResolveError {
162    InvalidLiteral(AddressFamily),
163    ResolveFailed,
164    FamilyMismatch {
165        requested: AddressFamily,
166        actual: AddressFamily,
167    },
168}
169
170fn family_flag(family: AddressFamily) -> &'static str {
171    match family {
172        AddressFamily::Ipv4 => "-4",
173        AddressFamily::Ipv6 => "-6",
174    }
175}
176
177fn family_name(family: AddressFamily) -> &'static str {
178    match family {
179        AddressFamily::Ipv4 => "IPv4",
180        AddressFamily::Ipv6 => "IPv6",
181    }
182}
183
184fn apply_family_constraint(
185    requested: Option<AddressFamily>,
186    actual: AddressFamily,
187) -> Result<(), ResolveError> {
188    match requested {
189        Some(expected) if expected != actual => Err(ResolveError::FamilyMismatch {
190            requested: expected,
191            actual,
192        }),
193        _ => Ok(()),
194    }
195}
196
197fn resolve_target<'a>(
198    target: &'a str,
199    requested_family: Option<AddressFamily>,
200    resolved_buf: &'a mut [u8; 64],
201) -> Result<ResolvedTarget<'a>, ResolveError> {
202    if parse_ipv4_literal(target).is_some() {
203        apply_family_constraint(requested_family, AddressFamily::Ipv4)?;
204        return Ok(ResolvedTarget {
205            addr: target,
206            family: AddressFamily::Ipv4,
207        });
208    }
209    if parse_ipv6_literal(target).is_some() {
210        apply_family_constraint(requested_family, AddressFamily::Ipv6)?;
211        return Ok(ResolvedTarget {
212            addr: target,
213            family: AddressFamily::Ipv6,
214        });
215    }
216    if is_ipv4_literal_candidate(target) {
217        return Err(ResolveError::InvalidLiteral(AddressFamily::Ipv4));
218    }
219    if is_ipv6_literal_candidate(target) {
220        return Err(ResolveError::InvalidLiteral(AddressFamily::Ipv6));
221    }
222
223    let mut path_buf = [0u8; 128];
224    let path_len = {
225        let mut pw = BufWriter {
226            buf: &mut path_buf,
227            pos: 0,
228        };
229        let _ = write!(pw, "/net/resolve/{}", target);
230        pw.pos
231    };
232    let path =
233        core::str::from_utf8(&path_buf[..path_len]).map_err(|_| ResolveError::ResolveFailed)?;
234    let n = scheme_open(path)
235        .and_then(|fd| {
236            let r = scheme_read_fd(fd, resolved_buf);
237            scheme_close(fd);
238            r
239        })
240        .map_err(|_| ResolveError::ResolveFailed)?;
241    if n == 0 {
242        return Err(ResolveError::ResolveFailed);
243    }
244    let end = resolved_buf[..n]
245        .iter()
246        .position(|&b| b == b'\n')
247        .unwrap_or(n);
248    if end == 0 {
249        return Err(ResolveError::ResolveFailed);
250    }
251    let resolved =
252        core::str::from_utf8(&resolved_buf[..end]).map_err(|_| ResolveError::ResolveFailed)?;
253    if parse_ipv4_literal(resolved).is_some() {
254        apply_family_constraint(requested_family, AddressFamily::Ipv4)?;
255        Ok(ResolvedTarget {
256            addr: resolved,
257            family: AddressFamily::Ipv4,
258        })
259    } else if parse_ipv6_literal(resolved).is_some() {
260        apply_family_constraint(requested_family, AddressFamily::Ipv6)?;
261        Ok(ResolvedTarget {
262            addr: resolved,
263            family: AddressFamily::Ipv6,
264        })
265    } else {
266        Err(ResolveError::ResolveFailed)
267    }
268}
269
270fn print_usage() {
271    log("Usage: ping [-6] [-c count] [target] [count]\n");
272    log("       ping -h | --help\n");
273    log("Options:\n");
274    log("  -6           Require IPv6\n");
275    log("  -c <count>   Send count requests (default: 4)\n");
276    log("  -h, --help   Show this help\n");
277}
278
279fn copy_target(dst: &mut [u8; 64], value: &str) -> usize {
280    let len = value.len().min(dst.len() - 1);
281    dst[..len].copy_from_slice(&value.as_bytes()[..len]);
282    len
283}
284
285fn read_default_target(family: Option<AddressFamily>, target: &mut [u8; 64]) -> Option<usize> {
286    let mut gateway_buf = [0u8; 64];
287    let path = if family == Some(AddressFamily::Ipv6) {
288        "/net/ip6/gateway"
289    } else {
290        "/net/gateway"
291    };
292    let n = scheme_open(path)
293        .and_then(|fd| {
294            let r = scheme_read_fd(fd, &mut gateway_buf);
295            scheme_close(fd);
296            r
297        })
298        .ok()?;
299    if n == 0 {
300        return None;
301    }
302
303    let end = gateway_buf[..n]
304        .iter()
305        .position(|&b| b == b'\n')
306        .unwrap_or(n);
307    if end == 0 {
308        return None;
309    }
310
311    let gateway = &gateway_buf[..end];
312    if gateway == b"0.0.0.0" || gateway == b"::" {
313        return None;
314    }
315
316    let gateway_str = core::str::from_utf8(gateway).ok()?;
317    Some(copy_target(target, gateway_str))
318}
319
320// ===========================================================================
321//  Minimal argument parsing
322// ===========================================================================
323
324struct PingArgs {
325    target: [u8; 64],
326    target_len: usize,
327    count: u32,
328    family: Option<AddressFamily>,
329}
330
331/// Convert a null-terminated C string pointer to a `&'static str`.
332///
333/// # Safety
334/// `ptr` must point to a valid null-terminated byte sequence that remains
335/// valid for the lifetime of the process (true for argv pointers on the
336/// initial user stack).
337unsafe fn cstr_to_str(ptr: *const u8) -> &'static str {
338    let mut len = 0usize;
339    while *ptr.add(len) != 0 {
340        len += 1;
341    }
342    core::str::from_utf8_unchecked(core::slice::from_raw_parts(ptr, len))
343}
344
345/// Parse an ASCII decimal string into a `u32`.
346fn str_to_u32(s: &str) -> Option<u32> {
347    if s.is_empty() {
348        return None;
349    }
350    let mut val: u32 = 0;
351    for &b in s.as_bytes() {
352        if !b.is_ascii_digit() {
353            return None;
354        }
355        val = val.checked_mul(10)?.checked_add((b - b'0') as u32)?;
356    }
357    Some(val)
358}
359
360/// Build `PingArgs` from the SysV initial user stack.
361///
362/// Supported forms:
363/// - `ping <target> [count]`
364/// - `ping -c <count> [target]`
365/// - `ping -6 ...`
366/// - `ping -h|--help`
367fn parse_args_from_stack(argc: usize, argv: *const *const u8) -> PingArgs {
368    let mut target = [0u8; 64];
369    let mut target_len = 0usize;
370    let mut count = 4u32;
371    let mut family: Option<AddressFamily> = None;
372    let mut positional_count_set = false;
373
374    let mut i = 1usize;
375    while i < argc {
376        let arg = unsafe { cstr_to_str(*argv.add(i)) };
377        match arg {
378            "-h" | "--help" => {
379                print_usage();
380                call::exit(0);
381            }
382            "-6" => {
383                family = Some(AddressFamily::Ipv6);
384            }
385            "-c" => {
386                i += 1;
387                if i >= argc {
388                    log("ping: missing value for -c\n");
389                    print_usage();
390                    call::exit(1);
391                }
392                let count_arg = unsafe { cstr_to_str(*argv.add(i)) };
393                let Some(parsed) = str_to_u32(count_arg) else {
394                    log("ping: invalid count: ");
395                    log(count_arg);
396                    log("\n");
397                    call::exit(1);
398                };
399                count = parsed;
400            }
401            _ if arg.starts_with('-') => {
402                log("ping: unknown option: ");
403                log(arg);
404                log("\n");
405                print_usage();
406                call::exit(1);
407            }
408            _ if target_len == 0 => {
409                target_len = copy_target(&mut target, arg);
410            }
411            _ if !positional_count_set => {
412                let Some(parsed) = str_to_u32(arg) else {
413                    log("ping: unexpected argument: ");
414                    log(arg);
415                    log("\n");
416                    print_usage();
417                    call::exit(1);
418                };
419                count = parsed;
420                positional_count_set = true;
421            }
422            _ => {
423                log("ping: unexpected argument: ");
424                log(arg);
425                log("\n");
426                print_usage();
427                call::exit(1);
428            }
429        }
430
431        i += 1;
432    }
433
434    if target_len == 0 {
435        target_len = match read_default_target(family, &mut target) {
436            Some(len) => len,
437            None => {
438                log("ping: no target specified and no default gateway configured\n");
439                print_usage();
440                call::exit(1);
441            }
442        };
443    }
444
445    PingArgs {
446        target,
447        target_len,
448        count,
449        family,
450    }
451}
452
453// ===========================================================================
454// Ping implementation
455// ===========================================================================
456
457/// ICMP echo request/reply payload passed through the `/net/ping/<ip>` scheme.
458///
459/// Write: seq(u16 LE) + timestamp_ns(u64 LE) + padding(40 bytes) = 50 bytes
460/// Read:  seq(u16 LE) + rtt_us(u64 LE)                           = 10 bytes
461#[repr(C)]
462struct PingRequest {
463    seq: u16,
464    timestamp_ns: u64,
465    payload: [u8; 40],
466}
467
468/// Entry point: captures the initial RSP (= SysV stack pointer) and calls
469/// `start_impl`. Using a naked function guarantees that no prologue has
470/// modified RSP before we pass it as `rdi`.
471#[unsafe(naked)]
472#[unsafe(no_mangle)]
473pub unsafe extern "C" fn _start() -> ! {
474    // At entry via iretq: RSP = boot_sp from the ELF loader.
475    // SysV layout: [RSP] = argc, [RSP+8] = argv[0] ptr, ...
476    core::arch::naked_asm!(
477        "mov rdi, rsp",   // pass initial stack pointer as first arg
478        "call {f}",
479        "ud2",
480        f = sym start_impl,
481    );
482}
483
484/// Main program logic; called from the naked `_start` trampoline.
485///
486/// `initial_sp` is the SysV stack pointer captured before any prologue code
487/// has run, so `*initial_sp` == argc and `*(initial_sp + 1)` == argv[0].
488extern "C" fn start_impl(initial_sp: *const u64) -> ! {
489    let argc = unsafe { *initial_sp } as usize;
490    let argv = unsafe { initial_sp.add(1) as *const *const u8 };
491    let args = parse_args_from_stack(argc, argv);
492    let raw_target = unsafe { core::str::from_utf8_unchecked(&args.target[..args.target_len]) };
493    let mut resolved_buf = [0u8; 64];
494    let target = match resolve_target(raw_target, args.family, &mut resolved_buf) {
495        Ok(target) => target,
496        Err(ResolveError::InvalidLiteral(family)) => {
497            log("ping: invalid ");
498            log(family_name(family));
499            log(" address: ");
500            log(raw_target);
501            log("\n");
502            call::exit(1);
503        }
504        Err(ResolveError::ResolveFailed) => {
505            log("ping: cannot resolve host: ");
506            log(raw_target);
507            log("\n");
508            call::exit(1);
509        }
510        Err(ResolveError::FamilyMismatch { requested, actual }) => {
511            log("ping: ");
512            log(family_flag(requested));
513            log(" requires an ");
514            log(family_name(requested));
515            log(" target, but got ");
516            log(family_name(actual));
517            log("\n");
518            call::exit(1);
519        }
520    };
521
522    log("PING ");
523    log(target.addr);
524    log(", sending ");
525    log_u32(args.count);
526    log(" ICMP now\n");
527
528    // Build the scheme path: /net/ping/<ip> or /net/ping6/<ip>
529    let mut path_buf = [0u8; 128];
530    let mut pw = BufWriter {
531        buf: &mut path_buf,
532        pos: 0,
533    };
534    let scheme_name = match target.family {
535        AddressFamily::Ipv4 => "ping",
536        AddressFamily::Ipv6 => "ping6",
537    };
538    let _ = write!(pw, "/net/{}/{}", scheme_name, target.addr);
539    let path_len = pw.pos;
540    let path = unsafe { core::str::from_utf8_unchecked(&path_buf[..path_len]) };
541
542    // Open the scheme fd once and reuse for all pings (avoids open/close per packet).
543    let fd = match scheme_open(path) {
544        Ok(fd) => fd,
545        Err(()) => {
546            log("ping: cannot open ");
547            log(path);
548            log("\n");
549            call::exit(1);
550        }
551    };
552
553    const PING_TIMEOUT_MS: u64 = 5_000;
554    const POLL_INTERVAL_MS: u64 = 100;
555
556    let mut sent: u32 = 0;
557    let mut received: u32 = 0;
558    let mut min_rtt_us: u64 = u64::MAX;
559    let mut max_rtt_us: u64 = 0;
560    let mut total_rtt_us: u64 = 0;
561
562    for seq in 0..args.count {
563        // Build the request payload
564        let ts = clock_ns();
565        let req = PingRequest {
566            seq: seq as u16,
567            timestamp_ns: ts,
568            payload: [0xAA; 40],
569        };
570        let req_bytes = unsafe {
571            core::slice::from_raw_parts(
572                &req as *const PingRequest as *const u8,
573                core::mem::size_of::<PingRequest>(),
574            )
575        };
576
577        let mut wrote = false;
578        let write_deadline_ns = clock_ns().saturating_add(PING_TIMEOUT_MS * 1_000_000);
579        while clock_ns() < write_deadline_ns {
580            log("[pt] wr ");
581            if scheme_write_fd(fd, req_bytes).is_ok() {
582                wrote = true;
583                log("ok\n");
584                break;
585            }
586            log(".");
587            // NOTE: do NOT read-drain here : with a persistent FD, a drain
588            // would consume replies from previously sent pings, losing them.
589            sleep_ms(POLL_INTERVAL_MS);
590        }
591
592        if !wrote {
593            log("  Request timeout (write failed): seq=");
594            log_u32(seq);
595            log("\n");
596            sent += 1;
597            continue;
598        }
599        sent += 1;
600
601        log("[pt] rd ");
602        let mut got_reply = false;
603        let read_deadline_ns = clock_ns().saturating_add(PING_TIMEOUT_MS * 1_000_000);
604        while clock_ns() < read_deadline_ns {
605            let mut reply_buf = [0u8; 64];
606            match scheme_read_fd(fd, &mut reply_buf) {
607                Ok(n) if n >= 10 => {
608                    log("rep\n");
609                    // Use the RTT computed by strate-net (accurate ICMP-level timing),
610                    // not a local timestamp which would include IPC overhead.
611                    let reply_seq = u16::from_le_bytes([reply_buf[0], reply_buf[1]]);
612                    let rtt_us =
613                        u64::from_le_bytes(reply_buf[2..10].try_into().unwrap_or([0u8; 8]));
614                    let rtt_ms = rtt_us / 1000;
615                    let rtt_frac = (rtt_us % 1000) / 100;
616
617                    log("  Reply from ");
618                    log(target.addr);
619                    log(": seq=");
620                    log_u32(reply_seq as u32);
621                    log(" time=");
622                    log_u32(rtt_ms as u32);
623                    log(".");
624                    log_u32(rtt_frac as u32);
625                    log("ms\n");
626
627                    received += 1;
628                    total_rtt_us += rtt_us;
629                    if rtt_us < min_rtt_us {
630                        min_rtt_us = rtt_us;
631                    }
632                    if rtt_us > max_rtt_us {
633                        max_rtt_us = rtt_us;
634                    }
635                    got_reply = true;
636                    break;
637                }
638                Ok(0) => {
639                    log(".");
640                    sleep_ms(POLL_INTERVAL_MS);
641                }
642                _ => {
643                    log("x");
644                    sleep_ms(POLL_INTERVAL_MS);
645                }
646            }
647        }
648
649        if !got_reply {
650            log("[pt] rto\n");
651            log("  Request timeout: seq=");
652            log_u32(seq);
653            log("\n");
654        }
655
656        if seq + 1 < args.count {
657            sleep_ms(900); // ~1s interval
658        }
659    }
660
661    // Statistics
662    log("\n--- ");
663    log(target.addr);
664    log(" ping statistics ---\n");
665    log_u32(sent);
666    log(" packets transmitted, ");
667    log_u32(received);
668    log(" received");
669    if sent > 0 {
670        let loss = ((sent - received) * 100) / sent;
671        log(", ");
672        log_u32(loss);
673        log("% packet loss");
674    }
675    log("\n");
676
677    if received > 0 {
678        let avg = total_rtt_us / received as u64;
679        log("rtt min/avg/max = ");
680        log_u32((min_rtt_us / 1000) as u32);
681        log("/");
682        log_u32((avg / 1000) as u32);
683        log("/");
684        log_u32((max_rtt_us / 1000) as u32);
685        log(" ms\n");
686    }
687
688    scheme_close(fd);
689    call::exit(0)
690}