Skip to main content

strat9_kernel/shell/commands/util/
ntpdate.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::*;
24use alloc::string::String;
25use strat9_abi::ip::parse_ipv4_literal;
26
27const NTP_PORT: u16 = 123;
28const NTP_UNIX_EPOCH_DELTA: u64 = 2_208_988_800; // 1900 -> 1970
29
30/// Resolves ntp server.
31fn resolve_ntp_server(server: &str) -> Result<[u8; 4], ShellError> {
32    if let Some(ip) = parse_ipv4_literal(server) {
33        return Ok(ip);
34    }
35
36    let path = alloc::format!("/net/resolve/{}", server);
37    let fd = vfs::open(&path, vfs::OpenFlags::READ).map_err(|_| ShellError::ExecutionFailed)?;
38    let mut buf = [0u8; 64];
39    let n = vfs::read(fd, &mut buf).unwrap_or(0);
40    let _ = vfs::close(fd);
41    if n == 0 {
42        return Err(ShellError::ExecutionFailed);
43    }
44    let end = buf[..n].iter().position(|&b| b == b'\n').unwrap_or(n);
45    let s = core::str::from_utf8(&buf[..end]).unwrap_or("").trim();
46    parse_ipv4_literal(s).ok_or(ShellError::ExecutionFailed)
47}
48
49/// Formats ipv4.
50fn format_ipv4(ip: &[u8; 4]) -> String {
51    alloc::format!("{}.{}.{}.{}", ip[0], ip[1], ip[2], ip[3])
52}
53
54/// Sends an NTP request over UDP scheme and returns server transmit timestamp
55/// as unix seconds + nanoseconds.
56fn ntp_query(server_ip: &[u8; 4]) -> Result<(u64, u32), ShellError> {
57    let path = alloc::format!(
58        "/net/udp/connect/{}.{}.{}/{}/{}",
59        server_ip[0],
60        server_ip[1],
61        server_ip[2],
62        server_ip[3],
63        NTP_PORT
64    );
65    let fd = vfs::open(&path, vfs::OpenFlags::RDWR).map_err(|_| ShellError::ExecutionFailed)?;
66
67    // NTP packet: 48 bytes. LI=0, VN=4, Mode=3 (client).
68    let mut req = [0u8; 48];
69    req[0] = 0x23;
70    req[2] = 6; // poll interval hint
71    req[3] = 0xEC; // precision (~2^-20)
72
73    // Use local monotonic clock as entropy for transmit fraction.
74    let now_ns = crate::syscall::time::current_time_ns();
75    let frac = (((now_ns % 1_000_000_000) as u128) << 32) / 1_000_000_000u128;
76    req[44..48].copy_from_slice(&(frac as u32).to_be_bytes());
77
78    if vfs::write(fd, &req).is_err() {
79        let _ = vfs::close(fd);
80        return Err(ShellError::ExecutionFailed);
81    }
82
83    let start_tick = crate::process::scheduler::ticks();
84    let timeout_ticks = crate::arch::timer::TIMER_HZ * 3; // ~3s
85    let mut resp = [0u8; 64];
86
87    loop {
88        match vfs::read(fd, &mut resp) {
89            Ok(n) if n >= 48 => {
90                let _ = vfs::close(fd);
91                let li_vn_mode = resp[0];
92                let mode = li_vn_mode & 0x07;
93                let stratum = resp[1];
94                if mode != 4 || stratum == 0 {
95                    return Err(ShellError::ExecutionFailed);
96                }
97
98                let ntp_secs = u32::from_be_bytes([resp[40], resp[41], resp[42], resp[43]]) as u64;
99                let ntp_frac = u32::from_be_bytes([resp[44], resp[45], resp[46], resp[47]]);
100                if ntp_secs < NTP_UNIX_EPOCH_DELTA {
101                    return Err(ShellError::ExecutionFailed);
102                }
103                let unix_secs = ntp_secs - NTP_UNIX_EPOCH_DELTA;
104                let unix_nanos = (((ntp_frac as u128) * 1_000_000_000u128) >> 32) as u32;
105                return Ok((unix_secs, unix_nanos));
106            }
107            Ok(_) => {}
108            Err(_) => {}
109        }
110
111        crate::process::yield_task();
112        let elapsed = crate::process::scheduler::ticks().wrapping_sub(start_tick);
113        if elapsed >= timeout_ticks {
114            let _ = vfs::close(fd);
115            return Err(ShellError::ExecutionFailed);
116        }
117    }
118}
119
120pub fn cmd_ntpdate(args: &[String]) -> Result<(), ShellError> {
121    let server = args.first().map(|s| s.as_str()).unwrap_or("pool.ntp.org");
122    shell_println!("ntpdate: querying {}...", server);
123
124    let server_ip = match resolve_ntp_server(server) {
125        Ok(ip) => ip,
126        Err(_) => {
127            shell_println!("  resolve failed for {}", server);
128            return Err(ShellError::ExecutionFailed);
129        }
130    };
131
132    match ntp_query(&server_ip) {
133        Ok((unix_secs, unix_nanos)) => {
134            shell_println!("  server: {}", format_ipv4(&server_ip));
135            shell_println!("  unix:   {}.{:09} UTC", unix_secs, unix_nanos);
136            let ns = unix_secs
137                .saturating_mul(1_000_000_000)
138                .saturating_add(unix_nanos as u64);
139            crate::syscall::time::set_realtime_ns(ns);
140            shell_println!("  kernel realtime clock set");
141            Ok(())
142        }
143        Err(_) => {
144            shell_println!(
145                "  no valid NTP response from {} ({})",
146                server,
147                format_ipv4(&server_ip)
148            );
149            Err(ShellError::ExecutionFailed)
150        }
151    }
152}