1use serde::{Deserialize, Serialize};
9
10#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)]
12pub struct SampleReport {
13 pub offset_s: f64,
15 pub delay_s: f64,
17 pub stratum: u8,
19 pub root_delay_s: f64,
21 pub root_dispersion_s: f64,
22}
23
24#[derive(Clone, Debug, PartialEq, Eq, Hash)]
36pub enum ControlEndpoint {
37 UnixPath(String),
39 Loopback(u16),
41}
42
43const DERIVED_PORT_BASE: u16 = 49_200;
46const DERIVED_PORT_SPAN: u16 = 300;
47
48pub fn default_control_spec() -> String {
55 #[cfg(windows)]
56 {
57 "rusty_time".to_string()
58 }
59 #[cfg(not(windows))]
60 {
61 match std::env::var("XDG_RUNTIME_DIR") {
62 Ok(dir) if !dir.is_empty() => format!("{dir}/rusty_time.sock"),
63 _ => "/tmp/rusty_time.sock".to_string(),
64 }
65 }
66}
67
68pub fn control_endpoint(spec: &str) -> ControlEndpoint {
70 if let Some((_, port)) = spec.rsplit_once(':')
72 && let Ok(port) = port.parse::<u16>()
73 {
74 return ControlEndpoint::Loopback(port);
75 }
76
77 if cfg!(windows) {
78 ControlEndpoint::Loopback(derive_port(spec))
79 } else {
80 ControlEndpoint::UnixPath(spec.to_string())
81 }
82}
83
84fn derive_port(spec: &str) -> u16 {
87 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
88 for byte in spec.as_bytes() {
89 hash ^= *byte as u64;
90 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
91 }
92 DERIVED_PORT_BASE + (hash % DERIVED_PORT_SPAN as u64) as u16
93}
94
95#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
97pub struct NtsReport {
98 pub ke_host: String,
100 pub ntp_server: String,
102 pub ntp_port: u16,
103 pub authenticated: u32,
105 pub rejected: u32,
107 pub cookies_after: usize,
109}
110
111#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
113pub struct QueryReport {
114 pub server: String,
115 pub address: String,
116 pub sent: u32,
118 pub received: u32,
119 pub samples: Vec<SampleReport>,
120 pub best_offset_s: Option<f64>,
122 pub best_delay_s: Option<f64>,
123 pub regress_offset_s: Option<f64>,
125 pub regress_freq_ppm: Option<f64>,
126 pub regress_sd_s: Option<f64>,
127 pub reference_id: String,
129 pub leap: String,
130 #[serde(skip_serializing_if = "Option::is_none", default)]
132 pub nts: Option<NtsReport>,
133}
134
135#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
146pub struct TrackingReport {
147 pub synchronized: bool,
150 pub offset_s: f64,
151 pub freq_ppm: f64,
152 pub error_bound_s: f64,
153 pub poll_log2: i8,
154}
155
156#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
158pub struct ServerStatsReport {
159 pub ntp_requests: u64,
160 pub ntp_responses: u64,
161 pub dropped_rate_limit: u64,
162 pub kiss_of_death: u64,
163 pub interleaved_responses: u64,
164 pub refused: u64,
165 pub clients_tracked: usize,
166 pub clients_evicted: u64,
167 pub uptime_s: u64,
168 pub stratum: u8,
169}
170
171#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
173pub struct ClientRow {
174 pub address: String,
175 pub last_seen_ago_s: f64,
177 pub requests: u64,
178 pub responses: u64,
179 pub dropped: u64,
180 pub interleaved: bool,
182}
183
184#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
187#[serde(tag = "op", rename_all = "snake_case")]
188pub enum ControlRequest {
189 ServerStats,
191 Clients { limit: usize },
193 NtsData,
195 Tracking,
202 Ping,
204}
205
206#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
208#[serde(tag = "result", rename_all = "snake_case")]
209pub enum ControlResponse {
210 ServerStats(ServerStatsReport),
211 Clients {
216 rows: Vec<ClientRow>,
217 },
218 NtsData {
219 master_key_ids: Vec<u32>,
223 },
224 Tracking(TrackingReport),
229 Pong {
230 version: String,
231 },
232 Error {
233 message: String,
234 },
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240
241 #[test]
242 fn query_report_json_shape_is_stable() {
243 let r = QueryReport {
244 server: "pool.ntp.org".into(),
245 address: "1.2.3.4:123".into(),
246 sent: 4,
247 received: 4,
248 samples: vec![SampleReport {
249 offset_s: 0.0012,
250 delay_s: 0.031,
251 stratum: 2,
252 root_delay_s: 0.01,
253 root_dispersion_s: 0.002,
254 }],
255 best_offset_s: Some(0.0012),
256 best_delay_s: Some(0.031),
257 regress_offset_s: None,
258 regress_freq_ppm: None,
259 regress_sd_s: None,
260 reference_id: "c0a80101".into(),
261 leap: "no-warning".into(),
262 nts: None,
263 };
264 let json = serde_json::to_string(&r).expect("serialize");
265 let back: QueryReport = serde_json::from_str(&json).expect("deserialize");
266 assert_eq!(r, back);
267 assert!(json.contains("\"best_offset_s\""));
269 assert!(!json.contains("\"nts\""));
271 }
272
273 #[test]
274 fn the_default_spec_resolves_the_same_way_for_everyone() {
275 let a = control_endpoint(&default_control_spec());
280 let b = control_endpoint(&default_control_spec());
281 assert_eq!(a, b);
282 }
283
284 #[test]
285 fn an_explicit_port_is_honoured_on_every_platform() {
286 assert_eq!(
287 control_endpoint("127.0.0.1:9999"),
288 ControlEndpoint::Loopback(9999)
289 );
290 }
291
292 #[test]
293 fn the_same_path_resolves_identically_in_both_processes() {
294 let a = control_endpoint("/run/rusty_time.sock");
297 let b = control_endpoint("/run/rusty_time.sock");
298 assert_eq!(a, b, "resolution must be deterministic");
299 }
300
301 #[test]
302 fn different_names_get_different_endpoints() {
303 let mut seen = std::collections::HashSet::new();
306 let names = [
307 "/run/rusty_time.sock",
308 "/tmp/a.sock",
309 "/tmp/b.sock",
310 "rusty_time",
311 "test-rig-1",
312 "test-rig-2",
313 ];
314 for name in names {
315 seen.insert(control_endpoint(name));
316 }
317 assert!(
318 seen.len() >= names.len() - 1,
319 "control names collided: {seen:?}"
320 );
321 }
322
323 #[test]
324 fn derived_ports_stay_in_the_intended_range() {
325 for name in ["a", "b", "/very/long/path/to/a/socket", ""] {
326 let port = derive_port(name);
327 assert!(
328 (DERIVED_PORT_BASE..DERIVED_PORT_BASE + DERIVED_PORT_SPAN).contains(&port),
329 "{name} derived out-of-range port {port}"
330 );
331 }
332 }
333
334 #[cfg(unix)]
335 #[test]
336 fn a_path_stays_a_unix_socket_on_unix() {
337 assert_eq!(
338 control_endpoint("/run/rusty_time.sock"),
339 ControlEndpoint::UnixPath("/run/rusty_time.sock".into())
340 );
341 }
342
343 #[test]
344 fn control_ops_round_trip_over_the_wire() {
345 let requests = vec![
348 ControlRequest::Ping,
349 ControlRequest::ServerStats,
350 ControlRequest::Clients { limit: 10 },
351 ControlRequest::NtsData,
352 ];
353 for req in requests {
354 let json = serde_json::to_string(&req).expect("serialize");
355 let back: ControlRequest = serde_json::from_str(&json).expect("deserialize");
356 assert_eq!(req, back, "op did not survive the wire: {json}");
357 }
358
359 let responses = vec![
360 ControlResponse::Pong {
361 version: "0.1.0".into(),
362 },
363 ControlResponse::ServerStats(ServerStatsReport {
364 ntp_requests: 10,
365 ntp_responses: 8,
366 dropped_rate_limit: 2,
367 ..ServerStatsReport::default()
368 }),
369 ControlResponse::Clients {
370 rows: vec![ClientRow {
371 address: "192.0.2.1:123".into(),
372 last_seen_ago_s: 1.5,
373 requests: 3,
374 responses: 3,
375 dropped: 0,
376 interleaved: true,
377 }],
378 },
379 ControlResponse::NtsData {
380 master_key_ids: vec![1, 2],
381 },
382 ControlResponse::Error {
383 message: "nope".into(),
384 },
385 ];
386 for resp in responses {
387 let json = serde_json::to_string(&resp).expect("serialize");
388 let back: ControlResponse = serde_json::from_str(&json).expect("deserialize");
389 assert_eq!(resp, back);
390 }
391 }
392
393 #[test]
394 fn nts_data_never_carries_key_material() {
395 let resp = ControlResponse::NtsData {
397 master_key_ids: vec![0xDEAD_BEEF],
398 };
399 let json = serde_json::to_string(&resp).expect("serialize");
400 assert!(json.contains("master_key_ids"));
401 assert!(!json.contains("key\":\"") && !json.to_lowercase().contains("secret"));
402 }
403
404 #[test]
405 fn nts_report_round_trips() {
406 let mut r = QueryReport {
407 server: "time.cloudflare.com".into(),
408 address: "1.1.1.1:123".into(),
409 sent: 4,
410 received: 4,
411 samples: Vec::new(),
412 best_offset_s: Some(-0.002),
413 best_delay_s: Some(0.02),
414 regress_offset_s: None,
415 regress_freq_ppm: None,
416 regress_sd_s: None,
417 reference_id: "0a0a0a0a".into(),
418 leap: "no-warning".into(),
419 nts: Some(NtsReport {
420 ke_host: "time.cloudflare.com".into(),
421 ntp_server: "time.cloudflare.com".into(),
422 ntp_port: 123,
423 authenticated: 4,
424 rejected: 0,
425 cookies_after: 8,
426 }),
427 };
428 let json = serde_json::to_string(&r).expect("serialize");
429 assert!(json.contains("\"authenticated\":4"));
430 let back: QueryReport = serde_json::from_str(&json).expect("deserialize");
431 assert_eq!(r, back);
432 r.nts = None;
433 assert_ne!(r, back);
434 }
435}