strat9_kernel/shell/commands/util/
ntpdate.rs1use 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; fn 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
49fn format_ipv4(ip: &[u8; 4]) -> String {
51 alloc::format!("{}.{}.{}.{}", ip[0], ip[1], ip[2], ip[3])
52}
53
54fn 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 let mut req = [0u8; 48];
69 req[0] = 0x23;
70 req[2] = 6; req[3] = 0xEC; 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; 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}