async-snmp 0.12.0

Modern async-first SNMP client library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Variable binding (VarBind) type.
//!
//! A VarBind pairs an OID with a value.

use crate::ber::{Decoder, EncodeBuf};
use crate::error::Result;
use crate::oid::Oid;
use crate::value::Value;

/// Variable binding - an OID-value pair.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VarBind {
    /// The object identifier.
    pub oid: Oid,
    /// The value.
    pub value: Value,
}

impl VarBind {
    /// Create a new VarBind.
    pub fn new(oid: Oid, value: Value) -> Self {
        Self { oid, value }
    }

    /// Create a VarBind with a NULL value (for GET requests).
    pub fn null(oid: Oid) -> Self {
        Self {
            oid,
            value: Value::Null,
        }
    }

    /// Encode to BER.
    pub fn encode(&self, buf: &mut EncodeBuf) {
        buf.push_sequence(|buf| {
            self.value.encode(buf);
            buf.push_oid(&self.oid);
        });
    }

    /// Returns the exact encoded size of this VarBind in bytes.
    ///
    /// Computes the size arithmetically without allocating.
    /// Useful for response size estimation in GETBULK processing.
    pub fn encoded_size(&self) -> usize {
        use crate::ber::length_encoded_len;

        // VarBind is SEQUENCE { oid, value }
        let oid_len = self.oid.ber_encoded_size();
        let value_len = self.value.ber_encoded_size();
        let content_len = oid_len + value_len;

        // SEQUENCE tag (1) + length encoding + content
        1 + length_encoded_len(content_len) + content_len
    }

    /// Decode from BER.
    pub fn decode(decoder: &mut Decoder) -> Result<Self> {
        let mut seq = decoder.read_sequence()?;
        let oid = seq.read_oid()?;
        let value = Value::decode(&mut seq)?;
        Ok(VarBind { oid, value })
    }
}

impl std::fmt::Display for VarBind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} = {}", self.oid, self.value)
    }
}

/// Encodes a list of VarBinds to BER format.
///
/// Writes the VarBinds as a SEQUENCE of SEQUENCE elements, where each inner
/// SEQUENCE contains an OID and its associated value.
pub fn encode_varbind_list(buf: &mut EncodeBuf, varbinds: &[VarBind]) {
    buf.push_sequence(|buf| {
        // Encode in reverse order since we're using reverse buffer
        for vb in varbinds.iter().rev() {
            vb.encode(buf);
        }
    });
}

/// Decodes a BER-encoded VarBind list into a vector of VarBinds.
///
/// Expects a SEQUENCE containing zero or more VarBind SEQUENCE elements.
pub fn decode_varbind_list(decoder: &mut Decoder) -> Result<Vec<VarBind>> {
    let mut seq = decoder.read_sequence()?;

    // Estimate capacity: typical VarBind is 20-50 bytes, use 16 as conservative divisor
    // to minimize reallocations while not over-allocating
    let estimated_capacity = (seq.remaining() / 16).max(1);
    let mut varbinds = Vec::with_capacity(estimated_capacity);

    while !seq.is_empty() {
        varbinds.push(VarBind::decode(&mut seq)?);
    }

    Ok(varbinds)
}

/// Encodes OIDs with NULL values for GET requests.
///
/// Creates a VarBind list where each OID is paired with a NULL value,
/// as required by SNMP GET, GETNEXT, and GETBULK request PDUs.
pub fn encode_null_varbinds(buf: &mut EncodeBuf, oids: &[Oid]) {
    buf.push_sequence(|buf| {
        for oid in oids.iter().rev() {
            buf.push_sequence(|buf| {
                buf.push_null();
                buf.push_oid(oid);
            });
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::oid;
    use bytes::Bytes;

    #[test]
    fn test_varbind_roundtrip() {
        let vb = VarBind::new(oid!(1, 3, 6, 1), Value::Integer(42));

        let mut buf = EncodeBuf::new();
        vb.encode(&mut buf);
        let bytes = buf.finish();

        let mut decoder = Decoder::new(bytes);
        let decoded = VarBind::decode(&mut decoder).unwrap();

        assert_eq!(vb, decoded);
    }

    #[test]
    fn test_varbind_list_roundtrip() {
        let varbinds = vec![
            VarBind::new(oid!(1, 3, 6, 1), Value::Integer(1)),
            VarBind::new(oid!(1, 3, 6, 2), Value::Integer(2)),
        ];

        let mut buf = EncodeBuf::new();
        encode_varbind_list(&mut buf, &varbinds);
        let bytes = buf.finish();

        let mut decoder = Decoder::new(bytes);
        let decoded = decode_varbind_list(&mut decoder).unwrap();

        assert_eq!(varbinds, decoded);
    }

    // ========================================================================
    // Exception Value VarBind Tests
    // ========================================================================

    #[test]
    fn test_varbind_no_such_object() {
        let vb = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), Value::NoSuchObject);

        let mut buf = EncodeBuf::new();
        vb.encode(&mut buf);
        let bytes = buf.finish();

        let mut decoder = Decoder::new(bytes);
        let decoded = VarBind::decode(&mut decoder).unwrap();

        assert_eq!(vb, decoded);
        assert!(decoded.value.is_exception());
    }

    #[test]
    fn test_varbind_no_such_instance() {
        let vb = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), Value::NoSuchInstance);

        let mut buf = EncodeBuf::new();
        vb.encode(&mut buf);
        let bytes = buf.finish();

        let mut decoder = Decoder::new(bytes);
        let decoded = VarBind::decode(&mut decoder).unwrap();

        assert_eq!(vb, decoded);
        assert!(decoded.value.is_exception());
    }

    #[test]
    fn test_varbind_end_of_mib_view() {
        let vb = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), Value::EndOfMibView);

        let mut buf = EncodeBuf::new();
        vb.encode(&mut buf);
        let bytes = buf.finish();

        let mut decoder = Decoder::new(bytes);
        let decoded = VarBind::decode(&mut decoder).unwrap();

        assert_eq!(vb, decoded);
        assert!(decoded.value.is_exception());
    }

    #[test]
    fn test_varbind_zero_length_oid_end_of_mib_view() {
        // Some devices send endOfMibView with a zero-length OID instead of echoing
        // back the requested OID (RFC 3416 violation). net-snmp accepts this by
        // treating 06 00 as OID 0.0; we accept it by returning an empty OID.
        // The bytes are: 30 04 06 00 82 00
        //   30 04  - SEQUENCE length 4
        //   06 00  - OID tag, zero-length content (malformed)
        //   82 00  - endOfMibView, length 0
        let bytes = bytes::Bytes::from_static(&[0x30, 0x04, 0x06, 0x00, 0x82, 0x00]);
        let mut decoder = Decoder::new(bytes);
        let vb = VarBind::decode(&mut decoder).unwrap();
        assert!(vb.oid.is_empty());
        assert_eq!(vb.value, Value::EndOfMibView);
    }

    #[test]
    fn test_varbind_octetstring_length_exceeds_sequence() {
        // MikroTik firmware bug: OctetString value declares a length 1 byte
        // larger than what fits in the enclosing varbind SEQUENCE. We clamp to
        // the available bytes rather than rejecting the varbind.
        //
        // Packet: 30 0e 06 08 2b 06 01 02 01 01 01 00 04 03 61 62
        //   30 0e  - varbind SEQUENCE, length 14
        //   06 08  - OID tag, length 8
        //   2b 06 01 02 01 01 01 00  - OID content (1.3.6.1.2.1.1.1.0)
        //   04 03  - OctetString tag, declared length 3 (WRONG - only 2 bytes remain)
        //   61 62  - 2 bytes of actual data ("ab")
        let bytes = bytes::Bytes::from_static(&[
            0x30, 0x0e, // SEQUENCE length 14
            0x06, 0x08, 0x2b, 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00, // OID
            0x04, 0x03, 0x61, 0x62, // OctetString: declares 3, has 2
        ]);
        let mut decoder = Decoder::new(bytes);
        let vb = VarBind::decode(&mut decoder).unwrap();
        assert_eq!(vb.oid, crate::oid!(1, 3, 6, 1, 2, 1, 1, 1, 0));
        assert_eq!(
            vb.value,
            Value::OctetString(bytes::Bytes::from_static(b"ab"))
        );
    }

    // ========================================================================
    // VarBind List Edge Cases
    // ========================================================================

    #[test]
    fn test_varbind_list_empty() {
        let varbinds: Vec<VarBind> = vec![];

        let mut buf = EncodeBuf::new();
        encode_varbind_list(&mut buf, &varbinds);
        let bytes = buf.finish();

        let mut decoder = Decoder::new(bytes);
        let decoded = decode_varbind_list(&mut decoder).unwrap();

        assert!(decoded.is_empty());
    }

    #[test]
    fn test_varbind_list_single() {
        let varbinds = vec![VarBind::new(oid!(1, 3, 6, 1), Value::Integer(42))];

        let mut buf = EncodeBuf::new();
        encode_varbind_list(&mut buf, &varbinds);
        let bytes = buf.finish();

        let mut decoder = Decoder::new(bytes);
        let decoded = decode_varbind_list(&mut decoder).unwrap();

        assert_eq!(varbinds, decoded);
    }

    #[test]
    fn test_varbind_list_with_exceptions() {
        let varbinds = vec![
            VarBind::new(
                oid!(1, 3, 6, 1, 2, 1, 1, 1, 0),
                Value::OctetString(Bytes::from_static(b"Linux router")),
            ),
            VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 99, 0), Value::NoSuchObject),
            VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 3, 0), Value::TimeTicks(123456)),
            VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 100, 0), Value::NoSuchInstance),
        ];

        let mut buf = EncodeBuf::new();
        encode_varbind_list(&mut buf, &varbinds);
        let bytes = buf.finish();

        let mut decoder = Decoder::new(bytes);
        let decoded = decode_varbind_list(&mut decoder).unwrap();

        assert_eq!(varbinds, decoded);
        assert!(!decoded[0].value.is_exception());
        assert!(decoded[1].value.is_exception());
        assert!(!decoded[2].value.is_exception());
        assert!(decoded[3].value.is_exception());
    }

    #[test]
    fn test_varbind_list_all_exceptions() {
        let varbinds = vec![
            VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), Value::NoSuchObject),
            VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 2, 0), Value::NoSuchInstance),
            VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 3, 0), Value::EndOfMibView),
        ];

        let mut buf = EncodeBuf::new();
        encode_varbind_list(&mut buf, &varbinds);
        let bytes = buf.finish();

        let mut decoder = Decoder::new(bytes);
        let decoded = decode_varbind_list(&mut decoder).unwrap();

        assert_eq!(varbinds, decoded);
        assert!(decoded.iter().all(|vb| vb.value.is_exception()));
    }

    #[test]
    fn test_varbind_list_mixed_value_types() {
        let varbinds = vec![
            VarBind::new(
                oid!(1, 3, 6, 1, 2, 1, 1, 1, 0),
                Value::OctetString(Bytes::from_static(b"test")),
            ),
            VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 2, 0), Value::Integer(42)),
            VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 3, 0), Value::Counter32(1000)),
            VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 4, 0), Value::Gauge32(500)),
            VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 5, 0), Value::TimeTicks(99999)),
            VarBind::new(
                oid!(1, 3, 6, 1, 2, 1, 1, 6, 0),
                Value::IpAddress([192, 168, 1, 1]),
            ),
            VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 7, 0), Value::Counter64(u64::MAX)),
            VarBind::new(
                oid!(1, 3, 6, 1, 2, 1, 1, 8, 0),
                Value::ObjectIdentifier(oid!(1, 3, 6, 1, 4)),
            ),
            VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 9, 0), Value::Null),
        ];

        let mut buf = EncodeBuf::new();
        encode_varbind_list(&mut buf, &varbinds);
        let bytes = buf.finish();

        let mut decoder = Decoder::new(bytes);
        let decoded = decode_varbind_list(&mut decoder).unwrap();

        assert_eq!(varbinds, decoded);
    }

    #[test]
    fn test_null_varbinds_encoding() {
        let oids = vec![
            oid!(1, 3, 6, 1, 2, 1, 1, 1, 0),
            oid!(1, 3, 6, 1, 2, 1, 1, 3, 0),
            oid!(1, 3, 6, 1, 2, 1, 1, 5, 0),
        ];

        let mut buf = EncodeBuf::new();
        encode_null_varbinds(&mut buf, &oids);
        let bytes = buf.finish();

        let mut decoder = Decoder::new(bytes);
        let decoded = decode_varbind_list(&mut decoder).unwrap();

        assert_eq!(decoded.len(), 3);
        for (i, vb) in decoded.iter().enumerate() {
            assert_eq!(vb.oid, oids[i]);
            assert_eq!(vb.value, Value::Null);
        }
    }

    #[test]
    fn test_null_varbinds_empty() {
        let oids: Vec<Oid> = vec![];

        let mut buf = EncodeBuf::new();
        encode_null_varbinds(&mut buf, &oids);
        let bytes = buf.finish();

        let mut decoder = Decoder::new(bytes);
        let decoded = decode_varbind_list(&mut decoder).unwrap();

        assert!(decoded.is_empty());
    }

    // ========================================================================
    // VarBind Display Tests
    // ========================================================================

    #[test]
    fn test_varbind_display() {
        let vb = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), Value::Integer(42));
        let display = format!("{}", vb);
        assert!(display.contains("1.3.6.1.2.1.1.1.0"));
        assert!(display.contains("42"));
    }

    #[test]
    fn test_varbind_display_exception() {
        let vb = VarBind::new(oid!(1, 3, 6, 1), Value::NoSuchObject);
        let display = format!("{}", vb);
        assert!(display.contains("noSuchObject"));
    }

    // ========================================================================
    // VarBind::null() Constructor Test
    // ========================================================================

    #[test]
    fn test_varbind_null_constructor() {
        let vb = VarBind::null(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0));
        assert_eq!(vb.oid, oid!(1, 3, 6, 1, 2, 1, 1, 1, 0));
        assert_eq!(vb.value, Value::Null);
    }

    // ========================================================================
    // VarBind::encoded_size() Tests
    // ========================================================================

    /// Helper to verify encoded_size() matches actual encoding length
    fn verify_encoded_size(vb: &VarBind) {
        let mut buf = EncodeBuf::new();
        vb.encode(&mut buf);
        let actual = buf.len();
        let computed = vb.encoded_size();
        assert_eq!(
            computed, actual,
            "encoded_size mismatch for {:?}: computed={}, actual={}",
            vb, computed, actual
        );
    }

    #[test]
    fn test_encoded_size_null() {
        verify_encoded_size(&VarBind::null(oid!(1, 3, 6, 1)));
        verify_encoded_size(&VarBind::null(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)));
    }

    #[test]
    fn test_encoded_size_integer() {
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::Integer(0)));
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::Integer(127)));
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::Integer(128)));
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::Integer(-1)));
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::Integer(i32::MAX)));
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::Integer(i32::MIN)));
    }

    #[test]
    fn test_encoded_size_octet_string() {
        verify_encoded_size(&VarBind::new(
            oid!(1, 3, 6, 1),
            Value::OctetString(Bytes::new()),
        ));
        verify_encoded_size(&VarBind::new(
            oid!(1, 3, 6, 1),
            Value::OctetString(Bytes::from_static(b"hello world")),
        ));
        // Large string
        verify_encoded_size(&VarBind::new(
            oid!(1, 3, 6, 1),
            Value::OctetString(Bytes::from(vec![0u8; 200])),
        ));
    }

    #[test]
    fn test_encoded_size_counters() {
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::Counter32(0)));
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::Counter32(u32::MAX)));
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::Gauge32(12345)));
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::TimeTicks(99999)));
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::Counter64(0)));
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::Counter64(u64::MAX)));
    }

    #[test]
    fn test_encoded_size_oid_value() {
        verify_encoded_size(&VarBind::new(
            oid!(1, 3, 6, 1, 2, 1, 1, 2, 0),
            Value::ObjectIdentifier(oid!(1, 3, 6, 1, 4, 1, 9999)),
        ));
    }

    #[test]
    fn test_encoded_size_exceptions() {
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::NoSuchObject));
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::NoSuchInstance));
        verify_encoded_size(&VarBind::new(oid!(1, 3, 6, 1), Value::EndOfMibView));
    }

    #[test]
    fn test_encoded_size_ip_address() {
        verify_encoded_size(&VarBind::new(
            oid!(1, 3, 6, 1),
            Value::IpAddress([192, 168, 1, 1]),
        ));
    }

    mod proptests {
        use super::*;
        use crate::oid::Oid;
        use proptest::prelude::*;

        fn arb_oid() -> impl Strategy<Value = Oid> {
            // Generate valid OIDs: first arc 0-2, second arc 0-39 (for arc1 < 2) or 0-999
            (0u32..3, 0u32..40, prop::collection::vec(0u32..10000, 0..8)).prop_map(
                |(arc1, arc2, rest)| {
                    let mut arcs = vec![arc1, arc2];
                    arcs.extend(rest);
                    Oid::from_slice(&arcs)
                },
            )
        }

        fn arb_value() -> impl Strategy<Value = Value> {
            prop_oneof![
                any::<i32>().prop_map(Value::Integer),
                prop::collection::vec(any::<u8>(), 0..256)
                    .prop_map(|v| Value::OctetString(Bytes::from(v))),
                Just(Value::Null),
                arb_oid().prop_map(Value::ObjectIdentifier),
                any::<[u8; 4]>().prop_map(Value::IpAddress),
                any::<u32>().prop_map(Value::Counter32),
                any::<u32>().prop_map(Value::Gauge32),
                any::<u32>().prop_map(Value::TimeTicks),
                any::<u64>().prop_map(Value::Counter64),
                Just(Value::NoSuchObject),
                Just(Value::NoSuchInstance),
                Just(Value::EndOfMibView),
                (any::<u8>(), prop::collection::vec(any::<u8>(), 0..256)).prop_map(
                    |(tag, data)| Value::Unknown {
                        tag,
                        data: Bytes::from(data),
                    }
                ),
            ]
        }

        proptest! {
            #[test]
            fn encoded_size_matches_encoding(
                oid in arb_oid(),
                value in arb_value()
            ) {
                let vb = VarBind::new(oid, value);
                let mut buf = EncodeBuf::new();
                vb.encode(&mut buf);
                prop_assert_eq!(
                    vb.encoded_size(),
                    buf.len(),
                    "encoded_size mismatch: computed={}, actual={}",
                    vb.encoded_size(),
                    buf.len()
                );
            }
        }
    }
}