Skip to main content

ntpsec_rs_core/
control_client.rs

1// ──── control_client.rs — Mode 6 NTP control client ─────────────────────
2//
3// Reusable Mode 6 client stack for ntpq-rs, ntpmon, ntptrace, and other
4// tools.  Handles wire framing, fragmentation, retransmission, and
5// response parsing.
6//
7// Three layers:
8//   1. ControlClient — UDP send/recv with timeout, retries, fragment reassembly
9//   2. Typed query model — SystemVariables, PeerVariables, AssociationStatus
10//   3. Renderer — ntpq-compatible text output
11//
12// =============================================================================
13
14use crate::ntp_control::*;
15use crate::ntp_types::*;
16use std::collections::{BTreeMap, HashMap};
17use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
18use std::time::Duration;
19
20// ──── Errors ──────────────────────────────────────────────────────────
21
22#[derive(Debug, Clone, PartialEq)]
23pub enum QueryError {
24    Network(String),
25    Timeout,
26    BadResponse(String),
27    ProtocolError(String),
28    AuthFailure,
29    NotFound,
30    NotSupported(String),
31}
32
33impl std::fmt::Display for QueryError {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        match self {
36            Self::Network(s) => write!(f, "network: {s}"),
37            Self::Timeout => write!(f, "timeout"),
38            Self::BadResponse(s) => write!(f, "bad response: {s}"),
39            Self::ProtocolError(s) => write!(f, "protocol: {s}"),
40            Self::AuthFailure => write!(f, "authentication failure"),
41            Self::NotFound => write!(f, "not found"),
42            Self::NotSupported(s) => write!(f, "not supported: {s}"),
43        }
44    }
45}
46
47impl std::error::Error for QueryError {}
48
49// ──── Fragment Collector ──────────────────────────────────────────────
50
51/// Pure fragment reassembly engine.  Collects fragments and validates
52/// that the assembled range is contiguous with no holes or overlaps.
53#[derive(Debug, Clone)]
54pub struct FragmentCollector {
55    /// Fragments keyed by offset. BTreeMap guarantees sorted iteration.
56    fragments: BTreeMap<u16, Vec<u8>>,
57    /// The end offset of the final fragment (set when `more == false`).
58    final_end: Option<u16>,
59    /// Status word from the first fragment.
60    pub status: Option<u16>,
61    /// Association ID from the first fragment.
62    pub associd: Option<u16>,
63}
64
65#[allow(clippy::new_without_default)]
66impl FragmentCollector {
67    pub fn new() -> Self {
68        Self {
69            fragments: BTreeMap::new(),
70            final_end: None,
71            status: None,
72            associd: None,
73        }
74    }
75
76    /// Add a fragment. Returns Ok(true) if the collection is complete.
77    /// Returns Err on length mismatch, overlaps, holes, or inconsistent metadata.
78    pub fn add_fragment(
79        &mut self,
80        offset: u16,
81        count: u16,
82        data: &[u8],
83        more: bool,
84        status: u16,
85        associd: u16,
86    ) -> Result<bool, QueryError> {
87        // Validate fragment data length matches declared count exactly
88        if data.len() != count as usize {
89            return Err(QueryError::BadResponse(format!(
90                "fragment count {} != payload length {}",
91                count,
92                data.len()
93            )));
94        }
95        let payload = data.to_vec();
96
97        // Enforce metadata consistency across all fragments
98        if let Some(existing_status) = self.status {
99            if status != existing_status {
100                return Err(QueryError::BadResponse(
101                    "inconsistent status across fragments".to_string(),
102                ));
103            }
104        } else {
105            self.status = Some(status);
106        }
107        if let Some(existing_associd) = self.associd {
108            if associd != existing_associd {
109                return Err(QueryError::BadResponse(
110                    "inconsistent associd across fragments".to_string(),
111                ));
112            }
113        } else {
114            self.associd = Some(associd);
115        }
116
117        // Check for overflow in offset + count
118        let frag_end = match offset.checked_add(count) {
119            Some(e) => e,
120            None => {
121                return Err(QueryError::BadResponse(
122                    "fragment offset+count overflows u16".to_string(),
123                ))
124            }
125        };
126        for (&existing_offset, existing_data) in &self.fragments {
127            let existing_end = match existing_offset.checked_add(existing_data.len() as u16) {
128                Some(e) => e,
129                None => {
130                    return Err(QueryError::BadResponse(
131                        "existing fragment overflows u16".to_string(),
132                    ))
133                }
134            };
135            if offset < existing_end && frag_end > existing_offset {
136                let overlap_start = offset.max(existing_offset);
137                let overlap_end = frag_end.min(existing_end);
138                if overlap_end > overlap_start {
139                    let existing_slice = &existing_data[(overlap_start - existing_offset) as usize
140                        ..(overlap_end - existing_offset) as usize];
141                    let new_slice = &payload
142                        [(overlap_start - offset) as usize..(overlap_end - offset) as usize];
143                    if existing_slice != new_slice {
144                        return Err(QueryError::BadResponse(
145                            "conflicting fragment data at offset".to_string(),
146                        ));
147                    }
148                }
149            }
150        }
151
152        // If final_end is known, reject fragments that extend past it
153        if let Some(fe) = self.final_end {
154            if frag_end > fe {
155                return Err(QueryError::BadResponse(
156                    "fragment extends beyond final response extent".to_string(),
157                ));
158            }
159        }
160
161        // Prevent shrinking an existing same-offset fragment
162        if self.fragments.contains_key(&offset) {
163            let existing_len = self.fragments.get(&offset).map(|d| d.len()).unwrap_or(0);
164            if payload.len() < existing_len {
165                return Err(QueryError::BadResponse(
166                    "retrograde fragment would shrink existing data".to_string(),
167                ));
168            }
169        }
170
171        self.fragments.insert(offset, payload);
172
173        // Track the final fragment extent
174        if !more {
175            let current_end = match offset.checked_add(count) {
176                Some(e) => e,
177                None => {
178                    return Err(QueryError::BadResponse(
179                        "final fragment offset+count overflows u16".to_string(),
180                    ))
181                }
182            };
183            // When establishing final_end, validate ALL existing fragments fit within
184            match self.final_end {
185                Some(existing) => {
186                    if current_end != existing {
187                        return Err(QueryError::BadResponse(
188                            "inconsistent final fragment extent".to_string(),
189                        ));
190                    }
191                }
192                None => {
193                    // New final_end: verify no existing fragment extends past it
194                    for (&eo, ed) in &self.fragments {
195                        let ee = eo.checked_add(ed.len() as u16).ok_or_else(|| {
196                            QueryError::BadResponse("existing fragment overflows".to_string())
197                        })?;
198                        if ee > current_end {
199                            return Err(QueryError::BadResponse(
200                                "existing fragment exceeds newly declared final extent".to_string(),
201                            ));
202                        }
203                    }
204                    self.final_end = Some(current_end);
205                }
206            }
207        }
208
209        Ok(self.is_complete())
210    }
211
212    /// Returns true if the collected fragments cover exactly `0..final_end`.
213    pub fn is_complete(&self) -> bool {
214        let final_end = match self.final_end {
215            Some(e) => e,
216            None => return false,
217        };
218        if final_end == 0 {
219            return true;
220        }
221        let mut covered_end = 0u16;
222        for (&offset, data) in &self.fragments {
223            if offset > covered_end {
224                return false;
225            }
226            let frag_end = match offset.checked_add(data.len() as u16) {
227                Some(e) if e <= final_end => e,
228                // Fragment extends past final_end (rejected by add_fragment, but defence-in-depth)
229                _ => return false,
230            };
231            if frag_end > covered_end {
232                covered_end = frag_end;
233            }
234        }
235        covered_end == final_end
236    }
237
238    /// Assemble the collected fragments into a contiguous byte vector.
239    pub fn assemble(&self) -> Result<Vec<u8>, QueryError> {
240        if !self.is_complete() {
241            return Err(QueryError::BadResponse(
242                "incomplete fragment set".to_string(),
243            ));
244        }
245        let final_end = self.final_end.unwrap_or(0) as usize;
246        let mut result = vec![0u8; final_end];
247        for (&offset, data) in &self.fragments {
248            let start = offset as usize;
249            let end = (start + data.len()).min(final_end);
250            result[start..end].copy_from_slice(&data[..end - start]);
251        }
252        Ok(result)
253    }
254
255    /// Number of fragments collected.
256    pub fn fragment_count(&self) -> usize {
257        self.fragments.len()
258    }
259}
260
261// ──── Association Status (from binary READSTAT) ───────────────────────
262
263/// Parsed association record from READSTAT binary response.
264#[derive(Debug, Clone)]
265pub struct AssociationStatus {
266    pub associd: u16,
267    pub status: u16,
268    pub configured: bool,
269    pub auth_enabled: bool,
270    pub auth_ok: bool,
271    pub reachable: bool,
272    pub broadcast: bool,
273    pub selection: u8,
274}
275
276impl AssociationStatus {
277    pub fn from_bytes(data: &[u8]) -> Result<Vec<Self>, QueryError> {
278        if (data.len()) % 4 != 0 {
279            return Err(QueryError::BadResponse(format!(
280                "READSTAT data length {} not multiple of 4",
281                data.len()
282            )));
283        }
284        let mut assocs = Vec::with_capacity(data.len() / 4);
285        for chunk in data.chunks(4) {
286            let associd = u16::from_be_bytes([chunk[0], chunk[1]]);
287            let status = u16::from_be_bytes([chunk[2], chunk[3]]);
288            let high = (status >> 8) as u8;
289            assocs.push(AssociationStatus {
290                associd,
291                status,
292                configured: (high & 0x80) != 0,
293                auth_enabled: (high & 0x40) != 0,
294                auth_ok: (high & 0x20) != 0,
295                reachable: (high & 0x10) != 0,
296                broadcast: (high & 0x08) != 0,
297                selection: high & 0x07,
298            });
299        }
300        Ok(assocs)
301    }
302
303    pub fn tally_char(&self) -> char {
304        match self.selection {
305            7 => 'o', // PPS peer
306            6 => '*', // system peer
307            5 => '#', // backup
308            4 => '+', // candidate
309            3 => '-', // outlier
310            2 => 'x', // excess
311            1 => 'x', // falsetick
312            _ => ' ', // rejected
313        }
314    }
315}
316
317// ──── Mode 6 Variable Text Parser ────────────────────────────────────
318
319/// Parse Mode 6 key=value text with proper quote handling.
320/// Splits on `,` outside quotes; strips surrounding quotes from values.
321pub fn parse_mode6_vars(text: &str) -> Vec<(String, String)> {
322    let mut vars = Vec::new();
323    let mut current = String::new();
324    let mut in_quotes = false;
325    let mut escaped = false;
326
327    for ch in text.chars() {
328        if escaped {
329            current.push(ch);
330            escaped = false;
331            continue;
332        }
333        if ch == '\\' {
334            current.push(ch);
335            escaped = true;
336            continue;
337        }
338        if ch == '"' {
339            current.push(ch);
340            in_quotes = !in_quotes;
341            continue;
342        }
343        if ch == ',' && !in_quotes {
344            // End of a variable
345            if let Some(eq) = current.find('=') {
346                let key = current[..eq].trim().to_string();
347                let mut raw_val = current[eq + 1..].trim().to_string();
348                // Strip surrounding quotes
349                if raw_val.len() >= 2 && raw_val.starts_with('"') && raw_val.ends_with('"') {
350                    raw_val = raw_val[1..raw_val.len() - 1].to_string();
351                }
352                vars.push((key, raw_val));
353            }
354            current.clear();
355            continue;
356        }
357        current.push(ch);
358    }
359
360    // Last variable (no trailing comma)
361    if !current.is_empty() {
362        if let Some(eq) = current.find('=') {
363            let key = current[..eq].trim().to_string();
364            let mut raw_val = current[eq + 1..].trim().to_string();
365            if raw_val.len() >= 2 && raw_val.starts_with('"') && raw_val.ends_with('"') {
366                raw_val = raw_val[1..raw_val.len() - 1].to_string();
367            }
368            vars.push((key, raw_val));
369        }
370    }
371
372    vars
373}
374
375// ──── System Variables ────────────────────────────────────────────────
376
377/// Typed system variables parsed from Mode 6 text response.
378#[derive(Debug, Clone, Default)]
379pub struct SystemVariables {
380    pub ordered_vars: Vec<(String, String)>,
381    pub vars: HashMap<String, String>,
382    pub associd: u16,
383    pub status: u16,
384    /// Status word used for the display description.
385    ///
386    /// Real C ntpq issues a separate status-summary request (count=0)
387    /// whose response status word is used for the textual description
388    /// (leap/source/event), while the full READVAR response's status
389    /// word is shown as `status=XXXX`. When these differ, this field
390    /// holds the separate status word for description; `self.status`
391    /// is always the READVAR header status.
392    pub display_status: u16,
393}
394
395impl SystemVariables {
396    pub fn from_text(data: &str, associd: u16, status: u16) -> Self {
397        let ordered_vars = parse_mode6_vars(data);
398        let vars: HashMap<String, String> = ordered_vars.iter().cloned().collect();
399        Self {
400            ordered_vars,
401            vars,
402            associd,
403            status,
404            display_status: status,
405        }
406    }
407
408    /// Set a separate display status (from a status-summary request).
409    pub fn with_display_status(mut self, display_status: u16) -> Self {
410        self.display_status = display_status;
411        self
412    }
413
414    pub fn get(&self, key: &str) -> Option<&str> {
415        self.vars.get(key).map(|s| s.as_str())
416    }
417
418    pub fn stratum(&self) -> u8 {
419        self.get("stratum")
420            .and_then(|s| s.parse().ok())
421            .unwrap_or(16)
422    }
423
424    pub fn leap_str(&self) -> &str {
425        use crate::ntp_control::sys_status;
426        sys_status::li_name(sys_status::decode_li(self.display_status))
427    }
428
429    /// Status description matching real ntpq output format.
430    ///
431    /// Uses `display_status` (which may come from a separate status-summary
432    /// request in the C ntpq) for the textual description, while `self.status`
433    /// is always the READVAR header value shown as `status=XXXX`.
434    ///
435    /// Format matches real C ntpq: "leap_xxx, sync_xxx, N event, [flags,]"
436    pub fn status_description(&self) -> String {
437        use crate::ntp_control::sys_status;
438        let s = self.display_status;
439        let li = sys_status::decode_li(s);
440        let source = sys_status::decode_source(s);
441        let ev_cnt = sys_status::decode_event_count(s);
442        let ev_code = sys_status::decode_event_code(s);
443
444        let ev_name = system_event_name(ev_code);
445        let freq_mode = if s & 0x0080 != 0 { ", freq_mode" } else { "" };
446        format!(
447            "{}, {}, {} {}{}",
448            sys_status::li_name(li),
449            sys_status::source_name(source),
450            ev_cnt,
451            ev_name,
452            freq_mode,
453        )
454    }
455}
456
457// ──── Peer Variables ──────────────────────────────────────────────────
458
459/// Typed peer variables parsed from Mode 6 text response.
460#[derive(Debug, Clone, Default)]
461pub struct PeerVariables {
462    pub ordered_vars: Vec<(String, String)>,
463    pub vars: HashMap<String, String>,
464    pub associd: u16,
465    pub status: u16,
466}
467
468impl PeerVariables {
469    pub fn from_text(data: &str, associd: u16, status: u16) -> Self {
470        let ordered_vars = parse_mode6_vars(data);
471        let vars: HashMap<String, String> = ordered_vars.iter().cloned().collect();
472        Self {
473            ordered_vars,
474            vars,
475            associd,
476            status,
477        }
478    }
479
480    pub fn get(&self, key: &str) -> Option<&str> {
481        self.vars.get(key).map(|s| s.as_str())
482    }
483
484    pub fn stratum(&self) -> u8 {
485        self.get("stratum")
486            .and_then(|s| s.parse().ok())
487            .unwrap_or(16)
488    }
489}
490
491// ──── Control Client ──────────────────────────────────────────────────
492
493/// Mode 6 control protocol client with connected UDP, DNS resolution,
494/// fragment reassembly, and response validation.
495pub struct ControlClient {
496    sequence: u16,
497    timeout: Duration,
498    retries: u8,
499}
500
501impl ControlClient {
502    pub fn new(timeout_secs: u32, retries: u8) -> Self {
503        Self {
504            sequence: 1,
505            timeout: Duration::from_secs(timeout_secs as u64),
506            retries,
507        }
508    }
509
510    fn next_sequence(&mut self) -> u16 {
511        // RFC 9327: distinct nonzero sequence numbers
512        let seq = self.sequence;
513        self.sequence = self.sequence.wrapping_add(1);
514        // Skip zero if wrap occurs
515        if self.sequence == 0 {
516            self.sequence = 1;
517        }
518        seq
519    }
520
521    /// Resolve hostname to a SocketAddr, trying IPv4 first, then IPv6.
522    fn resolve(host: &str, port: u16) -> Result<SocketAddr, QueryError> {
523        // First try parsing as a numeric IP
524        if let Ok(addr) = format!("{host}:{port}").parse::<SocketAddr>() {
525            return Ok(addr);
526        }
527
528        // Try DNS resolution
529        let addrs: Vec<SocketAddr> = (host, port)
530            .to_socket_addrs()
531            .map_err(|e| QueryError::Network(format!("DNS resolution failed for '{host}': {e}")))?
532            .collect();
533
534        // Prefer IPv4, fall back to IPv6
535        for addr in &addrs {
536            if addr.is_ipv4() {
537                return Ok(*addr);
538            }
539        }
540        addrs
541            .into_iter()
542            .next()
543            .ok_or_else(|| QueryError::Network(format!("no addresses found for '{host}'")))
544    }
545
546    /// Send a Mode 6 request using connected UDP and collect fragments.
547    pub fn query(
548        &mut self,
549        host: &str,
550        port: u16,
551        msg: ControlMessage,
552    ) -> Result<(Vec<u8>, u16, u16), QueryError> {
553        let addr = Self::resolve(host, port)?;
554
555        // Create and connect a UDP socket matching the address family
556        let local = if addr.is_ipv4() {
557            "0.0.0.0:0"
558        } else {
559            "[::]:0"
560        };
561        let socket =
562            UdpSocket::bind(local).map_err(|e| QueryError::Network(format!("bind: {e}")))?;
563        socket
564            .set_read_timeout(Some(self.timeout))
565            .map_err(|e| QueryError::Network(format!("set timeout: {e}")))?;
566        socket
567            .connect(addr)
568            .map_err(|e| QueryError::Network(format!("connect: {e}")))?;
569
570        let seq = self.next_sequence();
571        let req = ControlMessage {
572            li_vn_mode: NtpPacket::set_li_vn_mode(
573                LeapIndicator::NoWarning,
574                NtpVersion::V4,
575                NtpMode::NtpControl,
576            ),
577            opcode: msg.opcode,
578            sequence: seq,
579            status: 0,
580            associd: msg.associd,
581            offset: 0,
582            count: 0,
583        };
584
585        let request_bytes = req.encode();
586        let expected_op = ControlOpcode::from_u8(msg.opcode).op;
587
588        for attempt in 0..=self.retries {
589            if attempt > 0 {
590                std::thread::sleep(Duration::from_millis(500));
591            }
592
593            socket
594                .send(&request_bytes)
595                .map_err(|e| QueryError::Network(format!("send: {e}")))?;
596
597            // Collect fragments using the pure collector
598            let mut collector = FragmentCollector::new();
599
600            loop {
601                let mut buf = vec![0u8; 512];
602                match socket.recv(&mut buf) {
603                    Ok(n) => {
604                        let raw = &buf[..n];
605                        let (resp, after_header) = ControlMessage::decode(raw)
606                            .ok_or_else(|| QueryError::BadResponse("short header".to_string()))?;
607
608                        // === Response validation ===
609                        // 1. Sequence must match
610                        if resp.sequence != seq {
611                            continue;
612                        }
613                        let oc = resp.decode_opcode();
614                        // 2. Must be a response
615                        if !oc.response {
616                            continue;
617                        }
618                        // 3. Source validated by connected socket
619                        // 4. Opcode must match request
620                        if oc.op != expected_op {
621                            continue;
622                        }
623                        // 5. Association ID must match (can be 0 for system)
624                        if resp.associd != msg.associd {
625                            continue;
626                        }
627                        // 6. Mode must be Mode 6 (NtpControl)
628                        if resp.mode() != NtpMode::NtpControl {
629                            continue;
630                        }
631
632                        // Handle error responses (RFC 9327 §5.6)
633                        // 1=Auth, 2=Format, 3=Opcode, 4=NotFound, 5=NotKnown, 6=BadValue, 7=Admin
634                        if oc.error {
635                            let err_code = (resp.status >> 8) as u8;
636                            return match err_code {
637                                1 => Err(QueryError::AuthFailure),
638                                2 => Err(QueryError::ProtocolError(
639                                    "invalid message format".to_string(),
640                                )),
641                                3 => Err(QueryError::NotSupported("invalid opcode".to_string())),
642                                4 => Err(QueryError::NotFound),
643                                5 => Err(QueryError::NotSupported("unknown variable".to_string())),
644                                6 => Err(QueryError::ProtocolError(
645                                    "invalid variable value".to_string(),
646                                )),
647                                7 => Err(QueryError::ProtocolError(
648                                    "administratively prohibited".to_string(),
649                                )),
650                                _ => Err(QueryError::ProtocolError(format!("error {err_code}"))),
651                            };
652                        }
653
654                        // Add fragment to collector (uses offset/count from the header,
655                        // but the bytes start at 0 in after_header since each fragment
656                        // is self-contained)
657                        let count = resp.count as usize;
658                        let data = if count <= after_header.len() {
659                            after_header[..count].to_vec()
660                        } else {
661                            return Err(QueryError::BadResponse(
662                                "fragment count exceeds datagram".to_string(),
663                            ));
664                        };
665
666                        let complete = collector.add_fragment(
667                            resp.offset,
668                            resp.count,
669                            &data,
670                            oc.more,
671                            resp.status,
672                            resp.associd,
673                        )?;
674
675                        if complete {
676                            let assembled = collector.assemble()?;
677                            return Ok((
678                                assembled,
679                                collector.status.unwrap_or(0),
680                                collector.associd.unwrap_or(0),
681                            ));
682                        }
683                    }
684                    Err(e) => {
685                        if e.kind() == std::io::ErrorKind::WouldBlock
686                            || e.kind() == std::io::ErrorKind::TimedOut
687                        {
688                            if attempt < self.retries && collector.fragment_count() == 0 {
689                                break; // Retry from scratch
690                            }
691                            if collector.fragment_count() > 0 {
692                                // Partial collection with timeout = incomplete
693                                return Err(QueryError::BadResponse(
694                                    "incomplete fragment collection".to_string(),
695                                ));
696                            }
697                            return Err(QueryError::Timeout);
698                        }
699                        return Err(QueryError::Network(e.to_string()));
700                    }
701                }
702            }
703        }
704
705        Err(QueryError::Timeout)
706    }
707
708    /// Send a Mode 6 request with a body payload and collect fragments.
709    fn query_with_body(
710        &mut self,
711        host: &str,
712        port: u16,
713        msg: ControlMessage,
714        body: &str,
715    ) -> Result<(Vec<u8>, u16, u16), QueryError> {
716        let addr = Self::resolve(host, port)?;
717
718        let local = if addr.is_ipv4() {
719            "0.0.0.0:0"
720        } else {
721            "[::]:0"
722        };
723        let socket =
724            UdpSocket::bind(local).map_err(|e| QueryError::Network(format!("bind: {e}")))?;
725        socket
726            .set_read_timeout(Some(self.timeout))
727            .map_err(|e| QueryError::Network(format!("set timeout: {e}")))?;
728        socket
729            .connect(addr)
730            .map_err(|e| QueryError::Network(format!("connect: {e}")))?;
731
732        let seq = self.next_sequence();
733        let req = ControlMessage {
734            li_vn_mode: NtpPacket::set_li_vn_mode(
735                LeapIndicator::NoWarning,
736                NtpVersion::V4,
737                NtpMode::NtpControl,
738            ),
739            opcode: msg.opcode,
740            sequence: seq,
741            status: 0,
742            associd: msg.associd,
743            offset: 0,
744            count: body.len() as u16,
745        };
746
747        let mut request_bytes = req.encode().to_vec();
748        request_bytes.extend_from_slice(body.as_bytes());
749        let _expected_op = ControlOpcode::from_u8(msg.opcode).op;
750
751        for attempt in 0..=self.retries {
752            if attempt > 0 {
753                std::thread::sleep(Duration::from_millis(500));
754            }
755
756            socket
757                .send(&request_bytes)
758                .map_err(|e| QueryError::Network(format!("send: {e}")))?;
759
760            let mut collector = FragmentCollector::new();
761
762            loop {
763                let mut buf = vec![0u8; 512];
764                match socket.recv(&mut buf) {
765                    Ok(n) => {
766                        let raw = &buf[..n];
767                        let (resp, after_header) = ControlMessage::decode(raw)
768                            .ok_or_else(|| QueryError::BadResponse("short header".to_string()))?;
769
770                        if resp.sequence != seq {
771                            continue;
772                        }
773                        let oc = resp.decode_opcode();
774                        if oc.error {
775                            let err_code = (resp.status >> 8) as u8;
776                            return match err_code {
777                                1 => Err(QueryError::AuthFailure),
778                                2 => Err(QueryError::ProtocolError(
779                                    "invalid message format".to_string(),
780                                )),
781                                3 => Err(QueryError::NotSupported("invalid opcode".to_string())),
782                                4 => Err(QueryError::NotFound),
783                                5 => Err(QueryError::NotSupported("unknown variable".to_string())),
784                                6 => Err(QueryError::ProtocolError(
785                                    "invalid variable value".to_string(),
786                                )),
787                                7 => Err(QueryError::ProtocolError(
788                                    "administratively prohibited".to_string(),
789                                )),
790                                _ => Err(QueryError::ProtocolError(format!("error {err_code}"))),
791                            };
792                        }
793
794                        let count = resp.count as usize;
795                        let data = if count <= after_header.len() {
796                            after_header[..count].to_vec()
797                        } else {
798                            return Err(QueryError::BadResponse(
799                                "fragment count exceeds datagram".to_string(),
800                            ));
801                        };
802
803                        let complete = collector.add_fragment(
804                            resp.offset,
805                            resp.count,
806                            &data,
807                            oc.more,
808                            resp.status,
809                            resp.associd,
810                        )?;
811
812                        if complete {
813                            let assembled = collector.assemble()?;
814                            return Ok((assembled, resp.status, resp.associd));
815                        }
816                    }
817                    Err(ref e)
818                        if e.kind() == std::io::ErrorKind::WouldBlock
819                            || e.kind() == std::io::ErrorKind::TimedOut =>
820                    {
821                        break;
822                    }
823                    Err(e) => {
824                        return Err(QueryError::Network(e.to_string()));
825                    }
826                }
827            }
828        }
829
830        Err(QueryError::Timeout)
831    }
832
833    /// Parse a nonce value from a textual NTP Mode 6 response.
834    /// Expects: nonce=XXXXXXXX
835    fn parse_nonce_value(text: &str) -> Option<String> {
836        let text = text.trim();
837        if let Some(eq_pos) = text.find('=') {
838            let value = text[eq_pos + 1..].trim();
839            if !value.is_empty() {
840                return Some(value.to_string());
841            }
842        }
843        None
844    }
845
846    /// Read system variables (ntpq -c rv).
847    ///
848    /// Real C ntpq issues a separate status-summary request (READVAR
849    /// associd=0, count=0) whose response status word is used for the
850    /// textual description, followed by a second READVAR request to
851    /// retrieve the actual variables. This two-request sequence is
852    /// necessary because the status word can change between requests.
853    pub fn read_system_vars(
854        &mut self,
855        host: &str,
856        port: u16,
857    ) -> Result<SystemVariables, QueryError> {
858        // Request 1: status-summary (count=0) to get the display status word
859        let status_msg = ControlMessage {
860            li_vn_mode: 0,
861            opcode: ControlOpcode::new(false, false, false, opcodes::OP_READVAR).to_u8(),
862            sequence: 0,
863            status: 0,
864            associd: 0,
865            offset: 0,
866            count: 0,
867        };
868        let display_status = match self.query(host, port, status_msg) {
869            Ok((_, status, _)) => status,
870            Err(_) => 0, // Fall back to 0 if status request fails
871        };
872
873        // Request 2: full READVAR to get the variables
874        let var_msg = ControlMessage {
875            li_vn_mode: 0,
876            opcode: ControlOpcode::new(false, false, false, opcodes::OP_READVAR).to_u8(),
877            sequence: 0,
878            status: 0,
879            associd: 0,
880            offset: 0,
881            count: 0,
882        };
883        let (data, status, associd) = self.query(host, port, var_msg)?;
884        let text = String::from_utf8_lossy(&data).to_string();
885        Ok(SystemVariables::from_text(&text, associd, status).with_display_status(display_status))
886    }
887
888    /// Read peer variables for a specific association.
889    pub fn read_peer_vars(
890        &mut self,
891        host: &str,
892        port: u16,
893        associd: u16,
894    ) -> Result<PeerVariables, QueryError> {
895        let msg = ControlMessage {
896            li_vn_mode: 0,
897            opcode: ControlOpcode::new(false, false, false, opcodes::OP_READVAR).to_u8(),
898            sequence: 0,
899            status: 0,
900            associd,
901            offset: 0,
902            count: 0,
903        };
904        let (data, status, _) = self.query(host, port, msg)?;
905        let text = String::from_utf8_lossy(&data).to_string();
906        Ok(PeerVariables::from_text(&text, associd, status))
907    }
908
909    /// Read associations (ntpq -c as).
910    pub fn read_associations(
911        &mut self,
912        host: &str,
913        port: u16,
914    ) -> Result<Vec<AssociationStatus>, QueryError> {
915        let msg = ControlMessage {
916            li_vn_mode: 0,
917            opcode: ControlOpcode::new(false, false, false, opcodes::OP_READSTAT).to_u8(),
918            sequence: 0,
919            status: 0,
920            associd: 0,
921            offset: 0,
922            count: 0,
923        };
924        let (data, _status, _associd) = self.query(host, port, msg)?;
925        AssociationStatus::from_bytes(&data)
926    }
927
928    /// Read the MRU (Most Recently Used) list from the daemon.
929    ///
930    /// Uses the NTPsec-compatible nonce protocol:
931    ///   1. REQ_NONCE (opcode 12) to acquire a nonce
932    ///   2. READ_MRU (opcode 10) with the nonce to retrieve entries
933    ///
934    /// The response uses textual Mode 6 variable lists with indexed
935    /// entries (addr.N, last.N, first.N, ct.N).
936    pub fn read_mru_list(&mut self, host: &str, port: u16) -> Result<Vec<MruEntry>, QueryError> {
937        // ── 1. Acquire nonce via REQ_NONCE (opcode 12) ────────────────
938        let nonce_msg = ControlMessage {
939            li_vn_mode: 0,
940            opcode: ControlOpcode::new(false, false, false, opcodes::OP_REQ_NONCE).to_u8(),
941            sequence: 0,
942            status: 0,
943            associd: 0,
944            offset: 0,
945            count: 0,
946        };
947        let (nonce_data, _status, _associd) = self.query(host, port, nonce_msg)?;
948        let nonce_text = String::from_utf8_lossy(&nonce_data);
949        let nonce = Self::parse_nonce_value(&nonce_text).ok_or_else(|| {
950            QueryError::BadResponse("MRU nonce response did not contain nonce=".to_string())
951        })?;
952
953        // ── 2. Request MRU list with nonce ────────────────────────────
954        // The request body contains the nonce as a text variable.
955        let request_body = format!("nonce={nonce}");
956        let msg = ControlMessage {
957            li_vn_mode: 0,
958            opcode: ControlOpcode::new(false, false, false, opcodes::OP_READ_MRU).to_u8(),
959            sequence: 0,
960            status: 0,
961            associd: 0,
962            offset: 0,
963            count: request_body.len() as u16,
964        };
965        let (data, _status, _associd) = self.query_with_body(host, port, msg, &request_body)?;
966        let response_text = String::from_utf8_lossy(&data);
967
968        // ── 3. Parse textual indexed entries ──────────────────────────
969        MruEntry::parse_textual(&response_text)
970    }
971}
972
973// ──── MRU Entry Model ────────────────────────────────────────────────────
974
975/// MRU (Most Recently Used) entry from the daemon.
976/// Represents a single client entry in the daemon's MRU list.
977#[derive(Debug, Clone)]
978pub struct MruEntry {
979    pub addr: String,
980    pub port: u16,
981    pub last_pkt_secs: i64,
982    pub last_pkt_frac: u32,
983    pub first_pkt_secs: i64,
984    pub first_pkt_frac: u32,
985    pub count: u32,
986    pub flags: u8,
987}
988
989impl MruEntry {
990    /// Parse MRU entries from a textual Mode 6 READ_MRU response.
991    ///
992    /// NTPsec returns indexed entries in text format:
993    ///   addr.0=192.168.1.1 last.0=3771763200.000000 first.0=3771763100.000000 ct.0=42 mv.0=2 rs.0=0
994    ///   addr.1=10.0.0.1 last.1=3771763300.000000 first.1=3771763200.000000 ct.1=100
995    ///
996    /// Indexed variables are grouped by their numeric index into entries.
997    pub fn parse_textual(text: &str) -> Result<Vec<MruEntry>, QueryError> {
998        // Split into variables and group by index
999        let mut entries_map: std::collections::BTreeMap<u32, MruEntry> =
1000            std::collections::BTreeMap::new();
1001
1002        for token in text.split(',') {
1003            let token = token.trim();
1004            if token.is_empty() {
1005                continue;
1006            }
1007            // Split on '=' to get key=value
1008            let parts: Vec<&str> = token.splitn(2, '=').collect();
1009            if parts.len() != 2 {
1010                continue;
1011            }
1012            let key = parts[0].trim();
1013            let value = parts[1].trim();
1014
1015            // Parse indexed keys like "addr.0", "last.1", "ct.2"
1016            let dot_pos = key.rfind('.');
1017            if let Some(dot) = dot_pos {
1018                let base = &key[..dot];
1019                let index: u32 = match key[dot + 1..].parse() {
1020                    Ok(i) => i,
1021                    Err(_) => continue,
1022                };
1023
1024                let entry = entries_map.entry(index).or_insert_with(|| MruEntry {
1025                    addr: String::new(),
1026                    port: 0,
1027                    last_pkt_secs: 0,
1028                    last_pkt_frac: 0,
1029                    first_pkt_secs: 0,
1030                    first_pkt_frac: 0,
1031                    count: 0,
1032                    flags: 0,
1033                });
1034
1035                match base {
1036                    "addr" => entry.addr = value.to_string(),
1037                    "last" => {
1038                        // Format: seconds.fraction
1039                        if let Some(dot) = value.find('.') {
1040                            if let Ok(secs) = value[..dot].parse::<i64>() {
1041                                entry.last_pkt_secs = secs;
1042                            }
1043                            if value.len() > dot + 1 {
1044                                let frac_str = &value[dot + 1..];
1045                                // Pad or truncate to 6 fractional digits for NTP frac
1046                                let frac_padded = format!("{:<6}", frac_str);
1047                                if let Ok(frac) = frac_padded[..6].parse::<u32>() {
1048                                    entry.last_pkt_frac = frac * 4295; // approx: 10^6 / 2^32 * frac
1049                                }
1050                            }
1051                        } else if let Ok(secs) = value.parse::<i64>() {
1052                            entry.last_pkt_secs = secs;
1053                        }
1054                    }
1055                    "first" => {
1056                        if let Some(dot) = value.find('.') {
1057                            if let Ok(secs) = value[..dot].parse::<i64>() {
1058                                entry.first_pkt_secs = secs;
1059                            }
1060                        } else if let Ok(secs) = value.parse::<i64>() {
1061                            entry.first_pkt_secs = secs;
1062                        }
1063                    }
1064                    "ct" => {
1065                        if let Ok(count) = value.parse::<u32>() {
1066                            entry.count = count;
1067                        }
1068                    }
1069                    "mv" | "rs" => {
1070                        if let Ok(flags) = value.parse::<u8>() {
1071                            entry.flags = flags;
1072                        }
1073                    }
1074                    _ => {}
1075                }
1076            } else {
1077                // Non-indexed keys (like nonce=...)
1078                if key == "nonce" {
1079                    // skip nonce in response
1080                }
1081            }
1082        }
1083
1084        // Filter out empty entries and collect
1085        let entries: Vec<MruEntry> = entries_map
1086            .into_values()
1087            .filter(|e| !e.addr.is_empty() || e.count > 0)
1088            .collect();
1089
1090        Ok(entries)
1091    }
1092
1093    /// Format a single MRU entry as a line of text.
1094    pub fn format_entry(&self) -> String {
1095        let last_f = self.last_pkt_secs as f64 + (self.last_pkt_frac as f64 / 4294967296.0);
1096        let first_f = self.first_pkt_secs as f64 + (self.first_pkt_frac as f64 / 4294967296.0);
1097        let interval = if self.count > 1 {
1098            (last_f - first_f) / (self.count.saturating_sub(1) as f64)
1099        } else {
1100            0.0
1101        };
1102        let typ = if self.flags & 0x01 != 0 {
1103            "cast"
1104        } else {
1105            "clnt"
1106        };
1107        format!(
1108            "{:>21} {:>5} {:>8.0}s {:>8} {:>4}",
1109            self.addr, self.port, interval, self.count, typ
1110        )
1111    }
1112
1113    /// Format the column header for MRU list output.
1114    pub fn format_header() -> String {
1115        format!(
1116            "{:>21} {:>5} {:>8} {:>8} {:>4}",
1117            "addr", "port", "avg_int", "count", "type"
1118        )
1119    }
1120
1121    /// Format a full MRU list as a table.
1122    pub fn format_list(entries: &[MruEntry]) -> String {
1123        if entries.is_empty() {
1124            return "(empty MRU list)".to_string();
1125        }
1126        let mut output = String::new();
1127        output.push_str(&Self::format_header());
1128        output.push('\n');
1129        output.push_str(&"-".repeat(50));
1130        output.push('\n');
1131        for entry in entries {
1132            output.push_str(&entry.format_entry());
1133            output.push('\n');
1134        }
1135        output
1136    }
1137}
1138
1139// ──── Peer Row Model ──────────────────────────────────────────────────
1140
1141/// A single peer row for the peers billboard.
1142#[derive(Debug, Clone)]
1143pub struct PeerRow {
1144    pub tally: char,
1145    pub remote: String,
1146    pub refid: String,
1147    pub associd: u16,
1148    pub stratum: u8,
1149    pub peer_type: char,
1150    pub when: Option<u64>,
1151    pub poll: u64,
1152    pub reach: u8,
1153    pub delay: f64,
1154    pub offset: f64,
1155    pub jitter: f64,
1156}
1157
1158/// Refclock driver name for 127.127.x.y addresses.
1159/// Maps driver type x to the display name used by ntpq.
1160fn refclock_driver_name(driver_type: u8) -> &'static str {
1161    match driver_type {
1162        1 => "LOCAL",
1163        2 => "WWVB",
1164        3 => "WWV",
1165        4 => "WWVH",
1166        5 => "GOES",
1167        6 => "GPS_ONCORE",
1168        7 => "ACTS",
1169        8 => "IRIG",
1170        9 => "ARCR",
1171        10 => "CHU",
1172        11 => "PARSE",
1173        12 => "PPS",
1174        13 => "TRAK",
1175        14 => "HOPF",
1176        15 => "MSF",
1177        16 => "GPSD",
1178        17 => "GENERIC",
1179        18 => "SHM",
1180        19 => "NMEA",
1181        20 => "PALISADE",
1182        21 => "ONCORE",
1183        22 => "ATOM",
1184        23 => "PTB",
1185        24 => "ULINK",
1186        25 => "DATUM",
1187        26 => "HARDWARE",
1188        27 => "NEOCLK4",
1189        28 => "GPS_HS",
1190        29 => "PROFANCT",
1191        30 => "GPS_AS2201",
1192        31 => "GPS",
1193        32 => "ARBITER",
1194        33 => "GPS_ME",
1195        34 => "GPS_WWV",
1196        35 => "PERFE",
1197        _ => "REFCLOCK",
1198    }
1199}
1200
1201/// Format a refclock address (127.127.x.y) into ntpq display name.
1202/// Returns None if the address is not a refclock address.
1203fn format_refclock_remote(srcaddr: &str) -> Option<String> {
1204    // Parse 127.127.x.y format
1205    let parts: Vec<&str> = srcaddr.split('.').collect();
1206    if parts.len() != 4 {
1207        return None;
1208    }
1209    if parts[0] != "127" || parts[1] != "127" {
1210        return None;
1211    }
1212    let driver_type: u8 = parts[2].parse().ok()?;
1213    let unit: u8 = parts[3].parse().ok()?;
1214    let name = refclock_driver_name(driver_type);
1215    Some(format!("{name}({unit})"))
1216}
1217
1218/// Wrap an ASCII refid in dots if it looks like a printable string
1219/// (matching real ntpq's convention of `.LOCL.` for ASCII refids).
1220fn format_refid(refid: &str) -> String {
1221    let trimmed = refid.trim_end_matches('\0');
1222    if trimmed.is_empty() {
1223        return String::new();
1224    }
1225    if trimmed.len() <= 4 && trimmed.chars().all(|c| c.is_ascii_graphic() || c == ' ') {
1226        format!(".{trimmed}.")
1227    } else {
1228        trimmed.to_string()
1229    }
1230}
1231
1232impl PeerRow {
1233    pub fn from_association(pv: &PeerVariables, assoc: &AssociationStatus) -> Self {
1234        let tally = assoc.tally_char();
1235        // Detect refclocks: stratum >= 10 and known refclock refid or address
1236        let pv_stratum = pv.stratum();
1237        let pv_refid = pv.get("refid").unwrap_or("");
1238        let srcaddr = pv.get("srcaddr").unwrap_or("");
1239        let is_refclock = pv_stratum >= 10
1240            && (pv_refid == "LOCL"
1241                || pv_refid.starts_with("127.127.")
1242                || srcaddr.starts_with("127.127."));
1243
1244        // For refclocks, format the remote as DRIVERNAME(unit);
1245        // otherwise use srcaddr or fall back to refid.
1246        let remote = if is_refclock {
1247            // Try parsing srcaddr as 127.127.x.y first
1248            if let Some(formatted) = format_refclock_remote(srcaddr) {
1249                formatted
1250            } else if pv_refid == "LOCL" {
1251                // Local clock: type 1, unit 0
1252                "LOCAL(0)".to_string()
1253            } else if pv_refid == "PPS" {
1254                "PPS(0)".to_string()
1255            } else if !srcaddr.is_empty() {
1256                srcaddr.to_string()
1257            } else {
1258                // Fall back to refid wrapped in dots (matching real ntpq)
1259                format_refid(pv_refid)
1260            }
1261        } else if !srcaddr.is_empty() {
1262            srcaddr.to_string()
1263        } else {
1264            format_refid(pv_refid)
1265        };
1266        let refid = format_refid(pv.get("refid").unwrap_or(""));
1267        let stratum = pv.stratum();
1268        let delay = pv.get("delay").and_then(|s| s.parse().ok()).unwrap_or(0.0);
1269        let offset = pv.get("offset").and_then(|s| s.parse().ok()).unwrap_or(0.0);
1270        let jitter = pv.get("jitter").and_then(|s| s.parse().ok()).unwrap_or(0.0);
1271        let poll = pv
1272            .get("hpoll")
1273            .and_then(|s| s.parse::<f64>().ok())
1274            .map(|p| 1u64 << p as u64)
1275            .unwrap_or(64);
1276
1277        // Derive reach from peer READVAR if available, else from association status
1278        let reach = pv
1279            .get("reach")
1280            .and_then(|s| u8::from_str_radix(s, 16).ok())
1281            .unwrap_or(if assoc.reachable { 1 } else { 0 });
1282
1283        // Derive `when` from the `recv` variable (seconds since last packet).
1284        // Fall back to `rec` if `recv` is absent.
1285        let when = pv
1286            .get("recv")
1287            .and_then(|s| s.parse::<u64>().ok())
1288            .or_else(|| pv.get("rec").and_then(|s| s.parse::<u64>().ok()));
1289        // For refclocks that don't report recv, derive from reachable state
1290        let when = when.or(if assoc.reachable { Some(0) } else { None });
1291
1292        // Determine peer type from hmode variable, matching ntpq conventions:
1293        //   0=unspec(local), 1=sym_active(s), 2=sym_passive(S),
1294        //   3=client(u), 4=server(u), 5=broadcast(b), 6=control(u)
1295        let peer_type = if assoc.broadcast {
1296            'b'
1297        } else if is_refclock {
1298            // Real C ntpq uses 'u' (unicast) for refclock peers
1299            'u'
1300        } else {
1301            match pv.get("hmode").and_then(|s| s.parse::<u8>().ok()) {
1302                Some(0) => 'l',
1303                Some(1) => 's',
1304                Some(2) => 'S',
1305                Some(5) => 'b',
1306                _ => 'u',
1307            }
1308        };
1309
1310        Self {
1311            tally,
1312            remote,
1313            refid,
1314            associd: assoc.associd,
1315            stratum,
1316            peer_type,
1317            when,
1318            poll,
1319            reach,
1320            delay,
1321            offset,
1322            jitter,
1323        }
1324    }
1325}
1326
1327// ──── Renderers ───────────────────────────────────────────────────────
1328
1329/// Strip 0x prefix from a value if present (matching C ntpq output).
1330fn strip_0x(val: &str) -> &str {
1331    val.strip_prefix("0x").unwrap_or(val)
1332}
1333
1334/// Format a value for ntpq output, matching C ntpq conventions (no quoting).
1335fn format_var_value(key: &str, val: &str) -> String {
1336    // Strip 0x prefix from hex timestamps
1337    let v = strip_0x(val);
1338    // Format leap as two-bit pattern matching C ntpq: ("00", "01", "10", "11")
1339    if key == "leap" {
1340        let leap_val: u8 = v.parse().unwrap_or(0);
1341        let leap_patterns = ["00", "01", "10", "11"];
1342        let idx = (leap_val.min(3)) as usize;
1343        return format!("{}={}", key, leap_patterns[idx]);
1344    }
1345    // Real C ntpq output: no quoting — values are printed as-is.
1346    // This matches ntpq C behavior where only specific values like
1347    // hostnames and some string refids are quoted, but the common
1348    // output format for peer variables is unquoted.
1349    format!("{}={}", key, v)
1350}
1351
1352/// Render system variables in ntpq-compatible format (matching real C ntpq).
1353///
1354/// Real C ntpq outputs variables in the order received from the daemon
1355/// (no preferred ordering), wrapped at ~60 chars per line, with trailing
1356/// comma and newline after each line.
1357pub fn format_readvar(sys: &SystemVariables) -> String {
1358    let mut out = String::new();
1359    out.push_str(&format!(
1360        "associd={} status={:04x} {},\n",
1361        sys.associd,
1362        sys.status,
1363        sys.status_description(),
1364    ));
1365    // Real C ntpq outputs variables in daemon wire order, wrapped at ~60
1366    // characters per line with trailing comma and newline.
1367    let mut line = String::new();
1368    for (key, val) in &sys.ordered_vars {
1369        let kv = format_var_value(key, val);
1370        if line.len() + kv.len() + 2 > 60 && !line.is_empty() {
1371            out.push_str(line.trim_end());
1372            out.push_str(",\n");
1373            line = String::new();
1374        }
1375        if !line.is_empty() {
1376            line.push_str(", ");
1377        }
1378        line.push_str(&kv);
1379    }
1380    if !line.is_empty() {
1381        out.push_str(line.trim_end());
1382        out.push_str(",\n");
1383    }
1384    out
1385}
1386
1387/// Render peer READVAR variables in ntpq-compatible format (multi-line, matching real C ntpq).
1388pub fn format_peer_readvar(peer: &PeerVariables) -> String {
1389    let mut out = String::new();
1390    let peer_ev_code = sys_status::decode_event_code(peer.status);
1391    let peer_ev_name = peer_event_name(peer_ev_code);
1392    let peer_ev_count = sys_status::decode_event_count(peer.status);
1393    out.push_str(&format!(
1394        "associd={} status={:04x} {} {}, {},\n",
1395        peer.associd,
1396        peer.status,
1397        peer_ev_count,
1398        peer_ev_name,
1399        peer.get("srcaddr").unwrap_or("unknown"),
1400    ));
1401    let preferred = [
1402        "srcaddr",
1403        "stratum",
1404        "offset",
1405        "delay",
1406        "dispersion",
1407        "jitter",
1408        "hpoll",
1409        "ppoll",
1410        "reach",
1411        "flash",
1412        "leap",
1413        "refid",
1414        "reftime",
1415        "hmode",
1416        "pmode",
1417        "precision",
1418    ];
1419    let mut rendered = std::collections::HashSet::new();
1420    for key in &preferred {
1421        if let Some(val) = peer.get(key) {
1422            out.push_str(&format_var_value(key, val));
1423            out.push('\n');
1424            rendered.insert(key.to_string());
1425        }
1426    }
1427    for (key, val) in &peer.ordered_vars {
1428        if !rendered.contains(key) {
1429            out.push_str(&format_var_value(key, val));
1430            out.push('\n');
1431            rendered.insert(key.clone());
1432        }
1433    }
1434    out
1435}
1436
1437/// Render associations table in ntpq-compatible format.
1438pub fn format_associations(assocs: &[AssociationStatus]) -> String {
1439    use crate::ntp_control::sys_status;
1440    let mut out = String::new();
1441    out.push_str("ind assid status  conf reach auth condition  last_event cnt\n");
1442    out.push_str("===========================================================\n");
1443    for (i, assoc) in assocs.iter().enumerate() {
1444        let conf = if assoc.configured { "yes" } else { "no" };
1445        let reach = if assoc.reachable { "yes" } else { "no" };
1446        let auth = if assoc.auth_ok {
1447            "ok"
1448        } else if assoc.auth_enabled {
1449            "yes"
1450        } else {
1451            "none"
1452        };
1453        let cond = match assoc.selection {
1454            6 => "sys.peer",
1455            5 => "backup",
1456            4 => "candidate",
1457            3 => "outlyer",
1458            2 => "excess",
1459            1 => "falsetick",
1460            _ => "rejected",
1461        };
1462        // Decode event code and count from the status word
1463        let event_code = sys_status::decode_event_code(assoc.status);
1464        let event_count = sys_status::decode_event_count(assoc.status);
1465        let last_event = ntpq_event_name(event_code);
1466        out.push_str(&format!(
1467            "  {} {:5}  {:04x}   {:<3}  {:<3}  {:<4}  {:<10}  {:>8} {:>2}\n",
1468            i + 1,
1469            assoc.associd,
1470            assoc.status,
1471            conf,
1472            reach,
1473            auth,
1474            cond,
1475            last_event,
1476            event_count,
1477        ));
1478    }
1479    out
1480}
1481
1482/// Map a system event code (0-15) to its ntpq display name.
1483///
1484/// NTPsec C ntpq uses a different event name table for system status
1485/// vs. peer status.  System events (from sys_event[] in ntp_control.c):
1486///   0=unspec, 1=no_reply, 2=no_reach, 3=fault, 4=freq_mode
1487///
1488/// Without this separate function, system event code 4 (freq_mode)
1489/// would incorrectly display as "reach_brd" (peer event code 4).
1490fn system_event_name(code: u16) -> &'static str {
1491    match code {
1492        0 => "unspec",
1493        1 => "no_reply",
1494        2 => "no_reach",
1495        3 => "fault",
1496        4 => "freq_mode",
1497        5 => "xleave",
1498        6 => "xtime",
1499        _ => "event",
1500    }
1501}
1502
1503/// Map a peer event code (0-15) to its ntpq display name.
1504fn ntpq_event_name(code: u16) -> &'static str {
1505    match code {
1506        0 => "restart",
1507        1 => "no_reach",
1508        2 => "no_reply",
1509        3 => "rate_excd",
1510        4 => "reach_brd",
1511        5 => "sys_rest",
1512        6 => "sys_clk",
1513        7 => "sys_peer",
1514        8 => "sys_peer",
1515        9 => "sys_peer",
1516        10 => "sys_peer",
1517        11 => "sys_peer",
1518        12 => "prot_test",
1519        13 => "crypto",
1520        14 => "nopeer",
1521        _ => "unknown",
1522    }
1523}
1524
1525/// Map a peer status event code (lower 4 bits of peer status word)
1526/// to its display name, matching real C ntpq output.
1527fn peer_event_name(code: u16) -> &'static str {
1528    match code {
1529        0 => "no event",
1530        1 => "reach",
1531        2 => "authen",
1532        3 => "mobilze",
1533        4 => "pkt_int",
1534        5 => "assoc",
1535        6 => "sel_rep",
1536        7 => "sys_clk",
1537        8 => "rate_excd",
1538        9 => "mobilze",
1539        10 => "demobil",
1540        11 => "unreach",
1541        12 => "seltest",
1542        13 => "popcorn",
1543        14 => "intervnt",
1544        _ => "unknown",
1545    }
1546}
1547
1548/// Render peers billboard in ntpq-compatible format.
1549pub fn format_peers(rows: &[PeerRow]) -> String {
1550    let mut out = String::new();
1551    out.push_str("remote           refid      st t when poll reach   delay   offset  jitter\n");
1552    out.push_str(
1553        "==============================================================================\n",
1554    );
1555    for row in rows {
1556        let when_str = match row.when {
1557            Some(s) if s < 1000 => format!("{}", s),
1558            Some(s) if s < 3600 => format!("{}m", s / 60),
1559            Some(s) => format!("{}h", s / 3600),
1560            None => "-".to_string(),
1561        };
1562        let reach_str = format!("{:o}", row.reach); // Octal display
1563        out.push_str(&format!(
1564            "{}{:15} {:12} {:2} {} {:>5} {:>4} {:>5} {:>9.3} {:>8.3} {:>7.3}\n",
1565            row.tally,
1566            row.remote,
1567            row.refid,
1568            row.stratum,
1569            row.peer_type,
1570            when_str,
1571            row.poll,
1572            reach_str,
1573            row.delay,
1574            row.offset,
1575            row.jitter,
1576        ));
1577    }
1578    out
1579}
1580
1581// ──── Test Mode 6 Server ────────────────────────────────────────────────
1582// In-process UDP server that responds to Mode 6 requests with configurable
1583// responses. Used by local oracle courts below.
1584
1585#[cfg(test)]
1586pub(crate) mod test_mode6_server {
1587    use std::net::UdpSocket;
1588    use std::sync::atomic::{AtomicBool, Ordering};
1589    use std::sync::Arc;
1590    use std::thread;
1591    use std::time::Duration;
1592
1593    /// A simple Mode 6 test server that responds to one request.
1594    pub struct TestMode6Server {
1595        pub port: u16,
1596        stop: Arc<AtomicBool>,
1597        join: Option<thread::JoinHandle<()>>,
1598    }
1599
1600    impl TestMode6Server {
1601        /// Create a server that waits for one request, then sends `response_bytes`.
1602        pub fn serve(response_bytes: Vec<u8>) -> Self {
1603            Self::serve_conditional(move |_buf, _len| Some(response_bytes.clone()))
1604        }
1605
1606        /// Create a server that computes a response based on the received request.
1607        /// The closure receives the raw request bytes and length, and returns
1608        /// an optional response (None = don't respond).
1609        pub fn serve_conditional<F>(handler: F) -> Self
1610        where
1611            F: Fn(&[u8], usize) -> Option<Vec<u8>> + Send + 'static,
1612        {
1613            let socket = UdpSocket::bind("127.0.0.1:0").expect("test server bind");
1614            socket
1615                .set_read_timeout(Some(Duration::from_secs(10)))
1616                .expect("test server set timeout");
1617            let port = socket.local_addr().unwrap().port();
1618            let stop = Arc::new(AtomicBool::new(false));
1619            let stop_clone = stop.clone();
1620
1621            // Barrier ensures the server thread is ready before returning.
1622            use std::sync::Barrier;
1623            let barrier = Arc::new(Barrier::new(2));
1624            let barrier_clone = barrier.clone();
1625
1626            let join = thread::spawn(move || {
1627                // Signal readiness: the socket is bound and the thread is alive.
1628                barrier_clone.wait();
1629
1630                let mut buf = [0u8; 512];
1631                loop {
1632                    if stop_clone.load(Ordering::Relaxed) {
1633                        break;
1634                    }
1635                    match socket.recv_from(&mut buf) {
1636                        Ok((len, src)) => {
1637                            if let Some(response) = handler(&buf, len) {
1638                                let _ = socket.send_to(&response, src);
1639                            }
1640                        }
1641                        Err(ref e)
1642                            if e.kind() == std::io::ErrorKind::WouldBlock
1643                                || e.kind() == std::io::ErrorKind::TimedOut =>
1644                        {
1645                            continue;
1646                        }
1647                        Err(_) => break,
1648                    }
1649                }
1650            });
1651
1652            // Wait for the server thread to signal readiness.
1653            barrier.wait();
1654
1655            Self {
1656                port,
1657                stop,
1658                join: Some(join),
1659            }
1660        }
1661
1662        /// Serve a sequence of responses, one per incoming request.
1663        /// Each request gets the next response in the sequence.
1664        /// Useful for multi-request operations like read_system_vars.
1665        pub fn serve_sequence(responses: Vec<Vec<u8>>) -> Self {
1666            use std::sync::Mutex;
1667            let idx = Arc::new(Mutex::new(0usize));
1668            let resp = Arc::new(responses);
1669            Self::serve_conditional(move |_buf, _len| {
1670                let mut i = idx.lock().unwrap();
1671                if *i < resp.len() {
1672                    let r = Some(resp[*i].clone());
1673                    *i += 1;
1674                    r
1675                } else {
1676                    None
1677                }
1678            })
1679        }
1680
1681        /// Receive one request, then send all fragments in sequence with small delays.
1682        pub fn serve_fragments(fragments: Vec<Vec<u8>>) -> Self {
1683            let socket = UdpSocket::bind("127.0.0.1:0").expect("test server bind");
1684            socket
1685                .set_read_timeout(Some(Duration::from_secs(10)))
1686                .expect("test server set timeout");
1687            let port = socket.local_addr().unwrap().port();
1688            let stop = Arc::new(AtomicBool::new(false));
1689            let stop_clone = stop.clone();
1690
1691            use std::sync::Barrier;
1692            let barrier = Arc::new(Barrier::new(2));
1693            let barrier_clone = barrier.clone();
1694
1695            let join = thread::spawn(move || {
1696                barrier_clone.wait();
1697                let mut buf = [0u8; 512];
1698                loop {
1699                    if stop_clone.load(Ordering::Relaxed) {
1700                        break;
1701                    }
1702                    match socket.recv_from(&mut buf) {
1703                        Ok((_len, src)) => {
1704                            for frag in &fragments {
1705                                let _ = socket.send_to(frag, src);
1706                                thread::sleep(Duration::from_millis(10));
1707                            }
1708                            break;
1709                        }
1710                        Err(ref e)
1711                            if e.kind() == std::io::ErrorKind::WouldBlock
1712                                || e.kind() == std::io::ErrorKind::TimedOut =>
1713                        {
1714                            continue;
1715                        }
1716                        Err(_) => break,
1717                    }
1718                }
1719            });
1720
1721            barrier.wait();
1722
1723            Self {
1724                port,
1725                stop,
1726                join: Some(join),
1727            }
1728        }
1729
1730        /// Receive multiple requests, each receiving a group of fragments.
1731        /// The outer Vec is one entry per expected request; each inner Vec
1732        /// is the fragments to send for that request.
1733        #[allow(dead_code)]
1734        pub fn serve_fragment_groups(groups: Vec<Vec<Vec<u8>>>) -> Self {
1735            let socket = UdpSocket::bind("127.0.0.1:0").expect("test server bind");
1736            socket
1737                .set_read_timeout(Some(Duration::from_secs(10)))
1738                .expect("test server set timeout");
1739            let port = socket.local_addr().unwrap().port();
1740            let stop = Arc::new(AtomicBool::new(false));
1741            let stop_clone = stop.clone();
1742
1743            use std::sync::Barrier;
1744            let barrier = Arc::new(Barrier::new(2));
1745            let barrier_clone = barrier.clone();
1746
1747            let join = thread::spawn(move || {
1748                barrier_clone.wait();
1749                let mut buf = [0u8; 512];
1750                let mut group_idx = 0usize;
1751                loop {
1752                    if stop_clone.load(Ordering::Relaxed) {
1753                        break;
1754                    }
1755                    if group_idx >= groups.len() {
1756                        break;
1757                    }
1758                    match socket.recv_from(&mut buf) {
1759                        Ok((_len, src)) => {
1760                            for frag in &groups[group_idx] {
1761                                let _ = socket.send_to(frag, src);
1762                                thread::sleep(Duration::from_millis(10));
1763                            }
1764                            group_idx += 1;
1765                        }
1766                        Err(ref e)
1767                            if e.kind() == std::io::ErrorKind::WouldBlock
1768                                || e.kind() == std::io::ErrorKind::TimedOut =>
1769                        {
1770                            continue;
1771                        }
1772                        Err(_) => break,
1773                    }
1774                }
1775            });
1776
1777            barrier.wait();
1778
1779            Self {
1780                port,
1781                stop,
1782                join: Some(join),
1783            }
1784        }
1785    }
1786
1787    impl Drop for TestMode6Server {
1788        fn drop(&mut self) {
1789            self.stop.store(true, Ordering::Relaxed);
1790            if let Ok(s) = UdpSocket::bind("127.0.0.1:0") {
1791                let _ = s.send_to(b"\x00", format!("127.0.0.1:{}", self.port));
1792            }
1793            if let Some(join) = self.join.take() {
1794                let _ = join.join();
1795            }
1796        }
1797    }
1798
1799    /// Build a Mode 6 READVAR response payload (system variables as text).
1800    pub fn make_readvar_response(
1801        associd: u16,
1802        sequence: u16,
1803        status: u16,
1804        variable_text: &str,
1805        more: bool,
1806    ) -> Vec<u8> {
1807        use crate::ntp_control::*;
1808        use crate::ntp_types::NtpPacket;
1809        let msg = ControlMessage {
1810            li_vn_mode: NtpPacket::set_li_vn_mode(
1811                crate::ntp_types::LeapIndicator::NoWarning,
1812                crate::ntp_types::NtpVersion::V4,
1813                crate::ntp_types::NtpMode::NtpControl,
1814            ),
1815            opcode: ControlOpcode::new(true, false, more, opcodes::OP_READVAR).to_u8(),
1816            sequence,
1817            status,
1818            associd,
1819            offset: 0,
1820            count: variable_text.len() as u16,
1821        };
1822        let mut buf = msg.encode().to_vec();
1823        buf.extend_from_slice(variable_text.as_bytes());
1824        buf
1825    }
1826
1827    /// Build a Mode 6 error response.
1828    pub fn make_error_response(associd: u16, sequence: u16, error_code: u8) -> Vec<u8> {
1829        use crate::ntp_control::*;
1830        use crate::ntp_types::NtpPacket;
1831        let msg = ControlMessage {
1832            li_vn_mode: NtpPacket::set_li_vn_mode(
1833                crate::ntp_types::LeapIndicator::NoWarning,
1834                crate::ntp_types::NtpVersion::V4,
1835                crate::ntp_types::NtpMode::NtpControl,
1836            ),
1837            opcode: ControlOpcode::new(true, true, false, opcodes::OP_READVAR).to_u8(),
1838            sequence,
1839            status: (error_code as u16) << 8,
1840            associd,
1841            offset: 0,
1842            count: 0,
1843        };
1844        msg.encode().to_vec()
1845    }
1846
1847    /// Build an associations (READSTAT) binary response.
1848    pub fn make_readstat_response(sequence: u16, assoc_pairs: &[(u16, u16)]) -> Vec<u8> {
1849        use crate::ntp_control::*;
1850        use crate::ntp_types::NtpPacket;
1851        let mut payload = Vec::with_capacity(assoc_pairs.len() * 4);
1852        for &(aid, st) in assoc_pairs {
1853            payload.extend_from_slice(&aid.to_be_bytes());
1854            payload.extend_from_slice(&st.to_be_bytes());
1855        }
1856        let msg = ControlMessage {
1857            li_vn_mode: NtpPacket::set_li_vn_mode(
1858                crate::ntp_types::LeapIndicator::NoWarning,
1859                crate::ntp_types::NtpVersion::V4,
1860                crate::ntp_types::NtpMode::NtpControl,
1861            ),
1862            opcode: ControlOpcode::new(true, false, false, opcodes::OP_READSTAT).to_u8(),
1863            sequence,
1864            status: 0x0622,
1865            associd: 0,
1866            offset: 0,
1867            count: payload.len() as u16,
1868        };
1869        let mut buf = msg.encode().to_vec();
1870        buf.extend_from_slice(&payload);
1871        buf
1872    }
1873}
1874
1875// ──── Tests ───────────────────────────────────────────────────────────
1876
1877#[cfg(test)]
1878mod tests {
1879    use super::*;
1880
1881    // ──── Fragment Collector Courts ───────────────────────────────────
1882
1883    #[test]
1884    fn test_fragment_single() {
1885        let mut fc = FragmentCollector::new();
1886        let done = fc
1887            .add_fragment(0, 10, b"0123456789", false, 0x0622, 0)
1888            .unwrap();
1889        assert!(done);
1890        let assembled = fc.assemble().unwrap();
1891        assert_eq!(assembled, b"0123456789");
1892    }
1893
1894    #[test]
1895    fn test_fragment_two_parts_in_order() {
1896        let mut fc = FragmentCollector::new();
1897        let done = fc.add_fragment(0, 5, b"01234", true, 0x0622, 0).unwrap();
1898        assert!(!done);
1899        let done = fc.add_fragment(5, 5, b"56789", false, 0x0622, 0).unwrap();
1900        assert!(done);
1901        let assembled = fc.assemble().unwrap();
1902        assert_eq!(assembled, b"0123456789");
1903    }
1904
1905    #[test]
1906    fn test_fragment_out_of_order() {
1907        let mut fc = FragmentCollector::new();
1908        let _ = fc.add_fragment(5, 5, b"56789", false, 0x0622, 0).unwrap();
1909        assert!(!fc.is_complete());
1910        let _ = fc.add_fragment(0, 5, b"01234", true, 0x0622, 0).unwrap();
1911        assert!(fc.is_complete());
1912        let assembled = fc.assemble().unwrap();
1913        assert_eq!(assembled, b"0123456789");
1914    }
1915
1916    #[test]
1917    fn test_fragment_hole_detected() {
1918        let mut fc = FragmentCollector::new();
1919        let _ = fc.add_fragment(0, 5, b"01234", true, 0x0622, 0).unwrap();
1920        let _ = fc.add_fragment(10, 5, b"56789", false, 0x0622, 0).unwrap();
1921        assert!(!fc.is_complete()); // Hole at 5-10
1922    }
1923
1924    #[test]
1925    fn test_fragment_overlap_consistent() {
1926        let mut fc = FragmentCollector::new();
1927        let _ = fc.add_fragment(0, 6, b"012345", true, 0x0622, 0).unwrap();
1928        // Overlapping consistent data
1929        let r = fc.add_fragment(3, 6, b"345678", false, 0x0622, 0);
1930        assert!(r.is_ok());
1931        assert!(fc.is_complete());
1932    }
1933
1934    #[test]
1935    fn test_fragment_overlap_conflict() {
1936        let mut fc = FragmentCollector::new();
1937        let _ = fc.add_fragment(0, 5, b"01234", true, 0x0622, 0).unwrap();
1938        // Overlapping INCONSISTENT data
1939        let r = fc.add_fragment(2, 5, b"XXXXX", false, 0x0622, 0);
1940        assert!(r.is_err());
1941    }
1942
1943    #[test]
1944    fn test_fragment_inconsistent_final_end() {
1945        let mut fc = FragmentCollector::new();
1946        // First fragment claims more=false at extent 5
1947        let _ = fc.add_fragment(0, 5, b"01234", false, 0x0622, 0).unwrap();
1948        // Second fragment also claims more=false but at extent 15 — INCONSISTENT
1949        let r = fc.add_fragment(5, 10, b"5678901234", false, 0x0622, 0);
1950        assert!(r.is_err());
1951    }
1952
1953    #[test]
1954    fn test_fragment_empty_response() {
1955        let mut fc = FragmentCollector::new();
1956        let done = fc.add_fragment(0, 0, b"", false, 0x0622, 0).unwrap();
1957        assert!(done);
1958        let assembled = fc.assemble().unwrap();
1959        assert!(assembled.is_empty());
1960    }
1961
1962    #[test]
1963    fn test_fragment_three_parts() {
1964        let mut fc = FragmentCollector::new();
1965        let _ = fc.add_fragment(0, 3, b"012", true, 0x0622, 0).unwrap();
1966        let _ = fc.add_fragment(3, 3, b"345", true, 0x0622, 0).unwrap();
1967        let done = fc.add_fragment(6, 4, b"6789", false, 0x0622, 0).unwrap();
1968        assert!(done);
1969        assert_eq!(fc.assemble().unwrap(), b"0123456789");
1970    }
1971
1972    #[test]
1973    fn test_fragment_excess_past_final_rejected() {
1974        let mut fc = FragmentCollector::new();
1975        // First fragment more=false at extent 5 → final_end=5
1976        let _ = fc.add_fragment(0, 5, b"01234", false, 0x0622, 0).unwrap();
1977        // Non-final fragment at 5..10 extends past final_end=5
1978        let r = fc.add_fragment(5, 5, b"56789", true, 0x0622, 0);
1979        assert!(r.is_err());
1980    }
1981
1982    #[test]
1983    fn test_fragment_reverse_order_excess_rejected() {
1984        let mut fc = FragmentCollector::new();
1985        // Excess fragment 0..12 arrives FIRST (non-final), extending past
1986        // the eventual final_end=10
1987        let _ = fc
1988            .add_fragment(0, 12, b"0123456789ab", true, 0x0622, 0)
1989            .unwrap();
1990        // Smaller final fragment 0..10 arrives LATER — should reject because
1991        // existing fragment 0..12 extends past final_end=10
1992        let r = fc.add_fragment(0, 10, b"0123456789", false, 0x0622, 0);
1993        assert!(r.is_err(), "existing fragment extends past new final_end");
1994    }
1995
1996    #[test]
1997    fn test_fragment_shrink_rejected() {
1998        let mut fc = FragmentCollector::new();
1999        // Fragment 0..10 arrives first
2000        let _ = fc
2001            .add_fragment(0, 10, b"0123456789", true, 0x0622, 0)
2002            .unwrap();
2003        // Same offset 0 with smaller payload 0..5 — should reject
2004        let r = fc.add_fragment(0, 5, b"01234", false, 0x0622, 0);
2005        assert!(r.is_err(), "retrograde fragment must be rejected");
2006    }
2007
2008    #[test]
2009    fn test_fragment_excess_extent_violation() {
2010        // Fragment 0..10 with more=true arrives first (covers bytes 0-10).
2011        let mut fc = FragmentCollector::new();
2012        let _ = fc
2013            .add_fragment(0, 10, b"0123456789", true, 0x0622, 0)
2014            .unwrap();
2015        // Final fragment at offset 3, count=2 declares final_end=5.
2016        // Existing fragment 0..10 extends to byte 10 > 5 → reject.
2017        // The overlapping bytes "34" match, so overlap is consistent;
2018        // rejection is purely from the extent invariant.
2019        let r = fc.add_fragment(3, 2, b"34", false, 0x0622, 0);
2020        assert!(
2021            r.is_err(),
2022            "existing fragment 0..10 extending to 10 must be rejected when final_end=5"
2023        );
2024    }
2025
2026    #[test]
2027    fn test_fragment_overflow_rejected() {
2028        let mut fc = FragmentCollector::new();
2029        // offset=65535, count=10 would overflow u16
2030        let r = fc.add_fragment(u16::MAX, 10, b"0123456789", false, 0x0622, 0);
2031        assert!(r.is_err());
2032    }
2033
2034    // ──── Association Status Courts ───────────────────────────────────
2035
2036    #[test]
2037    fn test_readstat_bytes_parsing() {
2038        let data = vec![
2039            0x00, 0x01, 0x96,
2040            0x14, // associd=1, status=0x9614 (configured|reachable|sys.peer)
2041            0x00, 0x02, 0x80, 0x10, // associd=2, status=0x8010 (configured|reachable)
2042        ];
2043        let assocs = AssociationStatus::from_bytes(&data).unwrap();
2044        assert_eq!(assocs.len(), 2);
2045        assert_eq!(assocs[0].associd, 1);
2046        assert!(assocs[0].configured);
2047        assert!(assocs[0].reachable);
2048        assert_eq!(assocs[0].selection, 6);
2049        assert_eq!(assocs[0].tally_char(), '*');
2050        assert_eq!(assocs[1].selection, 0);
2051        assert_eq!(assocs[1].tally_char(), ' ');
2052    }
2053
2054    #[test]
2055    fn test_wrong_length_rejected() {
2056        assert!(AssociationStatus::from_bytes(&[0u8; 5]).is_err());
2057    }
2058
2059    // ──── Variable Parser Courts ──────────────────────────────────────
2060
2061    #[test]
2062    fn test_parse_mode6_vars_simple() {
2063        let vars = parse_mode6_vars("stratum=2,offset=0.005,leap=00");
2064        assert_eq!(vars.len(), 3);
2065        assert_eq!(vars[0], ("stratum".to_string(), "2".to_string()));
2066        assert_eq!(vars[1], ("offset".to_string(), "0.005".to_string()));
2067    }
2068
2069    #[test]
2070    fn test_parse_mode6_vars_quoted() {
2071        let vars = parse_mode6_vars(r#"version="ntpd 4.2.8",stratum=2"#);
2072        assert_eq!(vars.len(), 2);
2073        assert_eq!(vars[0].0, "version");
2074        // Quotes should be stripped
2075        assert_eq!(vars[0].1, "ntpd 4.2.8");
2076        assert_eq!(vars[1], ("stratum".to_string(), "2".to_string()));
2077    }
2078
2079    #[test]
2080    fn test_parse_mode6_vars_quoted_comma() {
2081        let vars = parse_mode6_vars(r#"name="a,b",value=42"#);
2082        assert_eq!(vars.len(), 2);
2083        assert_eq!(vars[0].1, "a,b"); // Comma inside quotes preserved
2084        assert_eq!(vars[1], ("value".to_string(), "42".to_string()));
2085    }
2086
2087    // ──── System Variables Courts ─────────────────────────────────────
2088
2089    #[test]
2090    fn test_system_variables_parsing() {
2091        let text = r#"version="ntpd 4.2.8",stratum=2,offset=0.005,leap=00"#;
2092        let sv = SystemVariables::from_text(text, 0, 0x0622);
2093        assert_eq!(sv.get("version"), Some("ntpd 4.2.8"));
2094        assert_eq!(sv.get("stratum"), Some("2"));
2095        assert_eq!(sv.stratum(), 2);
2096        assert_eq!(sv.leap_str(), "leap_none");
2097    }
2098
2099    // ──── Renderer Courts ─────────────────────────────────────────────
2100
2101    #[test]
2102    fn test_associations_format() {
2103        let assocs = vec![AssociationStatus {
2104            associd: 49723,
2105            status: 0x9614,
2106            configured: true,
2107            auth_enabled: true,
2108            auth_ok: false,
2109            reachable: true,
2110            broadcast: false,
2111            selection: 6,
2112        }];
2113        let out = format_associations(&assocs);
2114        assert!(out.contains("49723"));
2115        assert!(out.contains("sys.peer"));
2116        assert!(out.contains("yes"));
2117    }
2118
2119    #[test]
2120    fn test_peers_format_header() {
2121        let rows = vec![PeerRow {
2122            tally: '*',
2123            remote: "127.0.0.1".to_string(),
2124            refid: ".LOCL.".to_string(),
2125            associd: 1,
2126            stratum: 1,
2127            peer_type: 'u',
2128            when: None,
2129            poll: 64,
2130            reach: 0o17,
2131            delay: 0.0,
2132            offset: 0.0,
2133            jitter: 0.001,
2134        }];
2135        let out = format_peers(&rows);
2136        assert!(out.contains("127.0.0.1"));
2137        assert!(out.contains("*127.0.0.1"), "tally should prefix remote");
2138        assert!(out.contains(".LOCL."), "refid should be dot-wrapped");
2139    }
2140
2141    #[test]
2142    fn test_readvar_format() {
2143        // Status description decodes from the status word, not variables.
2144        // 0x0622: li=0(none), source=6(CTL_SST_TS_NTP), count=2, event=2(no_reply)
2145        let text = r#"version="ntpd 4.2.8",stratum=2,offset=0.005"#;
2146        let sv = SystemVariables::from_text(text, 0, 0x0622);
2147        let out = format_readvar(&sv);
2148        assert!(out.contains("associd=0"));
2149        assert!(out.contains("leap_none, sync_ntp, 2 no_reach"));
2150        assert!(out.contains("stratum=2"));
2151    }
2152
2153    #[test]
2154    fn test_readvar_extra_vars() {
2155        // Verify that format_readvar includes variables beyond the preferred list
2156        let text = "version=ntpd,stratum=2,offset=0.005,leap=00,extra_var=42";
2157        let sv = SystemVariables::from_text(text, 0, 0x0622);
2158        let out = format_readvar(&sv);
2159        assert!(out.contains("extra_var=42"), "extra vars must be included");
2160    }
2161
2162    // ──── Frozen Renderer Fixture Courts ──────────────────────────────
2163
2164    #[test]
2165    fn test_format_readvar_frozen_parity() {
2166        // Exact known-good output matching real ntpq -c rv.
2167        // Status word 0x0322: li=0(none), source=3(ntp), count=2, event=2
2168        let text = r##"version="ntpd 4.2.8p3",processor="x86_64",system="Linux/4.19.0",stratum=2,precision=-24,rootdelay=0.001,rootdisp=0.005,refid=.NTP.,reftime=0,peer=0,tc=6,offset=0.002,frequency=0.123,sys_jitter=0.001,rootdist=0.006"##;
2169        let sv = SystemVariables::from_text(text, 0, 0x0322);
2170        let out = format_readvar(&sv);
2171        // The output preserves input order with line wrapping at ~60 chars.
2172        // The input has: version, processor, system, stratum, precision,
2173        // rootdelay, rootdisp, refid, reftime, peer, tc, offset, frequency,
2174        // sys_jitter, rootdist — exactly as they appear in the output.
2175        let expected = concat!(
2176            "associd=0 status=0322 leap_none, sync_ntp, 2 no_reach,\n",
2177            "version=ntpd 4.2.8p3, processor=x86_64, system=Linux/4.19.0,\n",
2178            "stratum=2, precision=-24, rootdelay=0.001, rootdisp=0.005,\n",
2179            "refid=.NTP., reftime=0, peer=0, tc=6, offset=0.002,\n",
2180            "frequency=0.123, sys_jitter=0.001, rootdist=0.006,\n",
2181        );
2182        assert_eq!(out, expected, "frozen system readvar output mismatch");
2183    }
2184
2185    #[test]
2186    fn test_format_readvar_extra_vars() {
2187        // Extra variables beyond core set appear, input order is preserved
2188        let text = "version=ntpd,stratum=2,extra_var=42,z_var=99,offset=0.005";
2189        let sv = SystemVariables::from_text(text, 0, 0);
2190        let out = format_readvar(&sv);
2191        assert!(
2192            out.starts_with("associd=0 status=0000 "),
2193            "output should start with associd/status header"
2194        );
2195        assert!(
2196            out.contains("extra_var=42"),
2197            "extra_var must appear in output"
2198        );
2199        assert!(out.contains("z_var=99"), "z_var must appear in output");
2200        // All vars appear in output (input order preserved)
2201        let version_pos = out.find("version=").unwrap();
2202        let stratum_pos = out.find("stratum=").unwrap();
2203        let extra_pos = out.find("extra_var=").unwrap();
2204        let z_pos = out.find("z_var=").unwrap();
2205        let offset_pos = out.find("offset=").unwrap();
2206        // Input order: version, stratum, extra_var, z_var, offset
2207        assert!(
2208            version_pos < stratum_pos,
2209            "version should appear before stratum"
2210        );
2211        assert!(
2212            stratum_pos < extra_pos,
2213            "stratum should appear before extra_var"
2214        );
2215        assert!(
2216            extra_pos < z_pos,
2217            "extra_var should appear before z_var (input order preserved)"
2218        );
2219        assert!(
2220            z_pos < offset_pos,
2221            "z_var should appear before offset (input order preserved)"
2222        );
2223    }
2224
2225    #[test]
2226    fn test_format_peer_readvar_frozen() {
2227        // Peer READVAR output format matches real ntpq
2228        let text = concat!(
2229            "srcaddr=192.168.1.1,",
2230            "stratum=2,",
2231            "offset=0.002,",
2232            "delay=0.001,",
2233            "dispersion=0.000,",
2234            "jitter=0.001,",
2235            "hpoll=6,",
2236            "ppoll=6,",
2237            "reach=0xFF,",
2238            "flash=0x000,",
2239            "leap=00,",
2240            "refid=.NTP.,",
2241            "reftime=0,",
2242            "hmode=3,",
2243            "pmode=4,",
2244            "precision=-24",
2245        );
2246        let pv = PeerVariables::from_text(text, 49723, 0x9614);
2247        let out = format_peer_readvar(&pv);
2248        let expected = concat!(
2249            "associd=49723 status=9614 1 pkt_int, 192.168.1.1,\n",
2250            "srcaddr=192.168.1.1\n",
2251            "stratum=2\n",
2252            "offset=0.002\n",
2253            "delay=0.001\n",
2254            "dispersion=0.000\n",
2255            "jitter=0.001\n",
2256            "hpoll=6\n",
2257            "ppoll=6\n",
2258            "reach=FF\n",
2259            "flash=000\n",
2260            "leap=00\n",
2261            "refid=.NTP.\n",
2262            "reftime=0\n",
2263            "hmode=3\n",
2264            "pmode=4\n",
2265            "precision=-24\n",
2266        );
2267        assert_eq!(out, expected, "frozen peer readvar output mismatch");
2268    }
2269
2270    #[test]
2271    fn test_format_associations_frozen() {
2272        // Exact output format for multiple associations
2273        let assocs = vec![
2274            AssociationStatus {
2275                associd: 49723,
2276                status: 0x9614,
2277                configured: true,
2278                auth_enabled: true,
2279                auth_ok: false,
2280                reachable: true,
2281                broadcast: false,
2282                selection: 6,
2283            },
2284            AssociationStatus {
2285                associd: 49724,
2286                status: 0x8010,
2287                configured: true,
2288                auth_enabled: false,
2289                auth_ok: false,
2290                reachable: true,
2291                broadcast: false,
2292                selection: 4,
2293            },
2294            AssociationStatus {
2295                associd: 49725,
2296                status: 0x8000,
2297                configured: true,
2298                auth_enabled: true,
2299                auth_ok: true,
2300                reachable: false,
2301                broadcast: false,
2302                selection: 0,
2303            },
2304        ];
2305        let out = format_associations(&assocs);
2306        // Build expected using the same format specs as production code
2307        let mut expected =
2308            String::from("ind assid status  conf reach auth condition  last_event cnt\n");
2309        expected.push_str("===========================================================\n");
2310        // Use format! to match the exact spacing from format_associations
2311        let fmt = |i: usize,
2312                   aid: u16,
2313                   st: u16,
2314                   conf: &str,
2315                   reach: &str,
2316                   auth: &str,
2317                   cond: &str,
2318                   ev: &str,
2319                   cnt: u16| {
2320            format!(
2321                "  {} {:5}  {:04x}   {:<3}  {:<3}  {:<4}  {:<10}  {:>8} {:>2}\n",
2322                i, aid, st, conf, reach, auth, cond, ev, cnt
2323            )
2324        };
2325        expected.push_str(&fmt(
2326            1,
2327            49723,
2328            0x9614,
2329            "yes",
2330            "yes",
2331            "yes",
2332            "sys.peer",
2333            "reach_brd",
2334            1,
2335        ));
2336        expected.push_str(&fmt(
2337            2,
2338            49724,
2339            0x8010,
2340            "yes",
2341            "yes",
2342            "none",
2343            "candidate",
2344            "restart",
2345            1,
2346        ));
2347        expected.push_str(&fmt(
2348            3, 49725, 0x8000, "yes", "no", "ok", "rejected", "restart", 0,
2349        ));
2350        assert_eq!(out, expected, "frozen associations output mismatch");
2351    }
2352
2353    #[test]
2354    fn test_format_peers_frozen() {
2355        // Exact peers billboard output format
2356        let rows = vec![
2357            PeerRow {
2358                tally: '*',
2359                remote: "time.example.com".to_string(),
2360                refid: ".NTP.".to_string(),
2361                associd: 1,
2362                stratum: 2,
2363                peer_type: 'u',
2364                when: Some(10),
2365                poll: 64,
2366                reach: 0o377,
2367                delay: 0.001,
2368                offset: 0.002,
2369                jitter: 0.001,
2370            },
2371            PeerRow {
2372                tally: ' ',
2373                remote: "192.168.1.100".to_string(),
2374                refid: ".GPS.".to_string(),
2375                associd: 2,
2376                stratum: 1,
2377                peer_type: 'u',
2378                when: None,
2379                poll: 64,
2380                reach: 0o377,
2381                delay: 0.003,
2382                offset: -0.001,
2383                jitter: 0.002,
2384            },
2385        ];
2386        let out = format_peers(&rows);
2387        // Build expected using the same format specs used by the production code
2388        let mut expected = String::new();
2389        expected.push_str(
2390            "remote           refid      st t when poll reach   delay   offset  jitter\n",
2391        );
2392        expected.push_str(
2393            "==============================================================================\n",
2394        );
2395        // Row 1
2396        expected.push_str(&format!(
2397            "{}{:15} {:12} {:2} {} {:>5} {:>4} {:>5} {:>9.3} {:>8.3} {:>7.3}\n",
2398            '*', "time.example.com", ".NTP.", 2, 'u', "10", 64, "377", 0.001, 0.002, 0.001,
2399        ));
2400        // Row 2
2401        expected.push_str(&format!(
2402            "{}{:15} {:12} {:2} {} {:>5} {:>4} {:>5} {:>9.3} {:>8.3} {:>7.3}\n",
2403            ' ', "192.168.1.100", ".GPS.", 1, 'u', "-", 64, "377", 0.003, -0.001, 0.002,
2404        ));
2405        assert_eq!(out, expected, "frozen peers output mismatch");
2406    }
2407
2408    #[test]
2409    fn test_format_peers_when_units() {
2410        // Test that when values render correctly with different units
2411        let rows = vec![
2412            PeerRow {
2413                tally: ' ',
2414                remote: "a".to_string(),
2415                refid: ".X.".to_string(),
2416                associd: 1,
2417                stratum: 1,
2418                peer_type: 'u',
2419                when: Some(45),
2420                poll: 64,
2421                reach: 0o377,
2422                delay: 0.0,
2423                offset: 0.0,
2424                jitter: 0.0,
2425            },
2426            PeerRow {
2427                tally: ' ',
2428                remote: "b".to_string(),
2429                refid: ".X.".to_string(),
2430                associd: 2,
2431                stratum: 1,
2432                peer_type: 'u',
2433                when: Some(1100),
2434                poll: 64,
2435                reach: 0o377,
2436                delay: 0.0,
2437                offset: 0.0,
2438                jitter: 0.0,
2439            },
2440            PeerRow {
2441                tally: ' ',
2442                remote: "c".to_string(),
2443                refid: ".X.".to_string(),
2444                associd: 3,
2445                stratum: 1,
2446                peer_type: 'u',
2447                when: Some(3660),
2448                poll: 64,
2449                reach: 0o377,
2450                delay: 0.0,
2451                offset: 0.0,
2452                jitter: 0.0,
2453            },
2454            PeerRow {
2455                tally: ' ',
2456                remote: "d".to_string(),
2457                refid: ".X.".to_string(),
2458                associd: 4,
2459                stratum: 1,
2460                peer_type: 'u',
2461                when: None,
2462                poll: 64,
2463                reach: 0o377,
2464                delay: 0.0,
2465                offset: 0.0,
2466                jitter: 0.0,
2467            },
2468        ];
2469        let out = format_peers(&rows);
2470        assert!(out.contains("45"), "when=45 should render as '45'");
2471        assert!(out.contains("18m"), "when=1100 should render as '18m'");
2472        assert!(out.contains("1h"), "when=3660 should render as '1h'");
2473        assert!(out.contains("  -"), "when=None should render as '-'");
2474    }
2475
2476    #[test]
2477    fn test_associations_format_many() {
2478        // Test all selection values render correct condition strings
2479        let selection_labels = [
2480            (0usize, "rejected"),
2481            (1usize, "falsetick"),
2482            (2usize, "excess"),
2483            (3usize, "outlyer"),
2484            (4usize, "candidate"),
2485            (5usize, "backup"),
2486            (6usize, "sys.peer"),
2487            (7usize, "rejected"),
2488        ];
2489        let assocs: Vec<AssociationStatus> = selection_labels
2490            .iter()
2491            .map(|&(sel, _)| AssociationStatus {
2492                associd: 1000 + sel as u16,
2493                status: 0x8000 | (sel as u16),
2494                configured: true,
2495                auth_enabled: false,
2496                auth_ok: false,
2497                reachable: false,
2498                broadcast: false,
2499                selection: sel as u8,
2500            })
2501            .collect();
2502        let out = format_associations(&assocs);
2503        for &(sel, label) in &selection_labels {
2504            assert!(
2505                out.contains(label),
2506                "selection={} should produce condition string '{}'",
2507                sel,
2508                label
2509            );
2510        }
2511        // Verify count: 1 header + 1 separator + 8 data lines
2512        let lines: Vec<&str> = out.lines().collect();
2513        assert_eq!(
2514            lines.len(),
2515            10,
2516            "expected 10 lines (header, separator, 8 assocs)"
2517        );
2518        // Verify event_code and event_count appear in output
2519        assert!(out.contains("restart"), "event_code 0 should be restart");
2520        assert!(
2521            out.contains("reach_brd"),
2522            "event_code 4 should be reach_brd"
2523        );
2524    }
2525
2526    // ──── Local UDP Oracle Courts ──────────────────────────────────────
2527
2528    #[test]
2529    fn test_local_udp_readvar() {
2530        // read_system_vars now makes TWO requests (status + variables).
2531        // Serve an empty status response first, then the variable response.
2532        let variable_text = r#"version="ntpd 4.2.8",stratum=2,offset=0.005"#;
2533        let empty_resp = test_mode6_server::make_readvar_response(0, 1, 0x0622, "", false);
2534        let var_resp = test_mode6_server::make_readvar_response(0, 2, 0x0622, variable_text, false);
2535        let responses = vec![empty_resp, var_resp];
2536        let server = test_mode6_server::TestMode6Server::serve_sequence(responses);
2537        let mut client = ControlClient::new(5, 1);
2538        let result = client.read_system_vars("127.0.0.1", server.port);
2539        assert!(
2540            result.is_ok(),
2541            "read_system_vars failed: {:?}",
2542            result.err()
2543        );
2544        let sv = result.unwrap();
2545        assert_eq!(sv.associd, 0);
2546        assert_eq!(sv.get("stratum"), Some("2"));
2547        assert_eq!(sv.get("offset"), Some("0.005"));
2548    }
2549
2550    #[test]
2551    fn test_local_udp_readvar_fragmented() {
2552        // Two fragments: first more=true with "version=1,", second more=false with "stratum=2"
2553        let frag1 = test_mode6_server::make_readvar_response(0, 1, 0x0622, "version=1,", true);
2554        let mut frag2 = test_mode6_server::make_readvar_response(0, 1, 0x0622, "stratum=2", false);
2555        // Patch offset field (bytes 8..10) to 10, the length of "version=1,"
2556        let offset_bytes = 10u16.to_be_bytes();
2557        frag2[8..10].copy_from_slice(&offset_bytes);
2558
2559        let server = test_mode6_server::TestMode6Server::serve_fragments(vec![frag1, frag2]);
2560        let mut client = ControlClient::new(5, 2);
2561        // Use a direct readvar query to avoid multi-request lifecycle issues
2562        let msg = ControlMessage {
2563            li_vn_mode: 0,
2564            opcode: ControlOpcode::new(false, false, false, opcodes::OP_READVAR).to_u8(),
2565            sequence: 0,
2566            status: 0,
2567            associd: 0,
2568            offset: 0,
2569            count: 0,
2570        };
2571        let result = client.query("127.0.0.1", server.port, msg);
2572        assert!(
2573            result.is_ok(),
2574            "fragmented readvar failed: {:?}",
2575            result.err()
2576        );
2577        let (data, _, _) = result.unwrap();
2578        let text = String::from_utf8_lossy(&data).to_string();
2579        let sv = crate::control_client::SystemVariables::from_text(&text, 0, 0x0622);
2580        assert_eq!(sv.get("version"), Some("1"));
2581        assert_eq!(sv.get("stratum"), Some("2"));
2582    }
2583
2584    #[test]
2585    fn test_local_udp_wrong_sequence() {
2586        // Server responds with a different sequence number than requested
2587        // First request (status) also gets wrong sequence
2588        let status_resp = test_mode6_server::make_readvar_response(0, 99, 0x0622, "", false);
2589        let var_resp = test_mode6_server::make_readvar_response(0, 99, 0x0622, "stratum=2", false);
2590        let server =
2591            test_mode6_server::TestMode6Server::serve_sequence(vec![status_resp, var_resp]);
2592        let mut client = ControlClient::new(1, 0); // No retries, timeout
2593        let result = client.read_system_vars("127.0.0.1", server.port);
2594        assert!(result.is_err(), "wrong sequence must be rejected");
2595    }
2596
2597    #[test]
2598    fn test_local_udp_error_response() {
2599        // First request (status) gets an error response
2600        // read_system_vars makes TWO requests, so provide TWO error responses
2601        let err_resp = test_mode6_server::make_error_response(0, 1, 5); // CERR_NOTKNOWN
2602        let server =
2603            test_mode6_server::TestMode6Server::serve_sequence(vec![err_resp.clone(), err_resp]);
2604        // Use longer timeout to avoid race with server thread startup
2605        let mut client = ControlClient::new(5, 2);
2606        let result = client.read_system_vars("127.0.0.1", server.port);
2607        assert!(result.is_err(), "error must produce error");
2608    }
2609
2610    #[test]
2611    fn test_local_udp_timeout() {
2612        // Server that never responds
2613        let server = test_mode6_server::TestMode6Server::serve_conditional(|_, _| None);
2614        let mut client = ControlClient::new(1, 0); // 1s timeout, no retries
2615        let result = client.read_system_vars("127.0.0.1", server.port);
2616        assert!(result.is_err(), "timeout must produce error");
2617        match result.err().unwrap() {
2618            QueryError::Timeout => {}
2619            other => panic!("expected Timeout, got: {other}"),
2620        }
2621    }
2622
2623    #[test]
2624    fn test_local_udp_readstat() {
2625        let assocs: Vec<(u16, u16)> = vec![(1, 0x9614), (2, 0x8010)];
2626        let resp = test_mode6_server::make_readstat_response(1, &assocs);
2627        let server = test_mode6_server::TestMode6Server::serve(resp);
2628        let mut client = ControlClient::new(5, 1);
2629        let result = client.read_associations("127.0.0.1", server.port);
2630        assert!(
2631            result.is_ok(),
2632            "read_associations failed: {:?}",
2633            result.err()
2634        );
2635        let assocs = result.unwrap();
2636        assert_eq!(assocs.len(), 2);
2637        assert_eq!(assocs[0].associd, 1);
2638        assert!(assocs[0].configured);
2639        assert!(assocs[0].reachable);
2640        assert_eq!(assocs[0].selection, 6);
2641        assert_eq!(assocs[1].associd, 2);
2642        assert_eq!(assocs[1].selection, 0);
2643    }
2644
2645    #[test]
2646    fn test_local_udp_authentication_error() {
2647        let err_resp = test_mode6_server::make_error_response(0, 1, 1); // CERR_AUTH
2648        let server =
2649            test_mode6_server::TestMode6Server::serve_sequence(vec![err_resp.clone(), err_resp]);
2650
2651        // Test with TWO direct query() calls, not read_system_vars
2652        let mut client = ControlClient::new(5, 0);
2653
2654        let status_msg = ControlMessage {
2655            li_vn_mode: 0,
2656            opcode: ControlOpcode::new(false, false, false, opcodes::OP_READVAR).to_u8(),
2657            sequence: 0,
2658            status: 0,
2659            associd: 0,
2660            offset: 0,
2661            count: 0,
2662        };
2663
2664        let _r1 = client.query("127.0.0.1", server.port, status_msg);
2665
2666        let var_msg = ControlMessage {
2667            li_vn_mode: 0,
2668            opcode: ControlOpcode::new(false, false, false, opcodes::OP_READVAR).to_u8(),
2669            sequence: 0,
2670            status: 0,
2671            associd: 0,
2672            offset: 0,
2673            count: 0,
2674        };
2675
2676        let r2 = client.query("127.0.0.1", server.port, var_msg);
2677
2678        assert!(r2.is_err(), "second query should fail");
2679    }
2680
2681    // ──── Raw Bytes → Typed Model Courts ──────────────────────────────
2682
2683    #[test]
2684    fn test_raw_bytes_to_system_vars() {
2685        // Layer 1 fixture: raw Mode 6 response bytes → SystemVariables
2686        use crate::ntp_control::*;
2687        use crate::ntp_types::NtpPacket;
2688
2689        let variable_text = r##"version="ntpd 4.2.8p3",stratum=2,offset=0.005,leap=00,sync=3"##;
2690        let msg = ControlMessage {
2691            li_vn_mode: NtpPacket::set_li_vn_mode(
2692                crate::ntp_types::LeapIndicator::NoWarning,
2693                crate::ntp_types::NtpVersion::V4,
2694                crate::ntp_types::NtpMode::NtpControl,
2695            ),
2696            opcode: ControlOpcode::new(true, false, false, opcodes::OP_READVAR).to_u8(),
2697            sequence: 1,
2698            status: 0x0622,
2699            associd: 0,
2700            offset: 0,
2701            count: variable_text.len() as u16,
2702        };
2703        let mut wire_bytes = msg.encode().to_vec();
2704        wire_bytes.extend_from_slice(variable_text.as_bytes());
2705
2706        // Decode wire bytes using ControlMessage::decode
2707        let (decoded, after_header) = ControlMessage::decode(&wire_bytes).unwrap();
2708        assert_eq!(decoded.sequence, 1);
2709        assert_eq!(decoded.status, 0x0622);
2710        assert_eq!(decoded.associd, 0);
2711
2712        // Extract text payload
2713        let count = decoded.count as usize;
2714        let text = String::from_utf8_lossy(&after_header[..count]);
2715        let sv = SystemVariables::from_text(&text, decoded.associd, decoded.status);
2716
2717        // Verify typed model
2718        assert_eq!(sv.associd, 0);
2719        assert_eq!(sv.status, 0x0622);
2720        assert_eq!(sv.get("version"), Some("ntpd 4.2.8p3"));
2721        assert_eq!(sv.get("stratum"), Some("2"));
2722        assert_eq!(sv.get("offset"), Some("0.005"));
2723        assert_eq!(sv.leap_str(), "leap_none");
2724        // Verify layer 2: typed model → exact text output
2725        // Status 0x0622: li=0(none), source=6(CTL_SST_TS_NTP), count=2, event=2(no_reply)
2726        let out = format_readvar(&sv);
2727        assert!(out.starts_with("associd=0 status=0622 "));
2728        assert!(out.contains("leap_none, sync_ntp, 2 no_reach"));
2729        assert!(out.contains("stratum=2"));
2730        assert!(out.contains("offset=0.005"));
2731    }
2732
2733    #[test]
2734    fn test_raw_bytes_to_peer_vars() {
2735        // Layer 1 fixture: raw Mode 6 response bytes → PeerVariables
2736        use crate::ntp_control::*;
2737        use crate::ntp_types::NtpPacket;
2738
2739        let variable_text = "srcaddr=192.168.1.1,stratum=2,offset=0.002,delay=0.001";
2740        let msg = ControlMessage {
2741            li_vn_mode: NtpPacket::set_li_vn_mode(
2742                crate::ntp_types::LeapIndicator::NoWarning,
2743                crate::ntp_types::NtpVersion::V4,
2744                crate::ntp_types::NtpMode::NtpControl,
2745            ),
2746            opcode: ControlOpcode::new(true, false, false, opcodes::OP_READVAR).to_u8(),
2747            sequence: 1,
2748            status: 0x9614,
2749            associd: 49723,
2750            offset: 0,
2751            count: variable_text.len() as u16,
2752        };
2753        let mut wire_bytes = msg.encode().to_vec();
2754        wire_bytes.extend_from_slice(variable_text.as_bytes());
2755
2756        // Decode wire bytes
2757        let (decoded, after_header) = ControlMessage::decode(&wire_bytes).unwrap();
2758        let count = decoded.count as usize;
2759        let text = String::from_utf8_lossy(&after_header[..count]);
2760        let pv = PeerVariables::from_text(&text, decoded.associd, decoded.status);
2761
2762        // Verify typed model
2763        assert_eq!(pv.associd, 49723);
2764        assert_eq!(pv.status, 0x9614);
2765        assert_eq!(pv.get("srcaddr"), Some("192.168.1.1"));
2766        assert_eq!(pv.get("stratum"), Some("2"));
2767        assert_eq!(pv.get("offset"), Some("0.002"));
2768
2769        // Verify layer 2: typed model → exact text output
2770        let out = format_peer_readvar(&pv);
2771        assert!(out.contains("associd=49723 status=9614"));
2772        assert!(out.contains("srcaddr=192.168.1.1"));
2773        assert!(out.contains("stratum=2"));
2774    }
2775
2776    // ──── MRU List Tests (textual format) ───────────────────────────
2777
2778    #[test]
2779    fn test_mru_parse_ipv4_entry() {
2780        let text =
2781            "addr.0=192.168.1.1,last.0=3771763200.000000,first.0=3771763100.000000,ct.0=42,mv.0=0";
2782        let entries = MruEntry::parse_textual(text).unwrap();
2783        assert_eq!(entries.len(), 1);
2784        assert_eq!(entries[0].addr, "192.168.1.1");
2785        assert_eq!(entries[0].port, 0);
2786        assert_eq!(entries[0].last_pkt_secs, 3771763200);
2787        assert_eq!(entries[0].first_pkt_secs, 3771763100);
2788        assert_eq!(entries[0].count, 42);
2789        assert_eq!(entries[0].flags, 0);
2790        assert!(entries[0].format_entry().contains("clnt"));
2791    }
2792
2793    #[test]
2794    fn test_mru_parse_multiple_entries() {
2795        let text = concat!(
2796            "addr.0=192.168.1.1,last.0=3771763200.000000,first.0=3771763100.000000,ct.0=42,mv.0=0,",
2797            "addr.1=10.0.0.1,last.1=3771763300.000000,first.1=3771763200.000000,ct.1=100,mv.1=1"
2798        );
2799        let entries = MruEntry::parse_textual(text).unwrap();
2800        assert_eq!(entries.len(), 2);
2801        assert_eq!(entries[0].addr, "192.168.1.1");
2802        assert_eq!(entries[0].count, 42);
2803        assert_eq!(entries[0].flags, 0);
2804        assert_eq!(entries[1].addr, "10.0.0.1");
2805        assert_eq!(entries[1].count, 100);
2806        assert_eq!(entries[1].flags, 1);
2807    }
2808
2809    #[test]
2810    fn test_mru_parse_empty() {
2811        let entries = MruEntry::parse_textual("").unwrap();
2812        assert!(entries.is_empty());
2813    }
2814
2815    #[test]
2816    fn test_mru_format_list_empty() {
2817        let output = MruEntry::format_list(&[]);
2818        assert_eq!(output, "(empty MRU list)");
2819    }
2820
2821    #[test]
2822    fn test_mru_format_list_has_header() {
2823        let text =
2824            "addr.0=192.168.1.1,last.0=3771763200.000000,first.0=3771763100.000000,ct.0=1,mv.0=0";
2825        let entries = MruEntry::parse_textual(text).unwrap();
2826        let output = MruEntry::format_list(&entries);
2827        assert!(output.contains("addr"));
2828        assert!(output.contains("port"));
2829        assert!(output.contains("count"));
2830        assert!(output.contains("192.168.1.1"));
2831    }
2832
2833    #[test]
2834    fn test_mru_parse_with_nonce() {
2835        let text =
2836            "nonce=abc123,addr.0=192.168.1.1,last.0=3771763200.000000,first.0=3771763100.000000,ct.0=42,mv.0=0";
2837        let entries = MruEntry::parse_textual(text).unwrap();
2838        assert_eq!(entries.len(), 1);
2839        assert_eq!(entries[0].addr, "192.168.1.1");
2840        assert_eq!(entries[0].count, 42);
2841    }
2842}