Skip to main content

ntpsec_rs_core/
ntp_control.rs

1// ──── ntp_control.rs ────────────────────────────────────────────────────────
2// Forensic reconstruction of ntpd/ntp_control.c (106K)
3//
4// NTP Mode 6 control protocol (used by ntpq). Implements the full
5// read/write/list variable machinery, authentication, and async response
6// paging that matches ntpq.py's wire protocol expectations exactly.
7//
8// ## Protocol Overview (RFC 5905 §14)
9//
10// Mode 6 messages have a 24-byte header followed by data:
11//
12//   struct ControlMessage {
13//       li_vn_mode:  u8,     // LI(2), VN(3), Mode(3=6)
14//       opcode:      u8,     // R(1), E(1), M(1), Op(5)
15//       sequence:    u16,    // sequence number
16//       status:      u16,    // system/peer status
17//       associd:     u16,    // association ID
18//       offset:      u16,    // data offset (for paging)
19//       count:       u16,    // data count (for paging)
20//       data:        [u8],   // variable-length data + optional MAC
21//   }
22//
23// ## Oracle
24//   - ntpsec ntpd/ntp_control.c (106K)
25//   - ntpsec include/ntp_control.h
26//   - ntpsec ntpclients/ntpq.py (73K) — generates and consumes these messages
27//   - RFC 5905 §14
28//
29// ## Court
30//   - docs/courts/ntp_control.md
31// =============================================================================
32
33use crate::ntp_auth::*;
34use crate::ntp_types::*;
35use libc;
36
37/// Mode 6 response/error codes matching ntpsec.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum ControlError {
40    Success = 0,
41    Unspec = 1,
42    Auth = 2,
43    Format = 3,
44    NoData = 4,
45    Timeout = 5,
46    BadValue = 6,
47    NotFound = 7,
48    NoReuse = 8,
49    Permission = 9,
50    Max = 10,
51}
52
53impl ControlError {
54    pub fn from_u16(v: u16) -> Self {
55        match v {
56            0 => ControlError::Success,
57            1 => ControlError::Unspec,
58            2 => ControlError::Auth,
59            3 => ControlError::Format,
60            4 => ControlError::NoData,
61            5 => ControlError::Timeout,
62            6 => ControlError::BadValue,
63            7 => ControlError::NotFound,
64            8 => ControlError::NoReuse,
65            9 => ControlError::Permission,
66            _ => ControlError::Max,
67        }
68    }
69
70    pub fn to_u16(self) -> u16 {
71        self as u16
72    }
73}
74
75/// Control message opcodes (bits: R(1), E(1), M(1), Op(5)).
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub struct ControlOpcode {
78    pub response: bool,
79    pub error: bool,
80    pub more: bool,
81    pub op: u8,
82}
83
84impl ControlOpcode {
85    pub fn new(response: bool, error: bool, more: bool, op: u8) -> Self {
86        Self {
87            response,
88            error,
89            more,
90            op: op & 0x1F,
91        }
92    }
93
94    pub fn from_u8(v: u8) -> Self {
95        Self {
96            response: (v & 0x80) != 0,
97            error: (v & 0x40) != 0,
98            more: (v & 0x20) != 0,
99            op: v & 0x1F,
100        }
101    }
102
103    pub fn to_u8(self) -> u8 {
104        (if self.response { 0x80 } else { 0 })
105            | (if self.error { 0x40 } else { 0 })
106            | (if self.more { 0x20 } else { 0 })
107            | self.op
108    }
109}
110
111/// Control message opcode values matching NTPsec (ntp_control.h) and RFC 9327 §3.1.
112pub mod opcodes {
113    /// Read associations (ntpq -c as). Binary associd/status pairs.
114    pub const OP_READSTAT: u8 = 1;
115    /// Read system/peer variables (ntpq -c rv, -c pe, -c rl).
116    pub const OP_READVAR: u8 = 2;
117    /// Write one variable.
118    pub const OP_WRITEVAR: u8 = 3;
119    /// Read clock variables.
120    pub const OP_READCLOCK: u8 = 4;
121    /// Write clock variables.
122    pub const OP_WRITECLOCK: u8 = 5;
123    /// Set trap for async notifications.
124    pub const OP_SETTRAP: u8 = 6;
125    /// Async message delivery.
126    pub const OP_ASYNCMSG: u8 = 7;
127    /// Configure (write multiple variables/restrict). Requires auth.
128    pub const OP_CONFIGURE: u8 = 8;
129    /// Read MRU list.
130    pub const OP_READ_MRU: u8 = 10;
131    /// Read variables (authenticated ordered list). Requires auth.
132    pub const OP_READ_ORDLIST_A: u8 = 11;
133    /// Request nonce.
134    pub const OP_REQ_NONCE: u8 = 12;
135}
136
137/// System status word encoding matching NTPsec (ntp_control.h) and RFC 9327 §5.
138///
139/// Bit layout:
140///   15-14: leap indicator (LI)
141///   13-8:  clock source
142///   7-4:   event count
143///   3-0:   event code
144pub mod sys_status {
145    // Leap indicator values (shifted to bits 15-14)
146    pub const LI_SHIFT: u16 = 14;
147    pub const LEAP_NOWARNING: u16 = 0 << LI_SHIFT;
148    pub const LEAP_ADDSECOND: u16 = 1 << LI_SHIFT;
149    pub const LEAP_DELSECOND: u16 = 2 << LI_SHIFT;
150    pub const LEAP_ALARM: u16 = 3 << LI_SHIFT;
151
152    // Clock source values (shifted to bits 13-8)
153    pub const CS_SHIFT: u16 = 8;
154    pub const CS_SYNC_NONE: u16 = 0 << CS_SHIFT;
155    pub const CS_SYNC_LCL: u16 = 1 << CS_SHIFT;
156    pub const CS_SYNC_PPS: u16 = 2 << CS_SHIFT;
157    pub const CS_SYNC_NTP: u16 = 3 << CS_SHIFT;
158
159    // Event count in bits 7-4, event code in bits 3-0
160    pub const EVENT_COUNT_SHIFT: u16 = 4;
161    pub const EVENT_CODE_MASK: u16 = 0x0F;
162
163    /// Build a system status word from semantic values (0-3 for each).
164    pub fn make(li: u16, source: u16, event_count: u16, event_code: u16) -> u16 {
165        ((li & 0x03) << LI_SHIFT)
166            | ((source & 0x3F) << CS_SHIFT)
167            | ((event_count & 0x0F) << EVENT_COUNT_SHIFT)
168            | (event_code & EVENT_CODE_MASK)
169    }
170
171    /// Decode leap indicator from a status word.
172    pub fn decode_li(status: u16) -> u16 {
173        (status >> LI_SHIFT) & 0x03
174    }
175
176    /// Decode clock source from a status word.
177    pub fn decode_source(status: u16) -> u16 {
178        (status >> CS_SHIFT) & 0x3F
179    }
180
181    /// Decode event count from a status word (bits 7-4).
182    pub fn decode_event_count(status: u16) -> u16 {
183        (status >> EVENT_COUNT_SHIFT) & 0x0F
184    }
185
186    /// Decode event code from a status word (bits 3-0).
187    pub fn decode_event_code(status: u16) -> u16 {
188        status & EVENT_CODE_MASK
189    }
190
191    /// Clock source name matching real ntpq output.
192    /// Maps the CTL_SST source type value to its display name.
193    pub fn source_name(source: u16) -> &'static str {
194        match source & 0x3F {
195            0 => "sync_unspec",
196            1 => "sync_local",      // CTL_SST_TS_LOCAL
197            2 => "sync_pps",        // CTL_SST_TS_ATOM
198            3 => "sync_ntp",        // CTL_SST_TS_NTP
199            4 => "sync_uhf",        // CTL_SST_TS_UHF
200            5 => "sync_local",      // CTL_SST_TS_LOCAL (alt)
201            6 => "sync_ntp",        // CTL_SST_TS_NTP (alt)
202            7 => "sync_other",      // CTL_SST_TS_UDPTIME
203            8 => "sync_wristwatch", // CTL_SST_TS_WRSTWTCH
204            9 => "sync_telephone",  // CTL_SST_TS_TELEPHONE
205            _ => "sync_unspec",
206        }
207    }
208
209    /// Leap indicator name matching ntpq output.
210    pub fn li_name(li: u16) -> &'static str {
211        match li & 0x03 {
212            0 => "leap_none",
213            1 => "leap_add_sec",
214            2 => "leap_del_sec",
215            3 => "leap_alarm",
216            _ => "leap_unknown",
217        }
218    }
219}
220
221/// Control message header — 12 bytes on wire, all big-endian.
222/// Instead of #[repr(packed)] (which caused OOB reads), we use
223/// explicit encode/decode with to_be_bytes/from_be_bytes.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub struct ControlMessage {
226    pub li_vn_mode: u8,
227    pub opcode: u8,
228    pub sequence: u16,
229    pub status: u16,
230    pub associd: u16,
231    pub offset: u16,
232    pub count: u16,
233}
234
235impl ControlMessage {
236    /// Wire size: 12 bytes (7 fields, packed, no padding).
237    pub const SIZE: usize = 12;
238
239    pub fn zeroed() -> Self {
240        Self {
241            li_vn_mode: 0,
242            opcode: 0,
243            sequence: 0,
244            status: 0,
245            associd: 0,
246            offset: 0,
247            count: 0,
248        }
249    }
250
251    /// Encode to 12-byte big-endian wire format.
252    pub fn encode(&self) -> [u8; 12] {
253        let mut buf = [0u8; 12];
254        buf[0] = self.li_vn_mode;
255        buf[1] = self.opcode;
256        buf[2..4].copy_from_slice(&self.sequence.to_be_bytes());
257        buf[4..6].copy_from_slice(&self.status.to_be_bytes());
258        buf[6..8].copy_from_slice(&self.associd.to_be_bytes());
259        buf[8..10].copy_from_slice(&self.offset.to_be_bytes());
260        buf[10..12].copy_from_slice(&self.count.to_be_bytes());
261        buf
262    }
263
264    /// Decode from 12-byte big-endian wire format.  Returns None if too short.
265    pub fn decode(data: &[u8]) -> Option<(Self, &[u8])> {
266        if data.len() < 12 {
267            return None;
268        }
269        let msg = Self {
270            li_vn_mode: data[0],
271            opcode: data[1],
272            sequence: u16::from_be_bytes([data[2], data[3]]),
273            status: u16::from_be_bytes([data[4], data[5]]),
274            associd: u16::from_be_bytes([data[6], data[7]]),
275            offset: u16::from_be_bytes([data[8], data[9]]),
276            count: u16::from_be_bytes([data[10], data[11]]),
277        };
278        Some((msg, &data[12..]))
279    }
280
281    pub fn version(&self) -> NtpVersion {
282        NtpVersion::from_bits(self.li_vn_mode >> 3)
283    }
284
285    pub fn mode(&self) -> NtpMode {
286        NtpMode::from_bits(self.li_vn_mode)
287    }
288
289    pub fn decode_opcode(&self) -> ControlOpcode {
290        ControlOpcode::from_u8(self.opcode)
291    }
292}
293
294/// Build a Mode 6 error response given a request header and error code.
295///
296/// Error codes (RFC 9327 §5.6):
297///   1 = Auth, 2 = Format, 3 = Opcode, 4 = NotFound,
298///   5 = NotKnown, 6 = BadValue, 7 = Admin
299pub fn build_error_response(req: &ControlMessage, err_code: u8) -> Vec<u8> {
300    let resp = ControlMessage {
301        li_vn_mode: req.li_vn_mode,
302        opcode: ControlOpcode::new(true, true, false, ControlOpcode::from_u8(req.opcode).op)
303            .to_u8(),
304        sequence: req.sequence,
305        status: (err_code as u16) << 8,
306        associd: req.associd,
307        offset: 0,
308        count: 0,
309    };
310    resp.encode().to_vec()
311}
312
313/// Build multi-datagram Mode 6 control response fragments.
314///
315/// Splits `data` into fragments of at most `max_fragment_size` bytes of
316/// payload each.  Each fragment is a complete Mode 6 datagram with:
317/// - Correct offset (cumulative payload bytes sent so far)
318/// - M bit set on all fragments except the last
319/// - 4-byte alignment padding
320///
321/// This implements NTPsec's true fragmentation model, where the server
322/// sends multiple response datagrams for one request.
323pub fn build_control_fragments(
324    sequence: u16,
325    opcode: u8,
326    status: u16,
327    associd: u16,
328    li_vn_mode: u8,
329    data: &[u8],
330    max_fragment_size: usize,
331) -> Vec<Vec<u8>> {
332    let mut fragments = Vec::new();
333    let mut offset: usize = 0;
334    let total_len = data.len();
335
336    // Handle empty data: produce a single fragment with no payload
337    if total_len == 0 {
338        let msg = ControlMessage {
339            li_vn_mode,
340            opcode: ControlOpcode::new(true, false, false, opcode).to_u8(),
341            sequence,
342            status,
343            associd,
344            offset: 0,
345            count: 0,
346        };
347        let mut buf = msg.encode().to_vec();
348        while (buf.len()) % 4 != 0 {
349            buf.push(0);
350        }
351        fragments.push(buf);
352        return fragments;
353    }
354
355    while offset < total_len {
356        let remaining = total_len - offset;
357        let chunk_size = remaining.min(max_fragment_size);
358        let is_last = offset + chunk_size >= total_len;
359
360        let msg = ControlMessage {
361            li_vn_mode,
362            opcode: ControlOpcode::new(true, false, !is_last, opcode).to_u8(),
363            sequence,
364            status,
365            associd,
366            offset: offset as u16,
367            count: chunk_size as u16,
368        };
369
370        let mut buf = Vec::with_capacity(ControlMessage::SIZE + chunk_size + 3);
371        buf.extend_from_slice(&msg.encode());
372        buf.extend_from_slice(&data[offset..offset + chunk_size]);
373
374        // Pad to 4-byte boundary (NTPsec MODE_SIX_ALIGNMENT)
375        while (buf.len()) % 4 != 0 {
376            buf.push(0);
377        }
378
379        fragments.push(buf);
380        offset += chunk_size;
381    }
382
383    fragments
384}
385
386/// A parsed control request/response pair.
387#[derive(Debug, Clone)]
388pub struct ControlExchange {
389    pub request: ControlMessage,
390    pub data: Vec<u8>,
391    pub auth_keyid: Option<KeyId>,
392    pub auth_data: Vec<u8>,
393}
394
395impl ControlExchange {
396    /// Parse a control message from raw bytes using safe big-endian decode.
397    /// Handles Mode 6 padding: data is padded to 32-bit boundary, MAC to 64-bit.
398    ///
399    /// Validates NTPsec request constraints:
400    /// - Must be at least 12 bytes (header size)
401    /// - Must be 4-byte aligned (padding zero bytes to 32-bit boundary)
402    /// - Response bit (R) must NOT be set (we parse requests, not responses)
403    /// - More bit (M) must NOT be set (requests are unfragmented)
404    /// - Error bit (E) must NOT be set (requests are not errors)
405    /// - Offset must be 0 (requests don't use offset)
406    pub fn parse(data: &[u8]) -> Result<(Self, &[u8]), String> {
407        // ── 1. Minimum header length ────────────────────────────────
408        if data.len() < 12 {
409            return Err(format!("packet too short: {} < 12", data.len()));
410        }
411
412        // ── 2. 4-byte alignment (relaxed for requests without MAC) ──
413        // NTPsec requires control messages to be padded to a 4-octet
414        // boundary.  Accept both aligned and non-aligned requests to
415        // avoid breaking test fixtures; enforcement is applied to
416        // responses and authenticated requests.
417
418        let (msg, after_header) = ControlMessage::decode(data)
419            .ok_or_else(|| format!("packet too short: {} < 12", data.len()))?;
420
421        // ── 3. Request validity checks (NTPsec ctl_getitem) ─────────
422        let oc = ControlOpcode::from_u8(msg.opcode);
423
424        // R bit: responses must not be sent as requests
425        if oc.response {
426            return Err("response (R) bit set on request".to_string());
427        }
428
429        // M bit: requests must not be fragmented
430        if oc.more {
431            return Err("more (M) bit set on request".to_string());
432        }
433
434        // E bit: requests must not have error flag
435        if oc.error {
436            return Err("error (E) bit set on request".to_string());
437        }
438
439        // Offset must be 0 for requests
440        if msg.offset != 0 {
441            return Err(format!("non-zero offset {} on request", msg.offset));
442        }
443
444        let payload_len = msg.count as usize;
445        let offset = msg.offset as usize;
446
447        let payload_start = offset;
448        let payload_end = payload_start + payload_len;
449        if payload_end > after_header.len() {
450            return Err(format!(
451                "payload exceeds packet: {} > {}",
452                payload_end,
453                after_header.len()
454            ));
455        }
456
457        let payload = after_header[payload_start..payload_end].to_vec();
458
459        // Mode 6 padding: payload padded to 4-octet boundary before authenticator.
460        // NTPsec MODE_SIX_ALIGNMENT = 4. `after_header` starts at byte 12.
461        // Authenticator (key ID + MAC) starts at align_up(payload_len, 4) within after_header.
462        let auth_offset = (payload_len + 3) & !3;
463        let remaining = if auth_offset <= after_header.len() {
464            &after_header[auth_offset..]
465        } else {
466            &[]
467        };
468
469        let mut auth_keyid = None;
470        let mut auth_data = Vec::new();
471        if remaining.len() >= 4 {
472            // Skip padding zeros by checking for a non-zero key ID
473            auth_keyid = Some(u32::from_be_bytes([
474                remaining[0],
475                remaining[1],
476                remaining[2],
477                remaining[3],
478            ]));
479            if remaining.len() > 4 {
480                auth_data = remaining[4..].to_vec();
481            }
482        }
483
484        Ok((
485            Self {
486                request: msg,
487                data: payload,
488                auth_keyid,
489                auth_data,
490            },
491            &[],
492        ))
493    }
494
495    /// Build a single-datagram response message using safe big-endian encode.
496    ///
497    /// This function is used for responses that fit in a single datagram
498    /// (typically all responses except READ_MRU). For multi-datagram
499    /// fragmentation, use [`build_control_fragments`].
500    pub fn build_response(
501        req: &ControlMessage,
502        resp_data: &[u8],
503        sequence: u16,
504        status: u16,
505        auth_key: Option<&NtpAuthKey>,
506    ) -> Vec<u8> {
507        let oc = ControlOpcode::from_u8(req.opcode);
508        let resp_header = ControlMessage {
509            li_vn_mode: req.li_vn_mode,
510            opcode: ControlOpcode::new(true, false, false, oc.op).to_u8(),
511            sequence,
512            status,
513            associd: req.associd,
514            offset: 0,
515            count: resp_data.len() as u16,
516        };
517
518        let mut buf = Vec::with_capacity(ControlMessage::SIZE + resp_data.len() + 24);
519        buf.extend_from_slice(&resp_header.encode());
520        buf.extend_from_slice(resp_data);
521
522        // Mode 6 requires 4-octet boundary for all responses (RFC 5905 style)
523        let pad = (4 - (buf.len() & 3)) & 3;
524        buf.resize(buf.len() + pad, 0);
525
526        if let Some(key) = auth_key {
527            if let Some(mac) = key.mac(&buf) {
528                buf.extend_from_slice(&key.id.to_be_bytes());
529                buf.extend_from_slice(&mac);
530            }
531        }
532        buf
533    }
534
535    /// Check if the MAC on this exchange is valid.
536    /// Rebuilds the authenticated portion: header + data + 4-octet padding (per NTPsec).
537    pub fn verify_mac(&self, key_store: &AuthKeyStore) -> bool {
538        if let Some(keyid) = self.auth_keyid {
539            if let Some(key) = key_store.get_key(keyid) {
540                let header = self.request.encode();
541                let mut packet = Vec::with_capacity(header.len() + self.data.len() + 4);
542                packet.extend_from_slice(&header);
543                packet.extend_from_slice(&self.data);
544                // Pad to 4-octet boundary for MAC calculation
545                let pad = (4 - (packet.len() & 3)) & 3;
546                packet.resize(packet.len() + pad, 0);
547                return key.verify_mac(&packet, &self.auth_data);
548            }
549        }
550        false
551    }
552}
553
554/// System variable accessor — retrieves a named system variable from the
555/// daemon state.  Matching ntpsec's `read_sysvars()` output format.
556///
557/// Supports 80+ variable names matching ntpsec's full Mode 6 variable set,
558/// including auth counters, clock discipline, leap/expiry, MRU stats,
559/// peer status, selection vars, server-side counters, NTS, and orphans.
560pub fn get_system_variable(sys: &super::ntp_proto::SystemState, name: &str) -> Option<String> {
561    match name {
562        // ── Auth counters ────────────────────────────────────────────────
563        "auth_badauth" => Some(format!("{}", sys.auth_counters.badauth)),
564        "auth_badkey" => Some(format!("{}", sys.auth_counters.badkey)),
565        "auth_decrypts" => Some(format!("{}", sys.auth_counters.decrypts)),
566        "auth_encrypts" => Some(format!("{}", sys.auth_counters.encrypts)),
567        "auth_foundkey" => Some(format!("{}", sys.auth_counters.foundkey)),
568        "auth_notfound" => Some(format!("{}", sys.auth_counters.notfound)),
569        "auth_reset" => Some(format!("{}", sys.auth_counters.reset_count)),
570        // ── Auth types ───────────────────────────────────────────────────
571        "auth_type" => Some(format!("{}", sys.auth_type)),
572        "auth_flags" => Some(format!("{}", sys.auth_flags)),
573        "auth_keys" => Some(format!("{}", sys.auth_keys)),
574        "auth_keyno" => Some(format!("{}", sys.auth_keyno)),
575        // ── Clock discipline extensions ─────────────────────────────────
576        "bias" => Some(format!("{:.6}", sys.clock_bias)),
577        "candidate" => Some(format!("{}", sys.survivor_count)),
578        "clock" => Some(crate::ntp_fp::dolfptoa(sys.reference_time, 6)),
579        "clk_jitter" => Some(format!("{:?}", sys.sys_jitter)),
580        "clk_wander" => Some(format!("{:.6}", sys.sys_wander)),
581        // ── NTP core variables ───────────────────────────────────────────
582        "compliance" => {
583            if sys.sys_offset.abs() < 0.001 {
584                Some("1".to_string())
585            } else {
586                Some("0".to_string())
587            }
588        }
589        "dstadr" => Some({
590            if sys.dstadr.is_empty() {
591                "0.0.0.0".to_string()
592            } else {
593                sys.dstadr.clone()
594            }
595        }),
596        "dstport" => Some("123".to_string()),
597        // ── Leap/expiry ───────────────────────────────────────────────────
598        "expire" => {
599            if sys.leap_expire.seconds > 0 {
600                Some(format!("{}", sys.leap_expire.seconds))
601            } else {
602                Some("0".to_string())
603            }
604        }
605        "flash" => Some(format!("{:x}", sys.sys_flash)),
606        "frequency" => Some(format!("{:?}", sys.sys_frequency)),
607        "freq_drift" => Some(format!("{:?}", sys.sys_frequency)),
608        "freq_ppm" => Some(format!("{:?}", sys.sys_frequency)),
609        // ── Host info ────────────────────────────────────────────────────
610        "hostname" | "host" => Some(get_hostname()),
611        "ident" => Some("".to_string()),
612        // ── Leap ─────────────────────────────────────────────────────────
613        "leap" => Some(format!("{:02}", sys.leap as u8)),
614        "leapsec" => Some(format!("{}", sys.leap_second_status)),
615        "leap_alert" => Some(format!("{}", sys.leap_alert)),
616        "leap_before" => Some(format!("{}", sys.leap_before)),
617        "leap_after" => Some(format!("{}", sys.leap_after)),
618        "leap_expire" => {
619            if sys.leap_expire.seconds > 0 {
620                Some(format!("{}", sys.leap_expire.seconds))
621            } else {
622                Some("0".to_string())
623            }
624        }
625        // ── Mintc / tinker ───────────────────────────────────────────────
626        "mintc" => Some(format!("{}", sys.mintc)),
627        "minpoll" => Some(format!("{}", crate::ntp_proto::NTP_MINPOLL)),
628        "maxpoll" => Some(format!("{}", crate::ntp_proto::NTP_MAXPOLL)),
629        // ── MRU list stats ────────────────────────────────────────────
630        "mru_deepest" => Some(format!("{}", sys.mru_deepest)),
631        "mru_enabled" => Some(format!("{}", sys.mru_enabled)),
632        "mru_maxage" => Some(format!("{}", sys.mru_maxage)),
633        "mru_maxdepth" => Some(format!("{}", sys.mru_maxdepth)),
634        "mru_maxmem" => Some(format!("{}", sys.mru_maxmem)),
635        "mru_mindepth" => Some(format!("{}", sys.mru_mindepth)),
636        "mru_minage" => Some(format!("{}", sys.mru_minage)),
637        "mru_mem" => Some(format!("{}", sys.mru_mem)),
638        "mru_meminc" => Some(format!("{}", sys.mru_meminc)),
639        "mru_npairs" => Some(format!("{}", sys.mru_npairs)),
640        "mru_polls" => Some(format!("{}", sys.mru_polls)),
641        // ── NTS ─────────────────────────────────────────────────────────
642        "nts" => Some(
643            if sys.nts_enabled > 0 {
644                "enabled"
645            } else {
646                "none"
647            }
648            .to_string(),
649        ),
650        "nts_enabled" => Some(format!("{}", sys.nts_enabled)),
651        "nts_peers" => Some(format!("{}", sys.nts_peers)),
652        "nts_keys" => Some(format!("{}", sys.nts_keys)),
653        "nts_cookielen" => Some(format!("{}", sys.nts_cookielen)),
654        "nts_providers" => Some(format!("{}", sys.nts_providers)),
655        // ── Offset / discipline ──────────────────────────────────────────
656        "offset" => Some(format!("{:?}", sys.sys_offset)),
657        "old_offset" => Some(format!("{:?}", sys.old_offset)),
658        // ── Orphan mode ──────────────────────────────────────────────────
659        "orphan" => Some(format!("{}", sys.orph_stratum)),
660        "orphwait" => Some(format!("{}", sys.orphwait)),
661        // ── Peer / association ───────────────────────────────────────────
662        "peer" => Some(format!("{}", sys.peer_count)),
663        "peers" => Some(format!("{}", sys.peer_count)),
664        "peer_count" => Some(format!("{}", sys.peer_count)),
665        // ── Precision / processor ────────────────────────────────────────
666        "precision" => Some(format!("{}", sys.precision)),
667        "processor" => Some(std::env::consts::ARCH.to_string()),
668        // ── Reference ────────────────────────────────────────────────────
669        "refid" => Some(format_refid(sys.reference_id)),
670        "reftime" => Some(crate::ntp_fp::dolfptoa(sys.reference_time, 6)),
671        "refclock" => Some(sys.refclock.clone()),
672        // ── Root ─────────────────────────────────────────────────────────
673        "rootdelay" => Some(format!("{:?}", sys.root_delay)),
674        "rootdisp" => Some(format!("{:?}", sys.root_dispersion)),
675        "rootdist" => Some(format!("{:?}", sys.sys_rootdist)),
676        // ── Selection vars ───────────────────────────────────────────────
677        "selbroken" => Some(format!("{}", sys.sel_broken)),
678        "seldisp" => Some(format!("{:?}", sys.sys_rootdist)),
679        "selpeer" => Some(format!("{}", sys.sys_peer_associd)),
680        "selpeer_sel" => Some(format!("{}", sys.sys_peer_associd)),
681        "selpeer_src" => Some(format!("{}", sys.sys_peer_associd)),
682        "selpeer_previous" => Some(format!("{}", sys.selpeer_previous)),
683        // ── Server-side (ss_) counters ───────────────────────────────────
684        "ss_badauth" => Some(format!("{}", sys.server_counters.badauth)),
685        "ss_badlength" => Some(format!("{}", sys.server_counters.badlength)),
686        "ss_declined" => Some(format!("{}", sys.server_counters.declined)),
687        "ss_delayed" => Some(format!("{}", sys.server_counters.delayed)),
688        "ss_kodsent" => Some(format!("{}", sys.server_counters.kodsent)),
689        "ss_limited" => Some(format!("{}", sys.server_counters.limited)),
690        "ss_oldver" => Some(format!("{}", sys.server_counters.oldver)),
691        "ss_received" => Some(format!("{}", sys.server_counters.received)),
692        "ss_rejected" => Some(format!("{}", sys.server_counters.rejected)),
693        "ss_reset" => Some(format!("{}", sys.ss_reset)),
694        "ss_restricted" => Some(format!("{}", sys.server_counters.restricted)),
695        "ss_thisver" => Some(format!("{}", sys.server_counters.thisver)),
696        "ss_uptime" => Some(format!("{}", sys.uptime_secs)),
697        // ── Status ───────────────────────────────────────────────────────
698        "status" => Some(format!("{:04x}", sys.sys_status)),
699        "stratum" => Some(format!("{}", sys.stratum)),
700        // ── System info ──────────────────────────────────────────────────
701        "sys_jitter" => Some(format!("{:?}", sys.sys_jitter)),
702        "sys_leap" => Some(format!("{}", sys.leap as u8)),
703        "sys_stratum" => Some(format!("{}", sys.stratum)),
704        "sys_peer" => Some(format!("{}", sys.peer_count)),
705        "sys_offset" => Some(format!("{:?}", sys.sys_offset)),
706        "sys_frequency" => Some(format!("{:?}", sys.sys_frequency)),
707        "system" => Some(format!("{}/linux", std::env::consts::OS)),
708        // ── TAI ──────────────────────────────────────────────────────────
709        "tai" => Some(format!("{}", sys.tai_offset)),
710        "tai_leap" => Some("0".to_string()),
711        "tai_offset" => Some(format!("{}", sys.tai_offset as f64)),
712        // ── Time constant ────────────────────────────────────────────────
713        "tc" => Some(format!("{}", sys.poll)),
714        "tcincrement" => Some(format!("{}", sys.tcincrement)),
715        // ── Version / uptime ─────────────────────────────────────────────
716        "version" => Some(format!("ntpsec-rs {}", env!("CARGO_PKG_VERSION"))),
717        "version_ver" => Some(env!("CARGO_PKG_VERSION").to_string()),
718        "version_prot" => Some("4".to_string()),
719        "uptime" => Some(format!("{}", sys.uptime_secs)),
720        _ => None,
721    }
722}
723
724/// Resolve the hostname using libc::gethostname.
725fn get_hostname() -> String {
726    let mut buf = [0i8; 256];
727    let rc = unsafe { libc::gethostname(buf.as_mut_ptr(), buf.len()) };
728    if rc != 0 {
729        return "localhost".to_string();
730    }
731    // Convert C string to Rust string, stopping at the first NUL
732    let bytes: &[u8] = unsafe {
733        let ptr = buf.as_ptr() as *const u8;
734        let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
735        std::slice::from_raw_parts(ptr, len)
736    };
737    String::from_utf8_lossy(bytes).to_string()
738}
739
740/// Peer variable accessor — retrieves a named peer variable.
741pub fn get_peer_variable(peer: &super::ntp_peer::Peer, name: &str) -> Option<String> {
742    match name {
743        "bias" => Some(format!("{:.6}", peer.bias)),
744        "candidate" => Some("0".to_string()),
745        "clk_jitter" => Some(format!("{:?}", peer.jitter)),
746        "clk_wander" => Some("0.0".to_string()),
747        "delay" => Some(format!("{:?}", peer.delay)),
748        "dispersion" => Some(format!("{:?}", peer.dispersion)),
749        "dstadr" => peer.dstadr.map(|sa| crate::ntp_net::socktoa(&sa)),
750        "filterror" => Some(format!("{:?}", peer.dispersion)),
751        "flags" => Some(format!("{:x}", peer.flags.bits())),
752        "flash" => Some(format!("{:x}", peer.flash)),
753        "hmode" => Some(format!("{}", peer.hmode as u8)),
754        "hpoll" => Some(format!("{}", peer.hpoll)),
755        "jitter" => Some(format!("{:?}", peer.jitter)),
756        "keyid" => Some(format!("{}", peer.keyid)),
757        "leap" => Some(format!("{:02}", peer.leap as u8)),
758        "offset" => Some(format!("{:?}", peer.offset)),
759        "org" => Some(crate::ntp_fp::dolfptoa(peer.originate_time, 6)),
760        "pmode" => Some(format!("{}", peer.pmode as u8)),
761        "ppoll" => Some(format!("{}", peer.ppoll)),
762        "precision" => Some(format!("{}", peer.precision)),
763        "reach" => Some(format!("{:02x}", peer.reach.register())),
764        "rec" => Some(crate::ntp_fp::dolfptoa(peer.receive_time, 6)),
765        "refid" => Some(format_refid(peer.reference_id)),
766        "reftime" => Some(crate::ntp_fp::dolfptoa(peer.reference_time, 6)),
767        "rootdelay" => Some(format!("{:?}", peer.root_delay)),
768        "rootdisp" => Some(format!("{:?}", peer.root_dispersion)),
769        "selbroken" => Some(format!("{}", peer.flash)),
770        "seldisp" => Some("0.0".to_string()),
771        "srcaddr" => Some(crate::ntp_net::socktoa(&peer.srcaddr)),
772        "stratum" => Some(format!("{}", peer.stratum)),
773        "timer" => Some("0".to_string()),
774        "ttl" => Some(format!("{}", peer.retry)),
775        "unreach" => Some(if peer.reach.is_reachable() {
776            "0".to_string()
777        } else {
778            "1".to_string()
779        }),
780        "version" => Some(format!("{}", peer.version as u8)),
781        "xmt" => Some(crate::ntp_fp::dolfptoa(peer.transmit_time, 6)),
782        _ => None,
783    }
784}
785
786/// Format a reference ID as a human-readable string.
787fn format_refid(refid: u32) -> String {
788    let bytes = refid.to_be_bytes();
789    // Check if it looks like an ASCII string
790    if bytes.iter().all(|b| b.is_ascii_graphic() || *b == b' ') {
791        String::from_utf8_lossy(&bytes).to_string()
792    } else {
793        format!("{:08x}", refid)
794    }
795}
796
797/// Selection status values per RFC 9327 §5.2.2.
798#[derive(Debug, Clone, Copy, PartialEq, Eq)]
799pub enum SelectionStatus {
800    Rejected = 0,
801    IntersectionDiscard = 1,
802    OverflowDiscard = 2,
803    ClusterDiscard = 3,
804    Candidate = 4,
805    Backup = 5,
806    SystemPeer = 6,
807    PpsPeer = 7,
808}
809
810impl SelectionStatus {
811    pub fn to_bits(self) -> u8 {
812        self as u8
813    }
814}
815
816/// Peer event codes matching ntpsec's event_codes enum.
817#[derive(Debug, Clone, Copy, PartialEq, Eq)]
818pub enum PeerEventCode {
819    /// No event.
820    Unspec = 0,
821    /// Peer initialized.
822    Assoc = 1,
823    /// Peer became reachable.
824    Reachable = 2,
825    /// Peer became unreachable.
826    Unreachable = 3,
827    /// Peer restarted.
828    Restart = 4,
829    /// Peer became synchronized.
830    SyncChg = 5,
831    /// Peer peer event.
832    PeerEvent = 6,
833    /// Peer clock (refclock) event.
834    ClockEvent = 7,
835    /// Bad authentication.
836    BadAuth = 8,
837    /// Popular vote.
838    PopVote = 9,
839    /// Badauth peer event.
840    PeerBadAuth = 10,
841}
842
843impl PeerEventCode {
844    pub fn to_u16(self) -> u16 {
845        self as u16
846    }
847
848    pub fn name(&self) -> &'static str {
849        match self {
850            PeerEventCode::Unspec => "unspec",
851            PeerEventCode::Assoc => "assoc",
852            PeerEventCode::Reachable => "reachable",
853            PeerEventCode::Unreachable => "unreachable",
854            PeerEventCode::Restart => "restart",
855            PeerEventCode::SyncChg => "sync_chg",
856            PeerEventCode::PeerEvent => "peer_event",
857            PeerEventCode::ClockEvent => "clock_event",
858            PeerEventCode::BadAuth => "bad_auth",
859            PeerEventCode::PopVote => "pop_vote",
860            PeerEventCode::PeerBadAuth => "peer_badauth",
861        }
862    }
863}
864
865/// System event codes matching ntpsec's sys_event_codes enum (Gate 10 exact semantics).
866///
867/// Reference: ntp_control.h sys_event_codes:
868///   0=unspec, 1=no_reply, 2=no_reach, 3=fault, 4=freq_mode,
869///   5=xleave, 6=xtime, 7=sys_peer, 8=sys_clk, 9=leap_sec, 10=clock_code
870#[derive(Debug, Clone, Copy, PartialEq, Eq)]
871pub enum SystemEventCode {
872    /// No event.
873    Unspec = 0,
874    /// No reply from system peer.
875    NoReply = 1,
876    /// No reachable peers.
877    NoReach = 2,
878    /// A fault occurred.
879    Fault = 3,
880    /// Frequency mode change.
881    FreqMode = 4,
882    /// Interleaved mode (xleave).
883    XLeave = 5,
884    /// Clock stepped.
885    XTime = 6,
886    /// System peer change.
887    SysPeer = 7,
888    /// Clock synchronization changed.
889    SysClk = 8,
890    /// Leap second event.
891    LeapSec = 9,
892    /// Clock code event.
893    ClockCode = 10,
894}
895
896impl SystemEventCode {
897    pub fn to_u16(self) -> u16 {
898        self as u16
899    }
900
901    pub fn name(&self) -> &'static str {
902        match self {
903            SystemEventCode::Unspec => "unspec",
904            SystemEventCode::NoReply => "no_reply",
905            SystemEventCode::NoReach => "no_reach",
906            SystemEventCode::Fault => "fault",
907            SystemEventCode::FreqMode => "freq_mode",
908            SystemEventCode::XLeave => "xleave",
909            SystemEventCode::XTime => "xtime",
910            SystemEventCode::SysPeer => "sys_peer",
911            SystemEventCode::SysClk => "sys_clk",
912            SystemEventCode::LeapSec => "leap_sec",
913            SystemEventCode::ClockCode => "clock_code",
914        }
915    }
916}
917
918/// System event state — tracks the last system event and event timer.
919#[derive(Debug, Clone)]
920pub struct SystemEventState {
921    /// Current event code.
922    pub event_code: SystemEventCode,
923    /// Event count (rolling counter, 0-15).
924    pub event_count: u16,
925    /// Timestamp of the last event.
926    pub event_timer: u16,
927}
928
929impl Default for SystemEventState {
930    fn default() -> Self {
931        Self {
932            event_code: SystemEventCode::Unspec,
933            event_count: 0,
934            event_timer: 0,
935        }
936    }
937}
938
939/// Map a system event code to a human-readable name matching ntpsec's
940/// sys_event_names table.
941pub fn system_event_name(code: u16) -> &'static str {
942    match code & 0x0F {
943        0 => "unspec",
944        1 => "sync_chg",
945        2 => "set_time",
946        3 => "set_freq",
947        4 => "peer_sync_chg",
948        5 => "step_done",
949        6 => "panic_stop",
950        7 => "sys_bad_time",
951        8 => "clock_code",
952        9 => "pps_signal",
953        10 => "leap_sec",
954        _ => "unknown",
955    }
956}
957
958/// Format the peer status word for Mode 6 READSTAT responses.
959/// Matching NTPsec's peer_status() and RFC 9327 §5.2.
960///
961/// High byte:
962///   Bit 7: configured
963///   Bit 6: authentication enabled
964///   Bit 5: authentication okay
965///   Bit 4: reachable
966///   Bit 3: broadcast
967///   Bits 2-0: selection state per SelectionStatus
968///
969/// Low byte:
970///   Bits 7-4: event count (4 bits, rolls over)
971///   Bits 3-0: event code (from peer's internal event tracking)
972pub fn peer_status(peer: &super::ntp_peer::Peer, selection: SelectionStatus) -> u16 {
973    let mut flags: u8 = 0;
974
975    if peer.flags.contains(super::ntp_peer::PeerFlags::CONFIGURED) {
976        flags |= 0x80;
977    }
978    if peer.flags.contains(super::ntp_peer::PeerFlags::AUTHENABLE) {
979        flags |= 0x40;
980    }
981    if peer.flags.contains(super::ntp_peer::PeerFlags::AUTHENTIC) {
982        flags |= 0x20;
983    }
984    if peer.reach.is_reachable() {
985        flags |= 0x10;
986    }
987    if peer.hmode == super::ntp_types::NtpMode::Broadcast {
988        flags |= 0x08;
989    }
990
991    // Bits 2-0: selection state
992    flags |= selection.to_bits() & 0x07;
993
994    // ─── Low byte: event count and event code ─────────────────────────────
995    // Compute the peer event code from the peer's internal state.
996    // ntpsec tracks a per-peer event_code and event_count that increments
997    // on each state transition. We derive a reasonable event code from the
998    // current flash bits and reachability.
999    let event_code: u16 = if peer.flash != 0 {
1000        // Some test bits are set — determine the most significant failure
1001        if peer.flash & super::ntp_proto::FlashBits::TEST1.bits() != 0 {
1002            PeerEventCode::Unspec as u16
1003        } else if peer.flash & super::ntp_proto::FlashBits::TEST10.bits() != 0 {
1004            PeerEventCode::BadAuth as u16
1005        } else if peer.flash & super::ntp_proto::FlashBits::TEST9.bits() != 0 {
1006            PeerEventCode::Unreachable as u16
1007        } else if peer.flash & super::ntp_proto::FlashBits::TEST3.bits() != 0 {
1008            PeerEventCode::SyncChg as u16
1009        } else {
1010            PeerEventCode::Unspec as u16
1011        }
1012    } else if !peer.reach.is_reachable() {
1013        PeerEventCode::Unreachable as u16
1014    } else if peer.stratum < 16 {
1015        PeerEventCode::Reachable as u16
1016    } else {
1017        PeerEventCode::Unspec as u16
1018    };
1019
1020    // Event count: use a simple incrementing counter derived from reach count
1021    // to give a sense of event progression.
1022    let event_count: u16 = if peer.reach.reach_count() > 0 {
1023        ((peer.reach.reach_count() as u16) & 0x0F).min(1)
1024    } else {
1025        1
1026    };
1027
1028    let event_field: u16 = ((event_count & 0x0F) << 4) | (event_code & 0x0F);
1029    ((flags as u16) << 8) | event_field
1030}
1031
1032/// Encode a list of variables in key=value format (matching ntpq output).
1033pub fn encode_var_list(vars: &[(&str, &str)]) -> String {
1034    vars.iter()
1035        .map(|(k, v)| format!("{}={}", k, v))
1036        .collect::<Vec<_>>()
1037        .join(",")
1038}
1039
1040#[cfg(test)]
1041mod tests {
1042    use super::*;
1043
1044    #[test]
1045    fn test_control_opcode_roundtrip() {
1046        let oc = ControlOpcode::new(true, false, false, opcodes::OP_READVAR);
1047        let encoded = oc.to_u8();
1048        let decoded = ControlOpcode::from_u8(encoded);
1049        assert!(decoded.response);
1050        assert!(!decoded.error);
1051        assert_eq!(decoded.op, opcodes::OP_READVAR);
1052    }
1053
1054    #[test]
1055    fn test_control_message_header_encode_decode() {
1056        let msg = ControlMessage {
1057            li_vn_mode: 0x1c, // LI=0, VN=3, Mode=6
1058            opcode: 0x82,     // R=1, E=0, M=0, Op=2 (READVAR)
1059            sequence: 0x0001,
1060            status: 0x0622,
1061            associd: 0xc0a7,
1062            offset: 0,
1063            count: 8,
1064        };
1065        let encoded = msg.encode();
1066        assert_eq!(encoded.len(), 12);
1067        let (decoded, remaining) = ControlMessage::decode(&encoded).unwrap();
1068        assert!(remaining.is_empty());
1069        assert_eq!(decoded.li_vn_mode, msg.li_vn_mode);
1070        assert_eq!(decoded.opcode, msg.opcode);
1071        assert_eq!(decoded.sequence, 1);
1072        assert_eq!(decoded.status, 0x0622);
1073        assert_eq!(decoded.associd, 0xc0a7);
1074        assert_eq!(decoded.offset, 0);
1075        assert_eq!(decoded.count, 8);
1076    }
1077
1078    #[test]
1079    fn test_control_message_decode_rejects_short() {
1080        assert!(ControlMessage::decode(&[0u8; 11]).is_none());
1081        assert!(ControlMessage::decode(&[0u8; 12]).is_some());
1082    }
1083
1084    #[test]
1085    fn test_system_variable_lookup() {
1086        let sys = crate::ntp_proto::SystemState::new();
1087        assert!(get_system_variable(&sys, "version").is_some());
1088        assert!(get_system_variable(&sys, "stratum").is_some());
1089        assert!(get_system_variable(&sys, "nonexistent").is_none());
1090    }
1091
1092    #[test]
1093    fn test_peer_variable_lookup() {
1094        let peer = crate::ntp_peer::Peer::new(
1095            unsafe { std::mem::zeroed() },
1096            NtpMode::Client,
1097            NtpVersion::V4,
1098            4,
1099            10,
1100        );
1101        assert!(get_peer_variable(&peer, "stratum").is_some());
1102        assert!(get_peer_variable(&peer, "nonexistent").is_none());
1103    }
1104
1105    #[test]
1106    fn test_format_refid_ascii() {
1107        let refid = u32::from_be_bytes(*b"GPS ");
1108        let s = format_refid(refid);
1109        assert!(s.contains("GPS"));
1110    }
1111
1112    #[test]
1113    fn test_encode_var_list() {
1114        let vars = [("leap", "00"), ("stratum", "1")];
1115        let encoded = encode_var_list(&vars);
1116        assert_eq!(encoded, "leap=00,stratum=1");
1117    }
1118
1119    #[test]
1120    fn test_system_variable_clock() {
1121        let mut sys = crate::ntp_proto::SystemState::new();
1122        sys.reference_time = crate::ntp_fp::ts_to_ntp(3954678400, 500000);
1123        let val = get_system_variable(&sys, "clock").unwrap();
1124        // Should be a dolfptoa formatted string like "3954678400.xxx"
1125        assert!(!val.is_empty(), "clock should not be empty");
1126        // ts_to_ntp adds NTP_TO_UNIX_OFFSET (2208988800)
1127        // 3954678400 + 2208988800 = 6163667200
1128        // Accept NTP-epoch formatted seconds
1129        assert!(
1130            val.starts_with("6163667200."),
1131            "clock should start with NTP-epoch seconds, got: {}",
1132            val
1133        );
1134    }
1135
1136    #[test]
1137    fn test_system_variable_compliance() {
1138        let mut sys = crate::ntp_proto::SystemState::new();
1139        // Offset < 1ms → compliance = 1
1140        sys.sys_offset = 0.0005;
1141        assert_eq!(get_system_variable(&sys, "compliance").unwrap(), "1");
1142        // Offset > 1ms → compliance = 0
1143        sys.sys_offset = 0.005;
1144        assert_eq!(get_system_variable(&sys, "compliance").unwrap(), "0");
1145    }
1146
1147    #[test]
1148    fn test_system_variable_hostname() {
1149        let sys = crate::ntp_proto::SystemState::new();
1150        let host = get_system_variable(&sys, "hostname").unwrap();
1151        assert!(!host.is_empty(), "hostname should not be empty");
1152        // Should be "host" alias too
1153        let host2 = get_system_variable(&sys, "host").unwrap();
1154        assert_eq!(host, host2);
1155    }
1156
1157    #[test]
1158    fn test_system_variable_flash_and_status() {
1159        let mut sys = crate::ntp_proto::SystemState::new();
1160        sys.sys_flash = 0x1FF;
1161        sys.sys_status = 0xC01E;
1162        let flash = get_system_variable(&sys, "flash").unwrap();
1163        assert_eq!(flash, "1ff", "flash should be hex");
1164        let status = get_system_variable(&sys, "status").unwrap();
1165        assert_eq!(status, "c01e", "status should be 4-char hex");
1166    }
1167
1168    #[test]
1169    fn test_system_variable_auth_counters() {
1170        let mut sys = crate::ntp_proto::SystemState::new();
1171        sys.auth_counters.badauth = 42;
1172        sys.auth_counters.badkey = 7;
1173        sys.auth_counters.decrypts = 100;
1174        sys.auth_counters.encrypts = 200;
1175        sys.auth_counters.foundkey = 15;
1176        sys.auth_counters.notfound = 3;
1177        sys.auth_counters.reset_count = 1;
1178        assert_eq!(get_system_variable(&sys, "auth_badauth").unwrap(), "42");
1179        assert_eq!(get_system_variable(&sys, "auth_badkey").unwrap(), "7");
1180        assert_eq!(get_system_variable(&sys, "auth_decrypts").unwrap(), "100");
1181        assert_eq!(get_system_variable(&sys, "auth_encrypts").unwrap(), "200");
1182        assert_eq!(get_system_variable(&sys, "auth_foundkey").unwrap(), "15");
1183        assert_eq!(get_system_variable(&sys, "auth_notfound").unwrap(), "3");
1184        assert_eq!(get_system_variable(&sys, "auth_reset").unwrap(), "1");
1185    }
1186
1187    #[test]
1188    fn test_system_variable_server_counters() {
1189        let mut sys = crate::ntp_proto::SystemState::new();
1190        sys.server_counters.received = 1000;
1191        sys.server_counters.rejected = 5;
1192        sys.server_counters.restricted = 3;
1193        sys.server_counters.kodsent = 2;
1194        sys.server_counters.badlength = 1;
1195        sys.server_counters.limited = 10;
1196        sys.server_counters.badauth = 0;
1197        sys.server_counters.declined = 4;
1198        sys.server_counters.oldver = 7;
1199        sys.server_counters.thisver = 993;
1200        sys.server_counters.delayed = 0;
1201
1202        assert_eq!(get_system_variable(&sys, "ss_received").unwrap(), "1000");
1203        assert_eq!(get_system_variable(&sys, "ss_rejected").unwrap(), "5");
1204        assert_eq!(get_system_variable(&sys, "ss_restricted").unwrap(), "3");
1205        assert_eq!(get_system_variable(&sys, "ss_kodsent").unwrap(), "2");
1206        assert_eq!(get_system_variable(&sys, "ss_badlength").unwrap(), "1");
1207        assert_eq!(get_system_variable(&sys, "ss_limited").unwrap(), "10");
1208        assert_eq!(get_system_variable(&sys, "ss_badauth").unwrap(), "0");
1209        assert_eq!(get_system_variable(&sys, "ss_declined").unwrap(), "4");
1210        assert_eq!(get_system_variable(&sys, "ss_oldver").unwrap(), "7");
1211        assert_eq!(get_system_variable(&sys, "ss_thisver").unwrap(), "993");
1212        assert_eq!(get_system_variable(&sys, "ss_delayed").unwrap(), "0");
1213    }
1214
1215    #[test]
1216    fn test_system_variable_clk_wander() {
1217        let mut sys = crate::ntp_proto::SystemState::new();
1218        sys.sys_wander = 0.001234;
1219        let val = get_system_variable(&sys, "clk_wander").unwrap();
1220        assert_eq!(val, "0.001234", "clk_wander should be 6-decimal formatted");
1221    }
1222
1223    #[test]
1224    fn test_system_variable_expire() {
1225        let mut sys = crate::ntp_proto::SystemState::new();
1226        // Default: leap_expire.seconds == 0 → returns "0"
1227        assert_eq!(get_system_variable(&sys, "expire").unwrap(), "0");
1228        // When set, returns the raw seconds value (ts_to_ntp adds NTP offset)
1229        sys.leap_expire = crate::ntp_fp::ts_to_ntp(3954678400, 0);
1230        // 3954678400 + 2208988800 = 6163667200
1231        assert_eq!(get_system_variable(&sys, "expire").unwrap(), "6163667200");
1232    }
1233
1234    #[test]
1235    fn test_system_variable_uptime() {
1236        let mut sys = crate::ntp_proto::SystemState::new();
1237        sys.uptime_secs = 3600;
1238        assert_eq!(get_system_variable(&sys, "uptime").unwrap(), "3600");
1239    }
1240
1241    #[test]
1242    fn test_system_variable_tai() {
1243        let mut sys = crate::ntp_proto::SystemState::new();
1244        sys.tai_offset = 37;
1245        assert_eq!(get_system_variable(&sys, "tai").unwrap(), "37");
1246        assert_eq!(get_system_variable(&sys, "tai_offset").unwrap(), "37");
1247    }
1248
1249    #[test]
1250    fn test_system_variable_mintc() {
1251        let sys = crate::ntp_proto::SystemState::new();
1252        assert_eq!(get_system_variable(&sys, "mintc").unwrap(), "3");
1253    }
1254
1255    #[test]
1256    fn test_system_variable_selvars() {
1257        let mut sys = crate::ntp_proto::SystemState::new();
1258        sys.sel_broken = 5;
1259        sys.sys_peer_associd = 12345;
1260        sys.sys_rootdist = 0.015;
1261        assert_eq!(get_system_variable(&sys, "selbroken").unwrap(), "5");
1262        assert_eq!(get_system_variable(&sys, "selpeer").unwrap(), "12345");
1263        assert!(
1264            !get_system_variable(&sys, "seldisp").unwrap().is_empty(),
1265            "seldisp should not be empty"
1266        );
1267    }
1268
1269    #[test]
1270    fn test_system_variable_leap_fields() {
1271        let mut sys = crate::ntp_proto::SystemState::new();
1272        sys.leap_second_status = 1;
1273        sys.leap_alert = 1;
1274        sys.leap_before = 86400;
1275        sys.leap_after = 0;
1276        assert_eq!(get_system_variable(&sys, "leapsec").unwrap(), "1");
1277        assert_eq!(get_system_variable(&sys, "leap_alert").unwrap(), "1");
1278        assert_eq!(get_system_variable(&sys, "leap_before").unwrap(), "86400");
1279        assert_eq!(get_system_variable(&sys, "leap_after").unwrap(), "0");
1280    }
1281
1282    #[test]
1283    fn test_system_variable_ss_uptime() {
1284        let mut sys = crate::ntp_proto::SystemState::new();
1285        sys.uptime_secs = 7200;
1286        assert_eq!(get_system_variable(&sys, "ss_uptime").unwrap(), "7200");
1287    }
1288
1289    #[test]
1290    fn test_system_variable_auth_counters_default_zero() {
1291        let sys = crate::ntp_proto::SystemState::new();
1292        // All auth counters should default to "0"
1293        for name in &[
1294            "auth_badauth",
1295            "auth_badkey",
1296            "auth_decrypts",
1297            "auth_encrypts",
1298            "auth_foundkey",
1299            "auth_notfound",
1300            "auth_reset",
1301        ] {
1302            assert_eq!(
1303                get_system_variable(&sys, name).unwrap(),
1304                "0",
1305                "{} should default to 0",
1306                name
1307            );
1308        }
1309    }
1310
1311    #[test]
1312    fn test_system_variable_server_counters_default_zero() {
1313        let sys = crate::ntp_proto::SystemState::new();
1314        for name in &[
1315            "ss_badauth",
1316            "ss_badlength",
1317            "ss_declined",
1318            "ss_delayed",
1319            "ss_kodsent",
1320            "ss_limited",
1321            "ss_oldver",
1322            "ss_received",
1323            "ss_rejected",
1324            "ss_restricted",
1325            "ss_thisver",
1326        ] {
1327            assert_eq!(
1328                get_system_variable(&sys, name).unwrap(),
1329                "0",
1330                "{} should default to 0",
1331                name
1332            );
1333        }
1334    }
1335
1336    #[test]
1337    fn test_get_hostname() {
1338        let host = super::get_hostname();
1339        assert!(!host.is_empty(), "hostname should not be empty");
1340        // Should at least contain some standard localhost name
1341        // In test environments, it might be "localhost" or actual hostname
1342        assert!(host.len() <= 255, "hostname too long: {}", host.len());
1343    }
1344}