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
//! # async-snmp
//!
//! Modern, async-first SNMP client library for Rust.
//!
//! ## Features
//!
//! - Full SNMPv1, v2c, and v3 support
//! - Async-first API built on Tokio
//! - Zero-copy BER encoding/decoding
//! - Type-safe OID and value handling
//! - Config-driven client construction
//! - Trap and inform sending (agent-based multi-sink or client-based)
//! - SNMP agent with async handlers, two-phase SET, VACM, and built-in MIB handlers
//! - Automatic tooBig recovery (GET/GETNEXT batches bisect on oversized responses)
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use async_snmp::{Auth, Client, oid};
//! use std::time::Duration;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<async_snmp::Error>> {
//!     // SNMPv2c client - target accepts (host, port), a string, or a SocketAddr
//!     let client = Client::builder(("192.168.1.1", 161), Auth::v2c("public"))
//!         .timeout(Duration::from_secs(5))
//!         .connect()
//!         .await?;
//!
//!     let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await?;
//!     println!("sysDescr: {:?}", result.value);
//!
//!     Ok(())
//! }
//! ```
//!
//! ## SNMPv3 Example
//!
//! ```rust,no_run
//! use async_snmp::{Auth, Client, oid, v3::{AuthProtocol, PrivProtocol}};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<async_snmp::Error>> {
//!     let client = Client::builder(("192.168.1.1", 161),
//!         Auth::usm("admin")
//!             .auth(AuthProtocol::Sha256, "authpass123")
//!             .privacy(PrivProtocol::Aes128, "privpass123"))
//!         .connect()
//!         .await?;
//!
//!     let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await?;
//!     println!("sysDescr: {:?}", result.value);
//!
//!     Ok(())
//! }
//! ```
//!
//! # Advanced Topics
//!
//! ## Error Handling Patterns
//!
//! The library provides detailed error information for debugging and recovery.
//! See the [`error`] module for complete documentation.
//!
//! ```rust,no_run
//! use async_snmp::{Auth, Client, Error, ErrorStatus, Retry, oid};
//! use std::time::Duration;
//!
//! async fn poll_device(addr: &str) -> Result<String, String> {
//!     let client = Client::builder(addr, Auth::v2c("public"))
//!         .timeout(Duration::from_secs(5))
//!         .retry(Retry::fixed(2, Duration::ZERO))
//!         .connect()
//!         .await
//!         .map_err(|e| format!("Failed to connect: {}", e))?;
//!
//!     match client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await {
//!         Ok(vb) => Ok(vb.value.as_str().unwrap_or("(non-string)").to_string()),
//!         Err(e) => match *e {
//!             Error::Timeout { retries, .. } => {
//!                 Err(format!("Device unreachable after {} retries", retries))
//!             }
//!             Error::Snmp { status: ErrorStatus::NoSuchName, .. } => {
//!                 Err("OID not supported by device".to_string())
//!             }
//!             _ => Err(format!("SNMP error: {}", e)),
//!         },
//!     }
//! }
//! ```
//!
//! ## Retry Configuration
//!
//! UDP transports retry on timeout with configurable backoff strategies.
//! TCP transports ignore retry configuration (the transport layer handles reliability).
//!
//! ```rust
//! use async_snmp::{Auth, Client, Retry};
//! use std::time::Duration;
//!
//! # async fn example() -> async_snmp::Result<()> {
//! // No retries (fail immediately on timeout)
//! let client = Client::builder("192.168.1.1:161", Auth::v2c("public"))
//!     .retry(Retry::none())
//!     .connect().await?;
//!
//! // 3 retries with no delay between attempts
//! let client = Client::builder("192.168.1.1:161", Auth::v2c("public"))
//!     .retry(Retry::fixed(3, Duration::ZERO))
//!     .connect().await?;
//!
//! // Exponential backoff with jitter (1s, 2s, 4s, 5s, 5s)
//! let client = Client::builder("192.168.1.1:161", Auth::v2c("public"))
//!     .retry(Retry::exponential(5)
//!         .max_delay(Duration::from_secs(5))
//!         .jitter(0.25))  // ±25% randomization
//!     .connect().await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Scalable Polling (Shared Transport)
//!
//! For monitoring systems polling many targets, share a single [`UdpTransport`]
//! across all clients:
//!
//! - **1 file descriptor** for all targets (vs 1 per target)
//! - **Firewall session reuse** between polls to the same target
//! - **Lower memory** from shared socket buffers
//! - **No per-poll socket creation** overhead
//!
//! **Scaling guidance:**
//! - **Most use cases**: Single shared [`UdpTransport`] recommended
//! - **~100,000s+ targets**: Multiple [`UdpTransport`] instances, sharded by target
//! - **Scrape isolation**: Per-client via [`.connect()`](ClientBuilder::connect) (FD + syscall overhead)
//!
//! ```rust,no_run
//! use async_snmp::{Auth, Client, oid, UdpTransport};
//! use futures::future::join_all;
//!
//! async fn poll_many_devices(targets: Vec<&str>) -> Vec<(&str, Result<String, String>)> {
//!     // Single socket shared across all clients
//!     let transport = UdpTransport::bind("0.0.0.0:0")
//!         .await
//!         .expect("failed to bind");
//!
//!     let sys_descr = oid!(1, 3, 6, 1, 2, 1, 1, 1, 0);
//!
//!     // Create clients for each target - (host, port) tuples work naturally
//!     let mut clients = Vec::new();
//!     for t in &targets {
//!         let client = Client::builder((*t, 161), Auth::v2c("public"))
//!             .build_with(&transport)
//!             .await
//!             .expect("failed to build client");
//!         clients.push(client);
//!     }
//!
//!     // Poll all targets concurrently
//!     let results = join_all(
//!         clients.iter().map(|c| async {
//!             match c.get(&sys_descr).await {
//!                 Ok(vb) => Ok(vb.value.to_string()),
//!                 Err(e) => Err(e.to_string()),
//!             }
//!         })
//!     ).await;
//!
//!     targets.into_iter().zip(results).collect()
//! }
//! ```
//!
//! ## High-Throughput SNMPv3 Polling
//!
//! SNMPv3 has two expensive per-connection operations:
//! - **Password derivation**: ~850μs to derive keys from passwords (SHA-256)
//! - **Engine discovery**: Round-trip to learn the agent's engine ID and time
//!
//! For polling many targets with shared credentials, cache both:
//!
//! ```rust,no_run
//! use async_snmp::{Auth, AuthProtocol, Client, EngineCache, MasterKeys, PrivProtocol, oid, UdpTransport};
//! use std::sync::Arc;
//!
//! # async fn example() -> async_snmp::Result<()> {
//! // 1. Derive master keys once (expensive: ~850μs)
//! let master_keys = MasterKeys::new(AuthProtocol::Sha256, b"authpassword").unwrap()
//!     .with_privacy(PrivProtocol::Aes128, b"privpassword").unwrap();
//!
//! // 2. Share engine discovery results across clients
//! let engine_cache = Arc::new(EngineCache::new());
//!
//! // 3. Use shared transport for socket efficiency
//! let transport = UdpTransport::bind("0.0.0.0:0").await?;
//!
//! // Poll multiple targets - only ~1μs key localization per engine
//! for target in ["192.0.2.1:161", "192.0.2.2:161"] {
//!     let auth = Auth::usm("snmpuser").with_master_keys(master_keys.clone());
//!
//!     let client = Client::builder(target, auth)
//!         .engine_cache(engine_cache.clone())
//!         .build_with(&transport).await?;
//!
//!     let result = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await?;
//!     println!("{}: {:?}", target, result.value);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! | Optimization | Without | With | Savings |
//! |--------------|---------|------|---------|
//! | `MasterKeys` | 850μs/engine | 1μs/engine | ~99.9% |
//! | `EngineCache` | 1 RTT/engine | 0 RTT (cached) | 1 RTT |
//!
//! ## Graceful Shutdown
//!
//! Use `tokio::select!` or cancellation tokens for clean shutdown.
//!
//! ```rust,no_run
//! use async_snmp::{Auth, Client, oid};
//! use std::time::Duration;
//! use tokio::time::interval;
//!
//! async fn poll_with_shutdown(
//!     addr: &str,
//!     mut shutdown: tokio::sync::oneshot::Receiver<()>,
//! ) {
//!     let client = Client::builder(addr, Auth::v2c("public"))
//!         .connect()
//!         .await
//!         .expect("failed to connect");
//!
//!     let sys_uptime = oid!(1, 3, 6, 1, 2, 1, 1, 3, 0);
//!     let mut poll_interval = interval(Duration::from_secs(30));
//!
//!     loop {
//!         tokio::select! {
//!             _ = &mut shutdown => {
//!                 println!("Shutdown signal received");
//!                 break;
//!             }
//!             _ = poll_interval.tick() => {
//!                 match client.get(&sys_uptime).await {
//!                     Ok(vb) => println!("Uptime: {:?}", vb.value),
//!                     Err(e) => eprintln!("Poll failed: {}", e),
//!                 }
//!             }
//!         }
//!     }
//! }
//! ```
//!
//! ## Tracing Integration
//!
//! The library uses the `tracing` crate for structured logging. All SNMP
//! operations emit spans and events with relevant context.
//!
//! ### Basic Setup
//!
//! ```rust,no_run
//! use async_snmp::{Auth, Client, oid};
//! use tracing_subscriber::EnvFilter;
//!
//! #[tokio::main]
//! async fn main() {
//!     tracing_subscriber::fmt()
//!         .with_env_filter(
//!             EnvFilter::from_default_env()
//!                 .add_directive("async_snmp=debug".parse().unwrap())
//!         )
//!         .init();
//!
//!     let client = Client::builder("192.168.1.1:161", Auth::v2c("public"))
//!         .connect()
//!         .await
//!         .expect("failed to connect");
//!
//!     // Logs: DEBUG async_snmp::client snmp.target=192.168.1.1:161 snmp.request_id=12345
//!     let _ = client.get(&oid!(1, 3, 6, 1, 2, 1, 1, 1, 0)).await;
//! }
//! ```
//!
//! ### Log Levels
//!
//! | Level | What's Logged |
//! |-------|---------------|
//! | ERROR | Socket errors, fatal transport failures |
//! | WARN | Auth failures, parse errors, source address mismatches |
//! | INFO | Connect/disconnect, walk completion |
//! | DEBUG | Request/response flow, engine discovery, retries |
//! | TRACE | Auth verification, raw packet data |
//!
//! ### Structured Fields
//!
//! All fields use the `snmp.` prefix for easy filtering:
//!
//! | Field | Description |
//! |-------|-------------|
//! | `snmp.target` | Target address for outgoing requests |
//! | `snmp.source` | Source address of incoming messages |
//! | `snmp.request_id` | SNMP request identifier |
//! | `snmp.retries` | Current retry attempt number |
//! | `snmp.elapsed_ms` | Request duration in milliseconds |
//! | `snmp.pdu_type` | PDU type (Get, GetNext, etc.) |
//! | `snmp.varbind_count` | Number of varbinds in request/response |
//! | `snmp.error_status` | SNMP error status from response |
//! | `snmp.error_index` | Index of problematic varbind |
//! | `snmp.non_repeaters` | GETBULK non-repeaters parameter |
//! | `snmp.max_repetitions` | GETBULK max-repetitions parameter |
//! | `snmp.username` | SNMPv3 USM username |
//! | `snmp.security_level` | SNMPv3 security level |
//! | `snmp.engine_id` | SNMPv3 engine identifier (hex) |
//! | `snmp.local_addr` | Local bind address |
//!
//! ### Filtering by Target
//!
//! Tracing targets follow a stable naming scheme (not tied to internal module paths):
//!
//! | Target Prefix | What's Included |
//! |---------------|-----------------|
//! | `async_snmp` | Everything |
//! | `async_snmp::client` | Client operations, requests, retries |
//! | `async_snmp::agent` | Agent request/response handling |
//! | `async_snmp::ber` | BER encoding/decoding |
//! | `async_snmp::v3` | SNMPv3 message processing |
//! | `async_snmp::transport` | UDP/TCP transport layer |
//! | `async_snmp::notification` | Trap/inform receiver |
//!
//! ```bash
//! # All library logs at debug level
//! RUST_LOG=async_snmp=debug cargo run
//!
//! # Only warnings and errors
//! RUST_LOG=async_snmp=warn cargo run
//!
//! # Trace client operations, debug everything else
//! RUST_LOG=async_snmp=debug,async_snmp::client=trace cargo run
//!
//! # Debug just BER decoding issues
//! RUST_LOG=async_snmp::ber=debug cargo run
//! ```
//!
//! ## Agent Compatibility
//!
//! Real-world SNMP agents often have quirks. This library provides several
//! options to handle non-conformant implementations.
//!
//! ### Walk Issues
//!
//! | Problem | Solution |
//! |---------|----------|
//! | GETBULK returns errors or garbage | Use [`WalkMode::GetNext`] |
//! | OIDs returned out of order | Use [`OidOrdering::AllowNonIncreasing`] |
//! | Walk never terminates | Set [`ClientBuilder::max_walk_results`] |
//! | Slow responses cause timeouts | Reduce [`ClientBuilder::max_repetitions`] |
//!
//! **Warning**: [`OidOrdering::AllowNonIncreasing`] uses O(n) memory to track
//! seen OIDs for cycle detection. Always pair it with [`ClientBuilder::max_walk_results`]
//! to bound memory usage. The cycle detection catches duplicate OIDs, but a
//! pathological agent could still return an infinite sequence of unique OIDs.
//!
//! ```rust,no_run
//! use async_snmp::{Auth, Client, WalkMode, OidOrdering};
//!
//! # async fn example() -> async_snmp::Result<()> {
//! // Configure for a problematic agent
//! let client = Client::builder("192.168.1.1:161", Auth::v2c("public"))
//!     .walk_mode(WalkMode::GetNext)           // Avoid buggy GETBULK
//!     .oid_ordering(OidOrdering::AllowNonIncreasing)  // Handle out-of-order OIDs
//!     .max_walk_results(10_000)               // IMPORTANT: bound memory usage
//!     .max_repetitions(10)                    // Smaller responses
//!     .connect()
//!     .await?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Permissive Parsing
//!
//! The BER decoder accepts non-conformant encodings that some agents produce:
//! - Non-minimal integer encodings (extra leading bytes)
//! - Non-minimal OID subidentifier encodings
//! - Truncated values (logged as warnings)
//!
//! This matches net-snmp's permissive behavior.
//!
//! ### Unknown Value Types
//!
//! Unrecognized BER tags are preserved as [`Value::Unknown`] rather than
//! causing decode errors. This provides forward compatibility with new
//! SNMP types or vendor extensions.
//!
//! ## Cargo Features
//!
//! - `agent` - SNMP agent (enabled by default)
//! - `crypto-rustcrypto` - RustCrypto-based crypto backend (enabled by default). Supports all auth and privacy protocols.
//! - `crypto-fips` - FIPS 140-3 crypto backend via aws-lc-rs. Rejects MD5, DES, and 3DES. Mutually exclusive with `crypto-rustcrypto`.
//! - `cli` - Builds command-line utilities (`asnmp-get`, `asnmp-walk`, `asnmp-set`)
//! - `mib` - MIB integration via mib-rs (OID conversions, value formatting helpers)
//! - `rt-multi-thread` - Multi-threaded tokio runtime
//! - `tls` - (Placeholder) SNMP over TLS per RFC 6353
//! - `dtls` - (Placeholder) SNMP over DTLS per RFC 6353
//!
//! **Note:** `crypto-rustcrypto` and `crypto-fips` are mutually exclusive.
//! Exactly one must be enabled. Using `--all-features` will not compile;
//! specify features explicitly instead.

#[cfg(feature = "agent")]
pub mod agent;
pub mod ber;
pub mod client;
pub mod error;
pub mod format;
pub mod handler;
pub mod message;
pub mod notification;
pub mod oid;
pub mod pdu;
pub mod prelude;
pub mod transport;
pub mod v3;
pub mod value;
pub mod varbind;
pub mod version;

pub(crate) mod util;

#[cfg(feature = "cli")]
pub mod cli;

#[cfg(feature = "mib")]
pub mod mib_support;

// Re-exports for convenience
#[cfg(feature = "agent")]
pub use agent::{Agent, AgentBuilder, BuiltinMib, VacmBuilder, VacmConfig, View};
pub use client::{
    Auth, Backoff, BulkWalk, Client, ClientBuilder, ClientConfig, CommunityVersion,
    DEFAULT_MAX_OIDS_PER_REQUEST, DEFAULT_MAX_REPETITIONS, DEFAULT_TIMEOUT, OidOrdering, Retry,
    RetryBuilder, Target, UsmAuth, UsmBuilder, Walk, WalkMode, WalkStream,
};
pub use error::{Error, ErrorStatus, Result, WalkAbortReason};
pub use handler::{
    BoxFuture, GetNextResult, GetResult, MibHandler, OidTable, RequestContext, Response,
    SecurityModel, SetResult,
};
pub use message::SecurityLevel;
pub use notification::{
    Notification, NotificationReceiver, NotificationReceiverBuilder, UsmConfig,
    validate_notification_varbinds,
};
pub use oid::Oid;
pub use pdu::{GenericTrap, Pdu, PduType, TrapV1Pdu};
pub use transport::{MAX_UDP_PAYLOAD, TcpTransport, Transport, UdpHandle, UdpTransport};
#[cfg(feature = "crypto-fips")]
pub use v3::AwsLcFipsProvider;
#[cfg(feature = "crypto-rustcrypto")]
pub use v3::RustCryptoProvider;
pub use v3::{
    AuthProtocol, CryptoError, CryptoProvider, CryptoResult, EngineCache, LocalizedKey, MasterKey,
    MasterKeys, ParseProtocolError, PrivProtocol,
};
pub use value::{RowStatus, StorageType, Value};
pub use varbind::VarBind;
pub use version::Version;

/// Type alias for a client using UDP transport.
///
/// This is the default and most common client type.
pub type UdpClient = Client<UdpHandle>;

/// Type alias for a client using a TCP connection.
pub type TcpClient = Client<TcpTransport>;