async_snmp/agent/
mod.rs

1//! SNMP Agent (RFC 3413).
2//!
3//! This module provides SNMP agent functionality for responding to
4//! GET, GETNEXT, GETBULK, and SET requests.
5//!
6//! # Features
7//!
8//! - **Async handlers**: All handler methods are async for database queries, network calls, etc.
9//! - **Atomic SET**: Two-phase commit protocol (test/commit/undo) per RFC 3416
10//! - **VACM support**: Optional View-based Access Control Model (RFC 3415)
11//!
12//! # Example
13//!
14//! ```rust,no_run
15//! use async_snmp::agent::Agent;
16//! use async_snmp::handler::{MibHandler, RequestContext, GetResult, GetNextResult, BoxFuture};
17//! use async_snmp::{Oid, Value, VarBind, oid};
18//! use std::sync::Arc;
19//!
20//! // Define a simple handler for the system MIB subtree
21//! struct SystemMibHandler;
22//!
23//! impl MibHandler for SystemMibHandler {
24//!     fn get<'a>(&'a self, _ctx: &'a RequestContext, oid: &'a Oid) -> BoxFuture<'a, GetResult> {
25//!         Box::pin(async move {
26//!             // sysDescr.0
27//!             if oid == &oid!(1, 3, 6, 1, 2, 1, 1, 1, 0) {
28//!                 return GetResult::Value(Value::OctetString("My SNMP Agent".into()));
29//!             }
30//!             // sysObjectID.0
31//!             if oid == &oid!(1, 3, 6, 1, 2, 1, 1, 2, 0) {
32//!                 return GetResult::Value(Value::ObjectIdentifier(oid!(1, 3, 6, 1, 4, 1, 99999)));
33//!             }
34//!             GetResult::NoSuchObject
35//!         })
36//!     }
37//!
38//!     fn get_next<'a>(&'a self, _ctx: &'a RequestContext, oid: &'a Oid) -> BoxFuture<'a, GetNextResult> {
39//!         Box::pin(async move {
40//!             // Return the lexicographically next OID after the given one
41//!             let sys_descr = oid!(1, 3, 6, 1, 2, 1, 1, 1, 0);
42//!             let sys_object_id = oid!(1, 3, 6, 1, 2, 1, 1, 2, 0);
43//!
44//!             if oid < &sys_descr {
45//!                 return GetNextResult::Value(VarBind::new(sys_descr, Value::OctetString("My SNMP Agent".into())));
46//!             }
47//!             if oid < &sys_object_id {
48//!                 return GetNextResult::Value(VarBind::new(sys_object_id, Value::ObjectIdentifier(oid!(1, 3, 6, 1, 4, 1, 99999))));
49//!             }
50//!             GetNextResult::EndOfMibView
51//!         })
52//!     }
53//! }
54//!
55//! #[tokio::main]
56//! async fn main() -> Result<(), async_snmp::Error> {
57//!     let agent = Agent::builder()
58//!         .bind("0.0.0.0:161")
59//!         .community(b"public")
60//!         .handler(oid!(1, 3, 6, 1, 2, 1, 1), Arc::new(SystemMibHandler))
61//!         .build()
62//!         .await?;
63//!
64//!     agent.run().await
65//! }
66//! ```
67
68mod request;
69mod response;
70mod set_handler;
71pub mod vacm;
72
73pub use vacm::{SecurityModel, VacmBuilder, VacmConfig, View, ViewSubtree};
74
75use std::collections::HashMap;
76use std::net::SocketAddr;
77use std::sync::Arc;
78use std::sync::atomic::{AtomicU32, Ordering};
79use std::time::Instant;
80
81use bytes::Bytes;
82use subtle::ConstantTimeEq;
83use tokio::net::UdpSocket;
84use tracing::instrument;
85
86use crate::ber::Decoder;
87use crate::error::{DecodeErrorKind, Error, ErrorStatus, Result};
88use crate::handler::{GetNextResult, GetResult, MibHandler, RequestContext};
89use crate::notification::UsmUserConfig;
90use crate::oid::Oid;
91use crate::pdu::{Pdu, PduType};
92use crate::util::bind_udp_socket;
93use crate::v3::SaltCounter;
94use crate::value::Value;
95use crate::varbind::VarBind;
96use crate::version::Version;
97
98/// Default maximum message size for UDP (RFC 3417 recommendation).
99const DEFAULT_MAX_MESSAGE_SIZE: usize = 1472;
100
101/// Overhead for SNMP message encoding (approximate conservative estimate).
102/// This accounts for version, community/USM, PDU headers, etc.
103const RESPONSE_OVERHEAD: usize = 100;
104
105/// Registered handler with its OID prefix.
106pub(crate) struct RegisteredHandler {
107    pub(crate) prefix: Oid,
108    pub(crate) handler: Arc<dyn MibHandler>,
109}
110
111/// Builder for [`Agent`].
112///
113/// Use this builder to configure and construct an SNMP agent. The builder
114/// pattern allows you to chain configuration methods before calling
115/// [`build()`](AgentBuilder::build) to create the agent.
116///
117/// # Minimal Example
118///
119/// ```rust,no_run
120/// use async_snmp::agent::Agent;
121/// use async_snmp::handler::{MibHandler, RequestContext, GetResult, GetNextResult, BoxFuture};
122/// use async_snmp::{Oid, Value, VarBind, oid};
123/// use std::sync::Arc;
124///
125/// struct MyHandler;
126/// impl MibHandler for MyHandler {
127///     fn get<'a>(&'a self, _: &'a RequestContext, _: &'a Oid) -> BoxFuture<'a, GetResult> {
128///         Box::pin(async { GetResult::NoSuchObject })
129///     }
130///     fn get_next<'a>(&'a self, _: &'a RequestContext, _: &'a Oid) -> BoxFuture<'a, GetNextResult> {
131///         Box::pin(async { GetNextResult::EndOfMibView })
132///     }
133/// }
134///
135/// # async fn example() -> Result<(), async_snmp::Error> {
136/// let agent = Agent::builder()
137///     .bind("0.0.0.0:1161")  // Use non-privileged port
138///     .community(b"public")
139///     .handler(oid!(1, 3, 6, 1, 4, 1, 99999), Arc::new(MyHandler))
140///     .build()
141///     .await?;
142/// # Ok(())
143/// # }
144/// ```
145pub struct AgentBuilder {
146    bind_addr: String,
147    communities: Vec<Vec<u8>>,
148    usm_users: HashMap<Bytes, UsmUserConfig>,
149    handlers: Vec<RegisteredHandler>,
150    engine_id: Option<Vec<u8>>,
151    max_message_size: usize,
152    vacm: Option<VacmConfig>,
153}
154
155impl AgentBuilder {
156    /// Create a new builder with default settings.
157    ///
158    /// Defaults:
159    /// - Bind address: `0.0.0.0:161` (UDP)
160    /// - Max message size: 1472 bytes (Ethernet MTU - IP/UDP headers)
161    /// - No communities or USM users (all requests rejected)
162    /// - No handlers registered
163    pub fn new() -> Self {
164        Self {
165            bind_addr: "0.0.0.0:161".to_string(),
166            communities: Vec::new(),
167            usm_users: HashMap::new(),
168            handlers: Vec::new(),
169            engine_id: None,
170            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
171            vacm: None,
172        }
173    }
174
175    /// Set the UDP bind address.
176    ///
177    /// Default is `0.0.0.0:161` (standard SNMP agent port). Note that binding
178    /// to UDP port 161 typically requires root/administrator privileges.
179    ///
180    /// # IPv4 Examples
181    ///
182    /// ```rust,no_run
183    /// use async_snmp::agent::Agent;
184    ///
185    /// # async fn example() -> Result<(), async_snmp::Error> {
186    /// // Bind to all IPv4 interfaces on standard port (requires privileges)
187    /// let agent = Agent::builder().bind("0.0.0.0:161").community(b"public").build().await?;
188    ///
189    /// // Bind to localhost only on non-privileged port
190    /// let agent = Agent::builder().bind("127.0.0.1:1161").community(b"public").build().await?;
191    ///
192    /// // Bind to specific interface
193    /// let agent = Agent::builder().bind("192.168.1.100:161").community(b"public").build().await?;
194    /// # Ok(())
195    /// # }
196    /// ```
197    ///
198    /// # IPv6 / Dual-Stack Examples
199    ///
200    /// ```rust,no_run
201    /// use async_snmp::agent::Agent;
202    ///
203    /// # async fn example() -> Result<(), async_snmp::Error> {
204    /// // Bind to all interfaces via dual-stack (handles both IPv4 and IPv6)
205    /// let agent = Agent::builder().bind("[::]:161").community(b"public").build().await?;
206    ///
207    /// // Bind to IPv6 localhost only
208    /// let agent = Agent::builder().bind("[::1]:1161").community(b"public").build().await?;
209    /// # Ok(())
210    /// # }
211    /// ```
212    pub fn bind(mut self, addr: impl Into<String>) -> Self {
213        self.bind_addr = addr.into();
214        self
215    }
216
217    /// Add an accepted community string for v1/v2c requests.
218    ///
219    /// Multiple communities can be added. If none are added,
220    /// all v1/v2c requests are rejected.
221    ///
222    /// # Example
223    ///
224    /// ```rust,no_run
225    /// use async_snmp::agent::Agent;
226    ///
227    /// # async fn example() -> Result<(), async_snmp::Error> {
228    /// let agent = Agent::builder()
229    ///     .bind("0.0.0.0:1161")
230    ///     .community(b"public")   // Read-only access
231    ///     .community(b"private")  // Read-write access (with VACM)
232    ///     .build()
233    ///     .await?;
234    /// # Ok(())
235    /// # }
236    /// ```
237    pub fn community(mut self, community: &[u8]) -> Self {
238        self.communities.push(community.to_vec());
239        self
240    }
241
242    /// Add multiple community strings.
243    ///
244    /// # Example
245    ///
246    /// ```rust,no_run
247    /// use async_snmp::agent::Agent;
248    ///
249    /// # async fn example() -> Result<(), async_snmp::Error> {
250    /// let communities = ["public", "private", "monitor"];
251    /// let agent = Agent::builder()
252    ///     .bind("0.0.0.0:1161")
253    ///     .communities(communities)
254    ///     .build()
255    ///     .await?;
256    /// # Ok(())
257    /// # }
258    /// ```
259    pub fn communities<I, C>(mut self, communities: I) -> Self
260    where
261        I: IntoIterator<Item = C>,
262        C: AsRef<[u8]>,
263    {
264        for c in communities {
265            self.communities.push(c.as_ref().to_vec());
266        }
267        self
268    }
269
270    /// Add a USM user for SNMPv3 authentication.
271    ///
272    /// Configure authentication and privacy settings using the closure.
273    /// Multiple users can be added with different security levels.
274    ///
275    /// # Security Levels
276    ///
277    /// - **noAuthNoPriv**: No authentication or encryption (not recommended)
278    /// - **authNoPriv**: Authentication only (HMAC verification)
279    /// - **authPriv**: Authentication and encryption (most secure)
280    ///
281    /// # Example
282    ///
283    /// ```rust,no_run
284    /// use async_snmp::agent::Agent;
285    /// use async_snmp::{AuthProtocol, PrivProtocol};
286    ///
287    /// # async fn example() -> Result<(), async_snmp::Error> {
288    /// let agent = Agent::builder()
289    ///     .bind("0.0.0.0:1161")
290    ///     // Read-only user with authentication only
291    ///     .usm_user("monitor", |u| {
292    ///         u.auth(AuthProtocol::Sha256, b"monitorpass123")
293    ///     })
294    ///     // Admin user with full encryption
295    ///     .usm_user("admin", |u| {
296    ///         u.auth(AuthProtocol::Sha256, b"adminauth123")
297    ///          .privacy(PrivProtocol::Aes128, b"adminpriv123")
298    ///     })
299    ///     .build()
300    ///     .await?;
301    /// # Ok(())
302    /// # }
303    /// ```
304    pub fn usm_user<F>(mut self, username: impl Into<Bytes>, configure: F) -> Self
305    where
306        F: FnOnce(UsmUserConfig) -> UsmUserConfig,
307    {
308        let username_bytes: Bytes = username.into();
309        let config = configure(UsmUserConfig::new(username_bytes.clone()));
310        self.usm_users.insert(username_bytes, config);
311        self
312    }
313
314    /// Set the engine ID for SNMPv3.
315    ///
316    /// If not set, a default engine ID will be generated based on the
317    /// RFC 3411 format using enterprise number and timestamp.
318    ///
319    /// # Example
320    ///
321    /// ```rust,no_run
322    /// use async_snmp::agent::Agent;
323    ///
324    /// # async fn example() -> Result<(), async_snmp::Error> {
325    /// let agent = Agent::builder()
326    ///     .bind("0.0.0.0:1161")
327    ///     .engine_id(b"\x80\x00\x00\x00\x01MyEngine".to_vec())
328    ///     .community(b"public")
329    ///     .build()
330    ///     .await?;
331    /// # Ok(())
332    /// # }
333    /// ```
334    pub fn engine_id(mut self, engine_id: impl Into<Vec<u8>>) -> Self {
335        self.engine_id = Some(engine_id.into());
336        self
337    }
338
339    /// Set the maximum message size for responses.
340    ///
341    /// Default is 1472 octets (fits Ethernet MTU minus IP/UDP headers).
342    /// GETBULK responses will be truncated to fit within this limit.
343    ///
344    /// For SNMPv3 requests, the agent uses the minimum of this value
345    /// and the msgMaxSize from the request.
346    pub fn max_message_size(mut self, size: usize) -> Self {
347        self.max_message_size = size;
348        self
349    }
350
351    /// Register a MIB handler for an OID subtree.
352    ///
353    /// Handlers are matched by longest prefix. When a request comes in,
354    /// the handler with the longest matching prefix is used.
355    ///
356    /// # Example
357    ///
358    /// ```rust,no_run
359    /// use async_snmp::agent::Agent;
360    /// use async_snmp::handler::{MibHandler, RequestContext, GetResult, GetNextResult, BoxFuture};
361    /// use async_snmp::{Oid, Value, VarBind, oid};
362    /// use std::sync::Arc;
363    ///
364    /// struct SystemHandler;
365    /// impl MibHandler for SystemHandler {
366    ///     fn get<'a>(&'a self, _: &'a RequestContext, oid: &'a Oid) -> BoxFuture<'a, GetResult> {
367    ///         Box::pin(async move {
368    ///             if oid == &oid!(1, 3, 6, 1, 2, 1, 1, 1, 0) {
369    ///                 GetResult::Value(Value::OctetString("My Agent".into()))
370    ///             } else {
371    ///                 GetResult::NoSuchObject
372    ///             }
373    ///         })
374    ///     }
375    ///     fn get_next<'a>(&'a self, _: &'a RequestContext, _: &'a Oid) -> BoxFuture<'a, GetNextResult> {
376    ///         Box::pin(async { GetNextResult::EndOfMibView })
377    ///     }
378    /// }
379    ///
380    /// # async fn example() -> Result<(), async_snmp::Error> {
381    /// let agent = Agent::builder()
382    ///     .bind("0.0.0.0:1161")
383    ///     .community(b"public")
384    ///     // Register handler for system MIB subtree
385    ///     .handler(oid!(1, 3, 6, 1, 2, 1, 1), Arc::new(SystemHandler))
386    ///     .build()
387    ///     .await?;
388    /// # Ok(())
389    /// # }
390    /// ```
391    pub fn handler(mut self, prefix: Oid, handler: Arc<dyn MibHandler>) -> Self {
392        self.handlers.push(RegisteredHandler { prefix, handler });
393        self
394    }
395
396    /// Configure VACM (View-based Access Control Model) using a builder function.
397    ///
398    /// When VACM is enabled, all requests are checked against the configured
399    /// access control rules. Requests that don't have proper access are rejected
400    /// with `noAccess` error (v2c/v3) or `noSuchName` (v1).
401    ///
402    /// # Example
403    ///
404    /// ```rust,no_run
405    /// use async_snmp::agent::{Agent, SecurityModel, VacmBuilder};
406    /// use async_snmp::message::SecurityLevel;
407    /// use async_snmp::oid;
408    ///
409    /// # async fn example() -> Result<(), async_snmp::Error> {
410    /// let agent = Agent::builder()
411    ///     .bind("0.0.0.0:161")
412    ///     .community(b"public")
413    ///     .community(b"private")
414    ///     .vacm(|v| v
415    ///         .group("public", SecurityModel::V2c, "readonly_group")
416    ///         .group("private", SecurityModel::V2c, "readwrite_group")
417    ///         .access("readonly_group", |a| a
418    ///             .read_view("full_view"))
419    ///         .access("readwrite_group", |a| a
420    ///             .read_view("full_view")
421    ///             .write_view("write_view"))
422    ///         .view("full_view", |v| v
423    ///             .include(oid!(1, 3, 6, 1)))
424    ///         .view("write_view", |v| v
425    ///             .include(oid!(1, 3, 6, 1, 2, 1, 1))))
426    ///     .build()
427    ///     .await?;
428    /// # Ok(())
429    /// # }
430    /// ```
431    pub fn vacm<F>(mut self, configure: F) -> Self
432    where
433        F: FnOnce(VacmBuilder) -> VacmBuilder,
434    {
435        let builder = VacmBuilder::new();
436        self.vacm = Some(configure(builder).build());
437        self
438    }
439
440    /// Build the agent.
441    pub async fn build(mut self) -> Result<Agent> {
442        let bind_addr: std::net::SocketAddr = self.bind_addr.parse().map_err(|_| Error::Io {
443            target: None,
444            source: std::io::Error::new(
445                std::io::ErrorKind::InvalidInput,
446                format!("invalid bind address: {}", self.bind_addr),
447            ),
448        })?;
449
450        let socket = bind_udp_socket(bind_addr).await.map_err(|e| Error::Io {
451            target: Some(bind_addr),
452            source: e,
453        })?;
454
455        let local_addr = socket.local_addr().map_err(|e| Error::Io {
456            target: Some(bind_addr),
457            source: e,
458        })?;
459
460        // Generate default engine ID if not provided
461        let engine_id = self.engine_id.unwrap_or_else(|| {
462            // RFC 3411 format: enterprise number + format + local identifier
463            // Use a simple format: 0x80 (local) + timestamp + random
464            let mut id = vec![0x80, 0x00, 0x00, 0x00, 0x01]; // Enterprise format indicator
465            let timestamp = std::time::SystemTime::now()
466                .duration_since(std::time::UNIX_EPOCH)
467                .unwrap_or_default()
468                .as_secs();
469            id.extend_from_slice(&timestamp.to_be_bytes());
470            id
471        });
472
473        // Sort handlers by prefix length (longest first) for matching
474        self.handlers
475            .sort_by(|a, b| b.prefix.len().cmp(&a.prefix.len()));
476
477        Ok(Agent {
478            inner: Arc::new(AgentInner {
479                socket,
480                local_addr,
481                communities: self.communities,
482                usm_users: self.usm_users,
483                handlers: self.handlers,
484                engine_id,
485                engine_boots: AtomicU32::new(1),
486                engine_time: AtomicU32::new(0),
487                engine_start: Instant::now(),
488                salt_counter: SaltCounter::new(),
489                max_message_size: self.max_message_size,
490                vacm: self.vacm,
491                snmp_invalid_msgs: AtomicU32::new(0),
492                snmp_unknown_security_models: AtomicU32::new(0),
493                snmp_silent_drops: AtomicU32::new(0),
494            }),
495        })
496    }
497}
498
499impl Default for AgentBuilder {
500    fn default() -> Self {
501        Self::new()
502    }
503}
504
505/// Inner state shared across agent clones.
506pub(crate) struct AgentInner {
507    pub(crate) socket: UdpSocket,
508    pub(crate) local_addr: SocketAddr,
509    pub(crate) communities: Vec<Vec<u8>>,
510    pub(crate) usm_users: HashMap<Bytes, UsmUserConfig>,
511    pub(crate) handlers: Vec<RegisteredHandler>,
512    pub(crate) engine_id: Vec<u8>,
513    pub(crate) engine_boots: AtomicU32,
514    pub(crate) engine_time: AtomicU32,
515    pub(crate) engine_start: Instant,
516    pub(crate) salt_counter: SaltCounter,
517    pub(crate) max_message_size: usize,
518    pub(crate) vacm: Option<VacmConfig>,
519    // RFC 3412 statistics counters
520    /// snmpInvalidMsgs (1.3.6.1.6.3.11.2.1.2) - messages with invalid msgFlags
521    /// (e.g., privacy without authentication)
522    pub(crate) snmp_invalid_msgs: AtomicU32,
523    /// snmpUnknownSecurityModels (1.3.6.1.6.3.11.2.1.1) - messages with
524    /// unrecognized security model
525    pub(crate) snmp_unknown_security_models: AtomicU32,
526    /// snmpSilentDrops (1.3.6.1.6.3.11.2.1.3) - confirmed-class PDUs silently
527    /// dropped because even an empty response would exceed max message size
528    pub(crate) snmp_silent_drops: AtomicU32,
529}
530
531/// SNMP Agent.
532///
533/// Listens for and responds to SNMP requests (GET, GETNEXT, GETBULK, SET).
534///
535/// # Example
536///
537/// ```rust,no_run
538/// use async_snmp::agent::Agent;
539/// use async_snmp::oid;
540///
541/// # async fn example() -> Result<(), async_snmp::Error> {
542/// let agent = Agent::builder()
543///     .bind("0.0.0.0:161")
544///     .community(b"public")
545///     .build()
546///     .await?;
547///
548/// agent.run().await
549/// # }
550/// ```
551pub struct Agent {
552    pub(crate) inner: Arc<AgentInner>,
553}
554
555impl Agent {
556    /// Create a builder for configuring the agent.
557    pub fn builder() -> AgentBuilder {
558        AgentBuilder::new()
559    }
560
561    /// Get the local address the agent is bound to.
562    pub fn local_addr(&self) -> SocketAddr {
563        self.inner.local_addr
564    }
565
566    /// Get the engine ID.
567    pub fn engine_id(&self) -> &[u8] {
568        &self.inner.engine_id
569    }
570
571    /// Get the snmpInvalidMsgs counter value.
572    ///
573    /// This counter tracks messages with invalid msgFlags, such as
574    /// privacy-without-authentication (RFC 3412 Section 7.2 Step 5d).
575    ///
576    /// OID: 1.3.6.1.6.3.11.2.1.2
577    pub fn snmp_invalid_msgs(&self) -> u32 {
578        self.inner.snmp_invalid_msgs.load(Ordering::Relaxed)
579    }
580
581    /// Get the snmpUnknownSecurityModels counter value.
582    ///
583    /// This counter tracks messages with unrecognized security models
584    /// (RFC 3412 Section 7.2 Step 2).
585    ///
586    /// OID: 1.3.6.1.6.3.11.2.1.1
587    pub fn snmp_unknown_security_models(&self) -> u32 {
588        self.inner
589            .snmp_unknown_security_models
590            .load(Ordering::Relaxed)
591    }
592
593    /// Get the snmpSilentDrops counter value.
594    ///
595    /// This counter tracks confirmed-class PDUs (GetRequest, GetNextRequest,
596    /// GetBulkRequest, SetRequest, InformRequest) that were silently dropped
597    /// because even an empty Response-PDU would exceed the maximum message
598    /// size constraint (RFC 3412 Section 7.1).
599    ///
600    /// OID: 1.3.6.1.6.3.11.2.1.3
601    pub fn snmp_silent_drops(&self) -> u32 {
602        self.inner.snmp_silent_drops.load(Ordering::Relaxed)
603    }
604
605    /// Run the agent, processing requests indefinitely.
606    ///
607    /// This method runs until an error occurs or the task is cancelled.
608    #[instrument(skip(self), err, fields(snmp.local_addr = %self.local_addr()))]
609    pub async fn run(&self) -> Result<()> {
610        let mut buf = vec![0u8; 65535];
611
612        loop {
613            let (len, source) =
614                self.inner
615                    .socket
616                    .recv_from(&mut buf)
617                    .await
618                    .map_err(|e| Error::Io {
619                        target: Some(self.inner.local_addr),
620                        source: e,
621                    })?;
622
623            let data = Bytes::copy_from_slice(&buf[..len]);
624
625            // Update engine time before processing
626            self.update_engine_time();
627
628            match self.handle_request(data, source).await {
629                Ok(Some(response_bytes)) => {
630                    if let Err(e) = self.inner.socket.send_to(&response_bytes, source).await {
631                        tracing::warn!(snmp.source = %source, error = %e, "failed to send response");
632                    }
633                }
634                Ok(None) => {
635                    // No response needed (e.g., invalid message)
636                }
637                Err(e) => {
638                    tracing::warn!(snmp.source = %source, error = %e, "error handling request");
639                }
640            }
641        }
642    }
643
644    /// Process a single request and return the response bytes.
645    ///
646    /// Returns `None` if no response should be sent.
647    async fn handle_request(&self, data: Bytes, source: SocketAddr) -> Result<Option<Bytes>> {
648        // Peek at version
649        let mut decoder = Decoder::new(data.clone());
650        let mut seq = decoder.read_sequence()?;
651        let version_num = seq.read_integer()?;
652        let version = Version::from_i32(version_num).ok_or_else(|| {
653            Error::decode(seq.offset(), DecodeErrorKind::UnknownVersion(version_num))
654        })?;
655        drop(seq);
656        drop(decoder);
657
658        match version {
659            Version::V1 => self.handle_v1(data, source).await,
660            Version::V2c => self.handle_v2c(data, source).await,
661            Version::V3 => self.handle_v3(data, source).await,
662        }
663    }
664
665    /// Update engine time based on elapsed time since start.
666    fn update_engine_time(&self) {
667        let elapsed = self.inner.engine_start.elapsed().as_secs() as u32;
668        self.inner.engine_time.store(elapsed, Ordering::Relaxed);
669    }
670
671    /// Validate community string using constant-time comparison.
672    ///
673    /// Uses constant-time comparison to prevent timing attacks that could
674    /// be used to guess valid community strings character by character.
675    pub(crate) fn validate_community(&self, community: &[u8]) -> bool {
676        if self.inner.communities.is_empty() {
677            // No communities configured = reject all
678            return false;
679        }
680        // Use constant-time comparison for each community string.
681        // We compare against all configured communities regardless of
682        // early matches to maintain constant-time behavior.
683        let mut valid = false;
684        for configured in &self.inner.communities {
685            // ct_eq returns a Choice, which we convert to bool after comparison
686            if configured.len() == community.len()
687                && bool::from(configured.as_slice().ct_eq(community))
688            {
689                valid = true;
690            }
691        }
692        valid
693    }
694
695    /// Dispatch a request to the appropriate handler.
696    async fn dispatch_request(&self, ctx: &RequestContext, pdu: &Pdu) -> Result<Pdu> {
697        match pdu.pdu_type {
698            PduType::GetRequest => self.handle_get(ctx, pdu).await,
699            PduType::GetNextRequest => self.handle_get_next(ctx, pdu).await,
700            PduType::GetBulkRequest => self.handle_get_bulk(ctx, pdu).await,
701            PduType::SetRequest => self.handle_set(ctx, pdu).await,
702            PduType::InformRequest => self.handle_inform(pdu),
703            _ => {
704                // Should not happen - filtered earlier
705                Ok(pdu.to_error_response(ErrorStatus::GenErr, 0))
706            }
707        }
708    }
709
710    /// Handle InformRequest PDU.
711    ///
712    /// Per RFC 3416 Section 4.2.7, an InformRequest is a confirmed-class PDU
713    /// that the receiver acknowledges by returning a Response with the same
714    /// request-id and varbind list.
715    fn handle_inform(&self, pdu: &Pdu) -> Result<Pdu> {
716        // Simply acknowledge by returning the same varbinds in a Response
717        Ok(Pdu {
718            pdu_type: PduType::Response,
719            request_id: pdu.request_id,
720            error_status: 0,
721            error_index: 0,
722            varbinds: pdu.varbinds.clone(),
723        })
724    }
725
726    /// Handle GET request.
727    async fn handle_get(&self, ctx: &RequestContext, pdu: &Pdu) -> Result<Pdu> {
728        let mut response_varbinds = Vec::with_capacity(pdu.varbinds.len());
729
730        for (index, vb) in pdu.varbinds.iter().enumerate() {
731            // VACM read access check
732            if let Some(ref vacm) = self.inner.vacm
733                && !vacm.check_access(ctx.read_view.as_ref(), &vb.oid)
734            {
735                // v1: noSuchName, v2c/v3: noAccess or NoSuchObject
736                if ctx.version == Version::V1 {
737                    return Ok(Pdu {
738                        pdu_type: PduType::Response,
739                        request_id: pdu.request_id,
740                        error_status: ErrorStatus::NoSuchName.as_i32(),
741                        error_index: (index + 1) as i32,
742                        varbinds: pdu.varbinds.clone(),
743                    });
744                } else {
745                    // For GET, return NoSuchObject for inaccessible OIDs per RFC 3415
746                    response_varbinds.push(VarBind::new(vb.oid.clone(), Value::NoSuchObject));
747                    continue;
748                }
749            }
750
751            let result = if let Some(handler) = self.find_handler(&vb.oid) {
752                handler.handler.get(ctx, &vb.oid).await
753            } else {
754                GetResult::NoSuchObject
755            };
756
757            let response_value = match result {
758                GetResult::Value(v) => v,
759                GetResult::NoSuchObject => {
760                    // v1 returns noSuchName error, v2c/v3 returns NoSuchObject exception
761                    if ctx.version == Version::V1 {
762                        return Ok(Pdu {
763                            pdu_type: PduType::Response,
764                            request_id: pdu.request_id,
765                            error_status: ErrorStatus::NoSuchName.as_i32(),
766                            error_index: (index + 1) as i32,
767                            varbinds: pdu.varbinds.clone(),
768                        });
769                    } else {
770                        Value::NoSuchObject
771                    }
772                }
773                GetResult::NoSuchInstance => {
774                    // v1 returns noSuchName error, v2c/v3 returns NoSuchInstance exception
775                    if ctx.version == Version::V1 {
776                        return Ok(Pdu {
777                            pdu_type: PduType::Response,
778                            request_id: pdu.request_id,
779                            error_status: ErrorStatus::NoSuchName.as_i32(),
780                            error_index: (index + 1) as i32,
781                            varbinds: pdu.varbinds.clone(),
782                        });
783                    } else {
784                        Value::NoSuchInstance
785                    }
786                }
787            };
788
789            response_varbinds.push(VarBind::new(vb.oid.clone(), response_value));
790        }
791
792        Ok(Pdu {
793            pdu_type: PduType::Response,
794            request_id: pdu.request_id,
795            error_status: 0,
796            error_index: 0,
797            varbinds: response_varbinds,
798        })
799    }
800
801    /// Handle GETNEXT request.
802    async fn handle_get_next(&self, ctx: &RequestContext, pdu: &Pdu) -> Result<Pdu> {
803        let mut response_varbinds = Vec::with_capacity(pdu.varbinds.len());
804
805        for (index, vb) in pdu.varbinds.iter().enumerate() {
806            // Try to find the next OID from any handler
807            let next = self.get_next_oid(ctx, &vb.oid).await;
808
809            // Check VACM access for the returned OID (if VACM enabled)
810            let next = if let Some(ref next_vb) = next {
811                if let Some(ref vacm) = self.inner.vacm {
812                    if vacm.check_access(ctx.read_view.as_ref(), &next_vb.oid) {
813                        next
814                    } else {
815                        // OID not accessible, continue searching
816                        // For simplicity, we just return EndOfMibView here
817                        // A more complete implementation would continue the search
818                        None
819                    }
820                } else {
821                    next
822                }
823            } else {
824                next
825            };
826
827            match next {
828                Some(next_vb) => {
829                    response_varbinds.push(next_vb);
830                }
831                None => {
832                    // v1 returns noSuchName, v2c/v3 returns endOfMibView
833                    if ctx.version == Version::V1 {
834                        return Ok(Pdu {
835                            pdu_type: PduType::Response,
836                            request_id: pdu.request_id,
837                            error_status: ErrorStatus::NoSuchName.as_i32(),
838                            error_index: (index + 1) as i32,
839                            varbinds: pdu.varbinds.clone(),
840                        });
841                    } else {
842                        response_varbinds.push(VarBind::new(vb.oid.clone(), Value::EndOfMibView));
843                    }
844                }
845            }
846        }
847
848        Ok(Pdu {
849            pdu_type: PduType::Response,
850            request_id: pdu.request_id,
851            error_status: 0,
852            error_index: 0,
853            varbinds: response_varbinds,
854        })
855    }
856
857    /// Handle GETBULK request.
858    ///
859    /// Per RFC 3416 Section 4.2.3, if the response would exceed the message
860    /// size limit, we return fewer variable bindings rather than all of them.
861    async fn handle_get_bulk(&self, ctx: &RequestContext, pdu: &Pdu) -> Result<Pdu> {
862        // For GETBULK, error_status is non_repeaters and error_index is max_repetitions
863        let non_repeaters = pdu.error_status.max(0) as usize;
864        let max_repetitions = pdu.error_index.max(0) as usize;
865
866        let mut response_varbinds = Vec::new();
867        let mut current_size: usize = RESPONSE_OVERHEAD;
868        let max_size = self.inner.max_message_size;
869
870        // Helper to check if we can add a varbind
871        let can_add = |vb: &VarBind, current_size: usize| -> bool {
872            current_size + vb.encoded_size() <= max_size
873        };
874
875        // Handle non-repeaters (first N varbinds get one GETNEXT each)
876        for vb in pdu.varbinds.iter().take(non_repeaters) {
877            let next_vb = match self.get_next_oid(ctx, &vb.oid).await {
878                Some(next_vb) => next_vb,
879                None => VarBind::new(vb.oid.clone(), Value::EndOfMibView),
880            };
881
882            if !can_add(&next_vb, current_size) {
883                // Can't fit even non-repeaters, return tooBig if we have nothing
884                if response_varbinds.is_empty() {
885                    return Ok(Pdu {
886                        pdu_type: PduType::Response,
887                        request_id: pdu.request_id,
888                        error_status: ErrorStatus::TooBig.as_i32(),
889                        error_index: 0,
890                        varbinds: pdu.varbinds.clone(),
891                    });
892                }
893                // Otherwise return what we have
894                break;
895            }
896
897            current_size += next_vb.encoded_size();
898            response_varbinds.push(next_vb);
899        }
900
901        // Handle repeaters
902        if non_repeaters < pdu.varbinds.len() {
903            let repeaters = &pdu.varbinds[non_repeaters..];
904            let mut current_oids: Vec<Oid> = repeaters.iter().map(|vb| vb.oid.clone()).collect();
905            let mut all_done = vec![false; repeaters.len()];
906
907            'outer: for _ in 0..max_repetitions {
908                let mut row_complete = true;
909                for (i, oid) in current_oids.iter_mut().enumerate() {
910                    let next_vb = if all_done[i] {
911                        VarBind::new(oid.clone(), Value::EndOfMibView)
912                    } else {
913                        match self.get_next_oid(ctx, oid).await {
914                            Some(next_vb) => {
915                                *oid = next_vb.oid.clone();
916                                row_complete = false;
917                                next_vb
918                            }
919                            None => {
920                                all_done[i] = true;
921                                VarBind::new(oid.clone(), Value::EndOfMibView)
922                            }
923                        }
924                    };
925
926                    // Check size before adding
927                    if !can_add(&next_vb, current_size) {
928                        // Can't fit more, return what we have
929                        break 'outer;
930                    }
931
932                    current_size += next_vb.encoded_size();
933                    response_varbinds.push(next_vb);
934                }
935
936                if row_complete {
937                    break;
938                }
939            }
940        }
941
942        Ok(Pdu {
943            pdu_type: PduType::Response,
944            request_id: pdu.request_id,
945            error_status: 0,
946            error_index: 0,
947            varbinds: response_varbinds,
948        })
949    }
950
951    /// Find the handler for a given OID.
952    pub(crate) fn find_handler(&self, oid: &Oid) -> Option<&RegisteredHandler> {
953        // Handlers are sorted by prefix length (longest first)
954        self.inner
955            .handlers
956            .iter()
957            .find(|&handler| handler.handler.handles(&handler.prefix, oid))
958            .map(|v| v as _)
959    }
960
961    /// Get the next OID from any handler.
962    async fn get_next_oid(&self, ctx: &RequestContext, oid: &Oid) -> Option<VarBind> {
963        // Find the first handler that can provide a next OID
964        let mut best_result: Option<VarBind> = None;
965
966        for handler in &self.inner.handlers {
967            if let GetNextResult::Value(next) = handler.handler.get_next(ctx, oid).await {
968                // Must be lexicographically greater than the request OID
969                if next.oid > *oid {
970                    match &best_result {
971                        None => best_result = Some(next),
972                        Some(current) if next.oid < current.oid => best_result = Some(next),
973                        _ => {}
974                    }
975                }
976            }
977        }
978
979        best_result
980    }
981}
982
983impl Clone for Agent {
984    fn clone(&self) -> Self {
985        Self {
986            inner: Arc::clone(&self.inner),
987        }
988    }
989}
990
991#[cfg(test)]
992mod tests {
993    use super::*;
994    use crate::handler::{
995        BoxFuture, GetNextResult, GetResult, MibHandler, RequestContext, SecurityModel, SetResult,
996    };
997    use crate::message::SecurityLevel;
998    use crate::oid;
999
1000    struct TestHandler;
1001
1002    impl MibHandler for TestHandler {
1003        fn get<'a>(&'a self, _ctx: &'a RequestContext, oid: &'a Oid) -> BoxFuture<'a, GetResult> {
1004            Box::pin(async move {
1005                if oid == &oid!(1, 3, 6, 1, 4, 1, 99999, 1, 0) {
1006                    return GetResult::Value(Value::Integer(42));
1007                }
1008                if oid == &oid!(1, 3, 6, 1, 4, 1, 99999, 2, 0) {
1009                    return GetResult::Value(Value::OctetString(Bytes::from_static(b"test")));
1010                }
1011                GetResult::NoSuchObject
1012            })
1013        }
1014
1015        fn get_next<'a>(
1016            &'a self,
1017            _ctx: &'a RequestContext,
1018            oid: &'a Oid,
1019        ) -> BoxFuture<'a, GetNextResult> {
1020            Box::pin(async move {
1021                let oid1 = oid!(1, 3, 6, 1, 4, 1, 99999, 1, 0);
1022                let oid2 = oid!(1, 3, 6, 1, 4, 1, 99999, 2, 0);
1023
1024                if oid < &oid1 {
1025                    return GetNextResult::Value(VarBind::new(oid1, Value::Integer(42)));
1026                }
1027                if oid < &oid2 {
1028                    return GetNextResult::Value(VarBind::new(
1029                        oid2,
1030                        Value::OctetString(Bytes::from_static(b"test")),
1031                    ));
1032                }
1033                GetNextResult::EndOfMibView
1034            })
1035        }
1036    }
1037
1038    fn test_ctx() -> RequestContext {
1039        RequestContext {
1040            source: "127.0.0.1:12345".parse().unwrap(),
1041            version: Version::V2c,
1042            security_model: SecurityModel::V2c,
1043            security_name: Bytes::from_static(b"public"),
1044            security_level: SecurityLevel::NoAuthNoPriv,
1045            context_name: Bytes::new(),
1046            request_id: 1,
1047            pdu_type: PduType::GetRequest,
1048            group_name: None,
1049            read_view: None,
1050            write_view: None,
1051        }
1052    }
1053
1054    #[test]
1055    fn test_agent_builder_defaults() {
1056        let builder = AgentBuilder::new();
1057        assert_eq!(builder.bind_addr, "0.0.0.0:161");
1058        assert!(builder.communities.is_empty());
1059        assert!(builder.usm_users.is_empty());
1060        assert!(builder.handlers.is_empty());
1061    }
1062
1063    #[test]
1064    fn test_agent_builder_community() {
1065        let builder = AgentBuilder::new()
1066            .community(b"public")
1067            .community(b"private");
1068        assert_eq!(builder.communities.len(), 2);
1069    }
1070
1071    #[test]
1072    fn test_agent_builder_communities() {
1073        let builder = AgentBuilder::new().communities(["public", "private"]);
1074        assert_eq!(builder.communities.len(), 2);
1075    }
1076
1077    #[test]
1078    fn test_agent_builder_handler() {
1079        let builder =
1080            AgentBuilder::new().handler(oid!(1, 3, 6, 1, 4, 1, 99999), Arc::new(TestHandler));
1081        assert_eq!(builder.handlers.len(), 1);
1082    }
1083
1084    #[tokio::test]
1085    async fn test_mib_handler_default_set() {
1086        let handler = TestHandler;
1087        let mut ctx = test_ctx();
1088        ctx.pdu_type = PduType::SetRequest;
1089
1090        let result = handler
1091            .test_set(&ctx, &oid!(1, 3, 6, 1), &Value::Integer(1))
1092            .await;
1093        assert_eq!(result, SetResult::NotWritable);
1094    }
1095
1096    #[test]
1097    fn test_mib_handler_handles() {
1098        let handler = TestHandler;
1099        let prefix = oid!(1, 3, 6, 1, 4, 1, 99999);
1100
1101        // OID within prefix
1102        assert!(handler.handles(&prefix, &oid!(1, 3, 6, 1, 4, 1, 99999, 1, 0)));
1103
1104        // OID before prefix (GETNEXT should still try)
1105        assert!(handler.handles(&prefix, &oid!(1, 3, 6, 1, 4, 1, 99998)));
1106
1107        // OID after prefix (not handled)
1108        assert!(!handler.handles(&prefix, &oid!(1, 3, 6, 1, 4, 1, 100000)));
1109    }
1110
1111    #[tokio::test]
1112    async fn test_test_handler_get() {
1113        let handler = TestHandler;
1114        let ctx = test_ctx();
1115
1116        // Existing OID
1117        let result = handler
1118            .get(&ctx, &oid!(1, 3, 6, 1, 4, 1, 99999, 1, 0))
1119            .await;
1120        assert!(matches!(result, GetResult::Value(Value::Integer(42))));
1121
1122        // Non-existing OID
1123        let result = handler
1124            .get(&ctx, &oid!(1, 3, 6, 1, 4, 1, 99999, 99, 0))
1125            .await;
1126        assert!(matches!(result, GetResult::NoSuchObject));
1127    }
1128
1129    #[tokio::test]
1130    async fn test_test_handler_get_next() {
1131        let handler = TestHandler;
1132        let mut ctx = test_ctx();
1133        ctx.pdu_type = PduType::GetNextRequest;
1134
1135        // Before first OID
1136        let next = handler.get_next(&ctx, &oid!(1, 3, 6, 1, 4, 1, 99999)).await;
1137        assert!(next.is_value());
1138        if let GetNextResult::Value(vb) = next {
1139            assert_eq!(vb.oid, oid!(1, 3, 6, 1, 4, 1, 99999, 1, 0));
1140        }
1141
1142        // Between OIDs
1143        let next = handler
1144            .get_next(&ctx, &oid!(1, 3, 6, 1, 4, 1, 99999, 1, 0))
1145            .await;
1146        assert!(next.is_value());
1147        if let GetNextResult::Value(vb) = next {
1148            assert_eq!(vb.oid, oid!(1, 3, 6, 1, 4, 1, 99999, 2, 0));
1149        }
1150
1151        // After last OID
1152        let next = handler
1153            .get_next(&ctx, &oid!(1, 3, 6, 1, 4, 1, 99999, 2, 0))
1154            .await;
1155        assert!(next.is_end_of_mib_view());
1156    }
1157}