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
//! Transport layer abstraction for SNMP communication.
//!
//! This module provides the [`Transport`] trait and implementations:
//!
//! - [`UdpTransport`] + [`UdpHandle`] - UDP socket with per-target handles
//! - [`TcpTransport`] - TCP stream with BER framing
//!
//! # Choosing a Transport
//!
//! | Scenario | Approach |
//! |----------|---------|
//! | Single target or few targets | [`Client::builder().connect()`](crate::Client::builder) - each client gets its own socket |
//! | Many targets from one process | Share a [`UdpTransport`] via [`build_with()`](crate::ClientBuilder::build_with) - one socket, one recv loop |
//! | UDP blocked or messages exceed MTU | [`Client::builder().connect_tcp()`](crate::ClientBuilder::connect_tcp) |

mod tcp;
mod udp;
mod udp_core;

pub use tcp::*;
pub use udp::*;

use crate::ber::length::parse_ber_length;
use crate::error::Result;
use bytes::Bytes;
use std::future::Future;
use std::net::SocketAddr;
use std::sync::LazyLock;
use std::sync::atomic::{AtomicI32, Ordering};
use std::time::Duration;

/// Maximum UDP datagram payload size.
///
/// This is 65535 (max IP packet) minus 20 (IPv4 header) minus 8 (UDP header).
/// Used as the default value for [`Transport::max_message_size()`].
pub const MAX_UDP_PAYLOAD: u32 = 65507;

/// Global request ID counter, initialized with a cryptographically random seed.
///
/// Using a global counter ensures request IDs are unique across all
/// transports within the process, preventing collisions when multiple
/// transports exist or when sockets are rapidly recreated.
static REQUEST_ID_COUNTER: LazyLock<AtomicI32> = LazyLock::new(|| {
    let mut buf = [0u8; 4];
    getrandom::fill(&mut buf).expect("getrandom failed");
    let seed = i32::from_ne_bytes(buf);
    AtomicI32::new(seed)
});

/// Allocate a globally unique request ID.
///
/// Returns a positive non-zero i32 (range 1..=2147483647) that is unique
/// within this process. Per RFC 1157/3412, request-id/msgID is defined as
/// INTEGER (0..2147483647), and some implementations may not handle negative
/// values correctly.
///
/// The counter is seeded with random bytes to minimize collision risk across
/// process restarts.
pub fn alloc_request_id() -> i32 {
    loop {
        let id = REQUEST_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
        let id = id & 0x7FFFFFFF;
        if id != 0 {
            return id;
        }
    }
}

/// Client-side transport abstraction.
///
/// All transports implement this trait uniformly. For shared transports,
/// handles (not the pool itself) implement Transport.
pub trait Transport: Send + Sync {
    /// Send request data to the target.
    fn send(&self, data: &[u8]) -> impl Future<Output = Result<()>> + Send;

    /// Wait for response. Uses deadline set by `register_request()`.
    ///
    /// For UDP transports, the deadline was stored during registration.
    /// For TCP transports, uses the timeout parameter.
    fn recv(&self, request_id: i32) -> impl Future<Output = Result<(Bytes, SocketAddr)>> + Send;

    /// The peer address for this transport.
    fn peer_addr(&self) -> SocketAddr;

    /// Local bind address.
    fn local_addr(&self) -> SocketAddr;

    /// Allocate the next request ID.
    ///
    /// Default uses the global allocator for process-wide uniqueness.
    fn alloc_request_id(&self) -> i32 {
        alloc_request_id()
    }

    /// Whether this is a reliable transport (TCP/TLS).
    ///
    /// When true, Client skips retries (transport guarantees delivery or failure).
    /// When false (UDP/DTLS), Client retries on timeout.
    fn is_reliable(&self) -> bool;

    /// Pre-register a request with timeout before sending.
    ///
    /// UDP transports use this to create the response slot with deadline.
    /// TCP transports ignore this (default no-op).
    fn register_request(&self, _request_id: i32, _timeout: Duration) {
        // Default: no-op for TCP and other transports that don't need pre-registration
    }

    /// Maximum message size this transport can handle.
    ///
    /// Used to cap agent-reported msgMaxSize values. Default is the maximum
    /// UDP datagram payload ([`MAX_UDP_PAYLOAD`]).
    fn max_message_size(&self) -> u32 {
        MAX_UDP_PAYLOAD
    }
}

/// Agent-side transport abstraction (listener mode).
///
/// This trait is for future agent functionality.
pub trait AgentTransport: Send + Sync {
    /// Receive data from any source.
    fn recv_from(&self, buf: &mut [u8])
    -> impl Future<Output = Result<(usize, SocketAddr)>> + Send;

    /// Send data to a specific target.
    fn send_to(&self, data: &[u8], target: SocketAddr) -> impl Future<Output = Result<()>> + Send;

    /// Local bind address.
    fn local_addr(&self) -> SocketAddr;
}

// ============================================================================
// Request ID Extraction (shared between transports)
// ============================================================================

/// Extract request_id (or msgID for V3) from an SNMP response.
///
/// SNMP message structure differs by version:
///
/// V1/V2c:
/// - SEQUENCE { INTEGER version, OCTET STRING community, PDU }
/// - PDU contains request_id as first INTEGER
///
/// V3:
/// - SEQUENCE { INTEGER version(3), SEQUENCE msgGlobalData { INTEGER msgID, ... }, ... }
/// - msgID in msgGlobalData is used for correlation
///
/// We need to navigate through BER encoding to find the appropriate ID.
pub(crate) fn extract_request_id(data: &[u8]) -> Option<i32> {
    let mut pos = 0;

    // Outer SEQUENCE
    if pos >= data.len() || data[pos] != 0x30 {
        return None;
    }
    pos += 1;

    // Skip outer SEQUENCE length
    let (_, consumed) = parse_ber_length(&data[pos..])?;
    pos += consumed;

    // Version (INTEGER)
    if pos >= data.len() || data[pos] != 0x02 {
        return None;
    }
    pos += 1;
    let (version_len, consumed) = parse_ber_length(&data[pos..])?;
    pos += consumed;

    // Read version value
    if pos + version_len > data.len() {
        return None;
    }
    let version = if version_len == 1 {
        data[pos] as i32
    } else {
        // Multi-byte version (unusual but handle it)
        let mut v: i32 = 0;
        for i in 0..version_len {
            v = (v << 8) | (data[pos + i] as i32);
        }
        v
    };
    pos += version_len;

    // Check what comes next to determine V1/V2c vs V3
    if pos >= data.len() {
        return None;
    }

    let next_tag = data[pos];

    if version == 3 && next_tag == 0x30 {
        // V3: Next is msgGlobalData SEQUENCE, extract msgID from it
        extract_v3_msg_id(data, pos)
    } else if next_tag == 0x04 {
        // V1/V2c: Next is community OCTET STRING
        extract_v1v2c_request_id(data, pos)
    } else {
        None
    }
}

/// Extract msgID from V3 message starting at msgGlobalData position.
fn extract_v3_msg_id(data: &[u8], mut pos: usize) -> Option<i32> {
    // msgGlobalData SEQUENCE
    if pos >= data.len() || data[pos] != 0x30 {
        return None;
    }
    pos += 1;

    // Skip msgGlobalData SEQUENCE length
    let (_, consumed) = parse_ber_length(&data[pos..])?;
    pos += consumed;

    // First INTEGER inside msgGlobalData is msgID
    if pos >= data.len() || data[pos] != 0x02 {
        return None;
    }
    pos += 1;

    // Read msgID length
    let (id_len, consumed) = parse_ber_length(&data[pos..])?;
    pos += consumed;

    if pos + id_len > data.len() {
        return None;
    }

    // Decode msgID (signed integer, big-endian)
    decode_ber_signed_integer(&data[pos..pos + id_len])
}

/// Extract request_id from V1/V2c message starting at community position.
fn extract_v1v2c_request_id(data: &[u8], mut pos: usize) -> Option<i32> {
    // Community (OCTET STRING)
    if pos >= data.len() || data[pos] != 0x04 {
        return None;
    }
    pos += 1;
    let (community_len, consumed) = parse_ber_length(&data[pos..])?;
    pos += consumed + community_len;

    // PDU (context-specific, e.g., 0xA2 for Response)
    if pos >= data.len() {
        return None;
    }
    let pdu_tag = data[pos];
    // PDU tags are 0xA0-0xA8
    if !(0xA0..=0xA8).contains(&pdu_tag) {
        return None;
    }
    pos += 1;

    // Skip PDU length
    let (_, consumed) = parse_ber_length(&data[pos..])?;
    pos += consumed;

    // Request ID (INTEGER)
    if pos >= data.len() || data[pos] != 0x02 {
        return None;
    }
    pos += 1;

    // Read request_id length
    let (id_len, consumed) = parse_ber_length(&data[pos..])?;
    pos += consumed;

    if pos + id_len > data.len() {
        return None;
    }

    // Decode request_id (signed integer, big-endian)
    decode_ber_signed_integer(&data[pos..pos + id_len])
}

/// Decode a BER-encoded signed integer.
fn decode_ber_signed_integer(bytes: &[u8]) -> Option<i32> {
    if bytes.is_empty() {
        return Some(0);
    }

    // Sign extend for negative numbers
    let mut value: i32 = if bytes[0] & 0x80 != 0 { -1 } else { 0 };

    for &byte in bytes {
        value = (value << 8) | (byte as i32);
    }

    Some(value)
}

#[cfg(test)]
mod request_id_tests {
    use super::*;
    use std::sync::atomic::AtomicI32;

    /// RFC 1157 and RFC 3412 define request-id/msgID as INTEGER (0..2147483647).
    #[test]
    fn request_id_is_always_positive() {
        for _ in 0..10_000 {
            let id = alloc_request_id();
            assert!(id > 0, "request ID must be positive, got {}", id);
        }
    }

    /// Some SNMP implementations treat request-id 0 specially or reject it.
    #[test]
    fn request_id_zero_is_skipped() {
        for _ in 0..10_000 {
            let id = alloc_request_id();
            assert_ne!(id, 0, "request ID must not be zero");
        }
    }

    /// Validates wrap-around: counter going from i32::MAX to negative must
    /// still produce positive values via 31-bit masking (RFC 3412 range).
    #[test]
    fn request_id_wrap_around_stays_positive() {
        let counter = AtomicI32::new(i32::MAX - 100);

        let alloc_test_id = || -> i32 {
            loop {
                let id = counter.fetch_add(1, Ordering::Relaxed);
                let id = id & 0x7FFFFFFF;
                if id != 0 {
                    return id;
                }
            }
        };

        for i in 0..200 {
            let id = alloc_test_id();
            assert!(
                id > 0,
                "request ID must be positive after wrap, iteration {}, got {}",
                i,
                id
            );
        }
    }

    #[test]
    fn request_ids_are_unique() {
        use std::collections::HashSet;

        let mut seen = HashSet::new();
        for _ in 0..10_000 {
            let id = alloc_request_id();
            assert!(seen.insert(id), "request ID {} was allocated twice", id);
        }
    }
}

#[cfg(test)]
mod extract_tests {
    use super::*;

    #[test]
    fn test_extract_request_id_v2c() {
        // A minimal SNMP v2c GET response with request_id = 12345
        let response = [
            0x30, 0x1c, // SEQUENCE
            0x02, 0x01, 0x01, // INTEGER 1 (v2c)
            0x04, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, // "public"
            0xa2, 0x0f, // Response PDU
            0x02, 0x02, 0x30, 0x39, // INTEGER 12345
            0x02, 0x01, 0x00, // error-status
            0x02, 0x01, 0x00, // error-index
            0x30, 0x03, 0x30, 0x01, 0x00, // varbinds
        ];

        assert_eq!(extract_request_id(&response), Some(12345));
    }

    #[test]
    fn test_extract_request_id_v3() {
        // A minimal SNMPv3 Response message with msgID = 12345
        let v3_response = [
            0x30, 0x35, // SEQUENCE
            0x02, 0x01, 0x03, // version = 3
            0x30, 0x11, // msgGlobalData SEQUENCE
            0x02, 0x02, 0x30, 0x39, // INTEGER 12345 (msgID)
            0x02, 0x03, 0x00, 0xff, 0xe3, // INTEGER 65507 (msgMaxSize)
            0x04, 0x01, 0x04, // OCTET STRING (msgFlags)
            0x02, 0x01, 0x03, // INTEGER 3 (msgSecurityModel)
            0x04, 0x00, // msgSecurityParameters
            0x30, 0x1b, // ScopedPDU SEQUENCE
            0x04, 0x00, // contextEngineID
            0x04, 0x00, // contextName
            0xa2, 0x15, // ResponsePDU
            0x02, 0x02, 0x30, 0x39, // request_id
            0x02, 0x01, 0x00, // error-status
            0x02, 0x01, 0x00, // error-index
            0x30, 0x09, // varbinds
            0x30, 0x07, // varbind
            0x06, 0x03, 0x2b, 0x06, 0x01, // OID
            0x05, 0x00, // NULL
        ];

        assert_eq!(extract_request_id(&v3_response), Some(12345));
    }

    #[test]
    fn test_extract_request_id_v1() {
        // A minimal SNMPv1 GET response with request_id = 42
        let v1_response = [
            0x30, 0x1b, // SEQUENCE
            0x02, 0x01, 0x00, // INTEGER 0 (v1)
            0x04, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, // "public"
            0xa2, 0x0e, // Response PDU
            0x02, 0x01, 0x2a, // INTEGER 42 (request_id)
            0x02, 0x01, 0x00, // error-status
            0x02, 0x01, 0x00, // error-index
            0x30, 0x03, 0x30, 0x01, 0x00, // varbinds
        ];

        assert_eq!(extract_request_id(&v1_response), Some(42));
    }

    #[test]
    fn test_extract_request_id_negative() {
        // Request ID = -1
        let response = [
            0x30, 0x19, 0x02, 0x01, 0x01, 0x04, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0xa2,
            0x0c, 0x02, 0x01, 0xff, // INTEGER -1
            0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x30, 0x00,
        ];

        assert_eq!(extract_request_id(&response), Some(-1));
    }

    #[test]
    fn test_extract_request_id_malformed() {
        assert_eq!(extract_request_id(&[]), None);
        assert_eq!(extract_request_id(&[0x02, 0x01, 0x00]), None);
        assert_eq!(extract_request_id(&[0x30, 0x10]), None);
    }
}