async_snmp/cli/
output.rs

1//! Output formatting for CLI tools.
2//!
3//! Supports human-readable, JSON, and raw output formats.
4
5use crate::cli::args::OutputFormat;
6use crate::cli::hints;
7use crate::{Oid, Value, VarBind, Version};
8use serde::Serialize;
9use std::io::{self, Write};
10use std::net::SocketAddr;
11use std::time::Duration;
12
13/// Operation type for verbose output.
14#[derive(Debug, Clone, Copy)]
15pub enum OperationType {
16    Get,
17    GetNext,
18    GetBulk {
19        non_repeaters: i32,
20        max_repetitions: i32,
21    },
22    Set,
23    Walk,
24    BulkWalk {
25        max_repetitions: i32,
26    },
27}
28
29impl std::fmt::Display for OperationType {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        match self {
32            Self::Get => write!(f, "GET"),
33            Self::GetNext => write!(f, "GETNEXT"),
34            Self::GetBulk { .. } => write!(f, "GETBULK"),
35            Self::Set => write!(f, "SET"),
36            Self::Walk => write!(f, "WALK (GETNEXT)"),
37            Self::BulkWalk { .. } => write!(f, "WALK (GETBULK)"),
38        }
39    }
40}
41
42/// Security info for verbose output.
43#[derive(Debug, Clone)]
44pub enum SecurityInfo {
45    Community(String),
46    V3 {
47        username: String,
48        auth_protocol: Option<String>,
49        priv_protocol: Option<String>,
50    },
51}
52
53/// Request metadata for verbose output.
54#[derive(Debug)]
55pub struct RequestInfo {
56    pub target: SocketAddr,
57    pub version: Version,
58    pub security: SecurityInfo,
59    pub operation: OperationType,
60    pub oids: Vec<Oid>,
61}
62
63/// Write verbose request header to stderr.
64pub fn write_verbose_request(info: &RequestInfo) {
65    let mut stderr = std::io::stderr().lock();
66    let _ = writeln!(stderr, "--- Request ---");
67    let _ = writeln!(stderr, "Target:    {}", info.target);
68    let _ = writeln!(stderr, "Version:   {:?}", info.version);
69
70    match &info.security {
71        SecurityInfo::Community(c) => {
72            let _ = writeln!(stderr, "Community: {}", c);
73        }
74        SecurityInfo::V3 {
75            username,
76            auth_protocol,
77            priv_protocol,
78        } => {
79            let _ = writeln!(stderr, "Username:  {}", username);
80            if let Some(auth) = auth_protocol {
81                let _ = writeln!(stderr, "Auth:      {}", auth);
82            }
83            if let Some(priv_p) = priv_protocol {
84                let _ = writeln!(stderr, "Privacy:   {}", priv_p);
85            }
86        }
87    }
88
89    let _ = writeln!(stderr, "Operation: {}", info.operation);
90
91    if let OperationType::GetBulk {
92        non_repeaters,
93        max_repetitions,
94    } = info.operation
95    {
96        let _ = writeln!(stderr, "  Non-repeaters:    {}", non_repeaters);
97        let _ = writeln!(stderr, "  Max-repetitions:  {}", max_repetitions);
98    } else if let OperationType::BulkWalk { max_repetitions } = info.operation {
99        let _ = writeln!(stderr, "  Max-repetitions:  {}", max_repetitions);
100    }
101
102    let _ = writeln!(stderr, "OIDs:      {} total", info.oids.len());
103    for oid in &info.oids {
104        let hint = hints::lookup(oid);
105        if let Some(h) = hint {
106            let _ = writeln!(stderr, "  {} ({})", oid, h);
107        } else {
108            let _ = writeln!(stderr, "  {}", oid);
109        }
110    }
111    let _ = writeln!(stderr);
112}
113
114/// Write verbose response summary to stderr.
115pub fn write_verbose_response(varbinds: &[VarBind], elapsed: Duration, show_hints: bool) {
116    let mut stderr = std::io::stderr().lock();
117    let _ = writeln!(stderr, "--- Response ---");
118    let _ = writeln!(stderr, "Results:   {} varbind(s)", varbinds.len());
119    let _ = writeln!(stderr, "Time:      {:.2}ms", elapsed.as_secs_f64() * 1000.0);
120    let _ = writeln!(stderr);
121
122    for vb in varbinds {
123        write_verbose_varbind(&mut stderr, vb, show_hints);
124    }
125
126    if !varbinds.is_empty() {
127        let _ = writeln!(stderr);
128    }
129}
130
131/// Write detailed varbind information for verbose output.
132fn write_verbose_varbind<W: Write>(w: &mut W, vb: &VarBind, show_hints: bool) {
133    // OID with optional hint
134    let hint = if show_hints {
135        hints::lookup(&vb.oid)
136    } else {
137        None
138    };
139    if let Some(h) = hint {
140        let _ = writeln!(w, "  {} ({})", format_oid(&vb.oid), h);
141    } else {
142        let _ = writeln!(w, "  {}", format_oid(&vb.oid));
143    }
144
145    // Type and value details
146    let (type_name, decoded, raw_hex, size) = format_verbose_value(&vb.value);
147
148    let _ = writeln!(w, "    Type:    {}", type_name);
149    let _ = writeln!(w, "    Value:   {}", decoded);
150
151    if let Some(hex) = raw_hex {
152        let _ = writeln!(w, "    Raw:     {}", hex);
153    }
154
155    if let Some(s) = size {
156        let _ = writeln!(w, "    Size:    {} bytes", s);
157    }
158}
159
160/// Format a value for verbose output, returning (type_name, decoded_value, raw_hex, size).
161fn format_verbose_value(value: &Value) -> (String, String, Option<String>, Option<usize>) {
162    match value {
163        Value::Integer(v) => ("INTEGER".into(), format!("{}", v), None, None),
164
165        Value::OctetString(bytes) => {
166            let raw_hex = format_hex_string(bytes);
167            let size = Some(bytes.len());
168
169            if is_printable(bytes) {
170                let decoded = String::from_utf8_lossy(bytes).to_string();
171                (
172                    "STRING".into(),
173                    format!("\"{}\"", decoded),
174                    Some(raw_hex),
175                    size,
176                )
177            } else {
178                ("Hex-STRING".into(), raw_hex.clone(), Some(raw_hex), size)
179            }
180        }
181
182        Value::Null => ("NULL".into(), "(null)".into(), None, None),
183
184        Value::ObjectIdentifier(oid) => {
185            let s = format_oid(oid);
186            let hint = hints::lookup(oid);
187            let decoded = if let Some(h) = hint {
188                format!("{} ({})", s, h)
189            } else {
190                s
191            };
192            ("OID".into(), decoded, None, None)
193        }
194
195        Value::IpAddress(bytes) => {
196            let s = format!("{}.{}.{}.{}", bytes[0], bytes[1], bytes[2], bytes[3]);
197            ("IpAddress".into(), s, None, None)
198        }
199
200        Value::Counter32(v) => ("Counter32".into(), format!("{}", v), None, None),
201
202        Value::Gauge32(v) => ("Gauge32".into(), format!("{}", v), None, None),
203
204        Value::TimeTicks(v) => {
205            let formatted = format_timeticks(*v);
206            (
207                "TimeTicks".into(),
208                format!("{} ({})", v, formatted),
209                None,
210                None,
211            )
212        }
213
214        Value::Opaque(bytes) => {
215            let raw_hex = format_hex_string(bytes);
216            (
217                "Opaque".into(),
218                raw_hex.clone(),
219                Some(raw_hex),
220                Some(bytes.len()),
221            )
222        }
223
224        Value::Counter64(v) => ("Counter64".into(), format!("{}", v), None, None),
225
226        Value::NoSuchObject => (
227            "NoSuchObject".into(),
228            "No Such Object available".into(),
229            None,
230            None,
231        ),
232
233        Value::NoSuchInstance => (
234            "NoSuchInstance".into(),
235            "No Such Instance currently exists".into(),
236            None,
237            None,
238        ),
239
240        Value::EndOfMibView => (
241            "EndOfMibView".into(),
242            "No more variables left in this MIB View".into(),
243            None,
244            None,
245        ),
246
247        Value::Unknown { tag, data } => {
248            let raw_hex = format_hex_string(data);
249            (
250                format!("Unknown(0x{:02X})", tag),
251                raw_hex.clone(),
252                Some(raw_hex),
253                Some(data.len()),
254            )
255        }
256    }
257}
258
259/// Result of a GET/WALK operation, ready for output.
260#[derive(Debug, Serialize)]
261pub struct OperationResult {
262    pub target: String,
263    pub version: String,
264    pub results: Vec<VarBindResult>,
265    #[serde(skip_serializing_if = "Option::is_none")]
266    pub timing_ms: Option<f64>,
267    #[serde(skip_serializing_if = "Option::is_none")]
268    pub retries: Option<u32>,
269}
270
271/// A single varbind result.
272#[derive(Debug, Serialize)]
273pub struct VarBindResult {
274    pub oid: String,
275    #[serde(skip_serializing_if = "Option::is_none")]
276    pub hint: Option<String>,
277    #[serde(rename = "type")]
278    pub value_type: String,
279    pub value: serde_json::Value,
280    #[serde(skip_serializing_if = "Option::is_none")]
281    pub formatted: Option<String>,
282    #[serde(skip_serializing_if = "Option::is_none")]
283    pub raw_hex: Option<String>,
284}
285
286/// Output context for formatting.
287pub struct OutputContext {
288    pub format: OutputFormat,
289    pub show_hints: bool,
290    pub force_hex: bool,
291    pub show_timing: bool,
292}
293
294impl OutputContext {
295    /// Create a new output context with default settings.
296    pub fn new(format: OutputFormat) -> Self {
297        Self {
298            format,
299            show_hints: true,
300            force_hex: false,
301            show_timing: false,
302        }
303    }
304
305    /// Write operation results to stdout.
306    pub fn write_results(
307        &self,
308        target: SocketAddr,
309        version: Version,
310        varbinds: &[VarBind],
311        elapsed: Option<Duration>,
312        retries: Option<u32>,
313    ) -> io::Result<()> {
314        let result = self.build_result(target, version, varbinds, elapsed, retries);
315        let mut stdout = io::stdout().lock();
316
317        match self.format {
318            OutputFormat::Human => self.write_human(&mut stdout, &result),
319            OutputFormat::Json => self.write_json(&mut stdout, &result),
320            OutputFormat::Raw => self.write_raw(&mut stdout, &result),
321        }
322    }
323
324    fn build_result(
325        &self,
326        target: SocketAddr,
327        version: Version,
328        varbinds: &[VarBind],
329        elapsed: Option<Duration>,
330        retries: Option<u32>,
331    ) -> OperationResult {
332        let results = varbinds.iter().map(|vb| self.format_varbind(vb)).collect();
333
334        OperationResult {
335            target: target.to_string(),
336            version: format!("{:?}", version),
337            results,
338            timing_ms: elapsed.map(|d| d.as_secs_f64() * 1000.0),
339            retries,
340        }
341    }
342
343    fn format_varbind(&self, vb: &VarBind) -> VarBindResult {
344        let oid_str = format_oid(&vb.oid);
345        let hint = if self.show_hints {
346            hints::lookup(&vb.oid).map(String::from)
347        } else {
348            None
349        };
350
351        let (value_type, value, formatted, raw_hex) = format_value(&vb.value, self.force_hex);
352
353        VarBindResult {
354            oid: oid_str,
355            hint,
356            value_type,
357            value,
358            formatted,
359            raw_hex,
360        }
361    }
362
363    fn write_human<W: Write>(&self, w: &mut W, result: &OperationResult) -> io::Result<()> {
364        for vb in &result.results {
365            // OID with optional hint
366            if let Some(ref hint) = vb.hint {
367                write!(w, "{} ({})", vb.oid, hint)?;
368            } else {
369                write!(w, "{}", vb.oid)?;
370            }
371
372            // Type and value
373            write!(w, " = {}: ", vb.value_type)?;
374
375            // Value - prefer formatted for display
376            if let Some(ref formatted) = vb.formatted {
377                writeln!(w, "{}", formatted)?;
378            } else {
379                match &vb.value {
380                    serde_json::Value::String(s) => writeln!(w, "\"{}\"", s)?,
381                    serde_json::Value::Null => writeln!(w)?,
382                    other => writeln!(w, "{}", other)?,
383                }
384            }
385        }
386
387        if self.show_timing
388            && let Some(ms) = result.timing_ms
389        {
390            if let Some(retries) = result.retries {
391                writeln!(w, "\nTiming: {:.1}ms ({} retries)", ms, retries)?;
392            } else {
393                writeln!(w, "\nTiming: {:.1}ms", ms)?;
394            }
395        }
396
397        Ok(())
398    }
399
400    fn write_json<W: Write>(&self, w: &mut W, result: &OperationResult) -> io::Result<()> {
401        let json = serde_json::to_string_pretty(result).map_err(io::Error::other)?;
402        writeln!(w, "{}", json)
403    }
404
405    fn write_raw<W: Write>(&self, w: &mut W, result: &OperationResult) -> io::Result<()> {
406        for vb in &result.results {
407            let value_str = match &vb.value {
408                serde_json::Value::String(s) => s.clone(),
409                serde_json::Value::Null => String::new(),
410                other => other.to_string(),
411            };
412            writeln!(w, "{}\t{}", vb.oid, value_str)?;
413        }
414        Ok(())
415    }
416}
417
418/// Format an OID as dotted string.
419fn format_oid(oid: &Oid) -> String {
420    oid.arcs()
421        .iter()
422        .map(|a| a.to_string())
423        .collect::<Vec<_>>()
424        .join(".")
425}
426
427/// Format a value, returning (type_name, json_value, formatted_string, raw_hex).
428fn format_value(
429    value: &Value,
430    force_hex: bool,
431) -> (String, serde_json::Value, Option<String>, Option<String>) {
432    match value {
433        Value::Integer(v) => ("INTEGER".into(), (*v).into(), None, None),
434
435        Value::OctetString(bytes) => {
436            let raw_hex = Some(hex_string(bytes));
437
438            if force_hex || !is_printable(bytes) {
439                let formatted = format_hex_string(bytes);
440                (
441                    "Hex-STRING".into(),
442                    serde_json::Value::String(raw_hex.clone().unwrap()),
443                    Some(formatted),
444                    raw_hex,
445                )
446            } else {
447                let s = String::from_utf8_lossy(bytes);
448                (
449                    "STRING".into(),
450                    serde_json::Value::String(s.to_string()),
451                    None,
452                    raw_hex,
453                )
454            }
455        }
456
457        Value::Null => ("NULL".into(), serde_json::Value::Null, None, None),
458
459        Value::ObjectIdentifier(oid) => {
460            let s = format_oid(oid);
461            ("OID".into(), serde_json::Value::String(s), None, None)
462        }
463
464        Value::IpAddress(bytes) => {
465            let s = format!("{}.{}.{}.{}", bytes[0], bytes[1], bytes[2], bytes[3]);
466            ("IpAddress".into(), serde_json::Value::String(s), None, None)
467        }
468
469        Value::Counter32(v) => ("Counter32".into(), (*v).into(), None, None),
470
471        Value::Gauge32(v) => ("Gauge32".into(), (*v).into(), None, None),
472
473        Value::TimeTicks(v) => {
474            let formatted = format_timeticks(*v);
475            (
476                "TimeTicks".into(),
477                (*v).into(),
478                Some(format!("({}) {}", v, formatted)),
479                None,
480            )
481        }
482
483        Value::Opaque(bytes) => {
484            let hex = hex_string(bytes);
485            (
486                "Opaque".into(),
487                serde_json::Value::String(hex.clone()),
488                Some(format_hex_string(bytes)),
489                Some(hex),
490            )
491        }
492
493        Value::Counter64(v) => ("Counter64".into(), (*v).into(), None, None),
494
495        Value::NoSuchObject => (
496            "NoSuchObject".into(),
497            serde_json::Value::Null,
498            Some("No Such Object available".into()),
499            None,
500        ),
501
502        Value::NoSuchInstance => (
503            "NoSuchInstance".into(),
504            serde_json::Value::Null,
505            Some("No Such Instance currently exists".into()),
506            None,
507        ),
508
509        Value::EndOfMibView => (
510            "EndOfMibView".into(),
511            serde_json::Value::Null,
512            Some("No more variables left in this MIB View".into()),
513            None,
514        ),
515
516        Value::Unknown { tag, data } => {
517            let hex = hex_string(data);
518            (
519                format!("Unknown(0x{:02X})", tag),
520                serde_json::Value::String(hex.clone()),
521                Some(format_hex_string(data)),
522                Some(hex),
523            )
524        }
525    }
526}
527
528/// Check if bytes are printable ASCII/UTF-8.
529fn is_printable(bytes: &[u8]) -> bool {
530    if bytes.is_empty() {
531        return true;
532    }
533
534    // Try UTF-8 first
535    if let Ok(s) = std::str::from_utf8(bytes) {
536        // Check that all characters are printable
537        s.chars()
538            .all(|c| c.is_ascii_graphic() || c.is_ascii_whitespace())
539    } else {
540        false
541    }
542}
543
544/// Format bytes as hex string (lowercase, no separator).
545fn hex_string(bytes: &[u8]) -> String {
546    bytes.iter().map(|b| format!("{:02x}", b)).collect()
547}
548
549/// Format bytes as spaced hex for display.
550fn format_hex_string(bytes: &[u8]) -> String {
551    bytes
552        .iter()
553        .map(|b| format!("{:02X}", b))
554        .collect::<Vec<_>>()
555        .join(" ")
556}
557
558/// Format TimeTicks as human-readable duration.
559fn format_timeticks(centiseconds: u32) -> String {
560    let total_seconds = centiseconds / 100;
561    let cs = centiseconds % 100;
562
563    let days = total_seconds / 86400;
564    let hours = (total_seconds % 86400) / 3600;
565    let minutes = (total_seconds % 3600) / 60;
566    let seconds = total_seconds % 60;
567
568    if days > 0 {
569        format!(
570            "{}d {:02}:{:02}:{:02}.{:02}",
571            days, hours, minutes, seconds, cs
572        )
573    } else {
574        format!("{:02}:{:02}:{:02}.{:02}", hours, minutes, seconds, cs)
575    }
576}
577
578/// Write an error message to stderr.
579pub fn write_error(err: &crate::Error) {
580    eprintln!("Error: {}", err);
581}
582
583#[cfg(test)]
584mod tests {
585    use super::*;
586
587    #[test]
588    fn test_format_timeticks() {
589        // 1 day, 10 hours, 17 minutes, 36.78 seconds = 123456.78 seconds = 12345678 centiseconds
590        assert_eq!(format_timeticks(12345678), "1d 10:17:36.78");
591
592        // Less than a day
593        assert_eq!(format_timeticks(360000), "01:00:00.00");
594
595        // Zero
596        assert_eq!(format_timeticks(0), "00:00:00.00");
597    }
598
599    #[test]
600    fn test_is_printable() {
601        assert!(is_printable(b"Hello World"));
602        assert!(is_printable(b"Line 1\nLine 2"));
603        assert!(is_printable(b""));
604        assert!(!is_printable(&[0x00, 0x01, 0x02]));
605        assert!(!is_printable(&[0x80, 0x81]));
606    }
607
608    #[test]
609    fn test_hex_string() {
610        assert_eq!(hex_string(&[0x00, 0x1A, 0x2B]), "001a2b");
611    }
612
613    #[test]
614    fn test_format_hex_string() {
615        assert_eq!(format_hex_string(&[0x00, 0x1A, 0x2B]), "00 1A 2B");
616    }
617}