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
//! Result types for MIB handler operations.
//!
//! Defines the result types returned by [`MibHandler`](super::MibHandler)
//! methods:
//!
//! - [`GetResult`] - Result of a GET operation
//! - [`GetNextResult`] - Result of a GETNEXT operation
//! - [`SetTestError`] / [`SetTestResult`] - SET validation failures and prepared state
//! - [`SetCommitResult`] / [`SetUndoResult`] - Phase-specific apply and rollback results
//! - [`HandlerError`] / [`HandlerResult`] - Handler processing failures (mapped to `genErr`)
use Cow;
use crateErrorStatus;
use crateValue;
use crateVarBind;
/// A handler processing failure, reported to the manager as a `genErr` Response.
///
/// Returned as the `Err` side of [`HandlerResult`] from
/// [`MibHandler::get`](super::MibHandler::get) and
/// [`MibHandler::get_next`](super::MibHandler::get_next) when the handler
/// *failed to process* the request — the backing store was unreachable, a lock
/// was poisoned, a hardware read timed out. It is distinct from the RFC 3416
/// exception values, which are successful answers about the MIB:
///
/// | Situation | Return |
/// |-----------|--------|
/// | Object/instance doesn't exist | `Ok(GetResult::NoSuchObject / NoSuchInstance)` |
/// | No more OIDs in the subtree | `Ok(GetNextResult::EndOfMibView)` |
/// | Couldn't find out (backend failure) | `Err(HandlerError)` |
///
/// When a handler returns an error, the agent answers the whole request with
/// error-status `genErr` and error-index set to the failing variable binding
/// (RFC 3416 Section 4.2.1), for all protocol versions. The message and source
/// are logged by the agent; they are never sent on the wire — `genErr` carries
/// no detail.
///
/// # Construction
///
/// Any [`std::error::Error`] converts via `?`, or build one from a message:
///
/// ```rust
/// use async_snmp::handler::{HandlerError, HandlerResult, GetResult};
///
/// fn read_backend() -> std::io::Result<i32> {
/// Err(std::io::Error::other("device bus timeout"))
/// }
///
/// fn get_value() -> HandlerResult<GetResult> {
/// let raw = read_backend()?; // io::Error -> HandlerError
/// Ok(GetResult::Value(async_snmp::Value::Integer(raw)))
/// }
///
/// let err: HandlerError = HandlerError::new("cache poisoned");
/// assert_eq!(err.message(), "cache poisoned");
/// assert!(get_value().is_err());
/// ```
///
/// `HandlerError` intentionally does not implement [`std::error::Error`]:
/// that keeps the blanket `From<E: std::error::Error>` conversion (and with it
/// `?` on arbitrary error types) possible, the same trade-off `anyhow::Error`
/// makes. It is a terminal type — the agent consumes it; nothing converts out
/// of it.
/// Result type returned by [`MibHandler::get`](super::MibHandler::get) and
/// [`MibHandler::get_next`](super::MibHandler::get_next).
///
/// `Err` means the handler failed to process the request and the agent must
/// answer `genErr`; see [`HandlerError`] for when to return which.
pub type HandlerResult<T> = ;
/// Result of preparing one SET varbind.
///
/// `Ok` carries request-owned state that the agent retains through the commit
/// phase. `Err` is the protocol failure for this varbind and must not leave a
/// reservation behind.
pub type SetTestResult = ;
/// A protocol validation failure from the SET test phase.
///
/// This type deliberately cannot represent successful validation, or failures
/// that only make sense after commit begins. Consequently `Err` from
/// [`MibHandler::test_set`](super::MibHandler::test_set) can never accidentally
/// encode `noError`, `commitFailed`, or `undoFailed`.
///
/// ```compile_fail
/// use async_snmp::{SetCommitError, SetTestResult};
///
/// let _: SetTestResult = Err(SetCommitError::Failed);
/// ```
///
/// Commit- and undo-only failures are likewise different types:
///
/// ```compile_fail
/// use async_snmp::{SetCommitError, SetTestError};
///
/// let _: SetTestError = SetCommitError::Failed;
/// ```
/// Result of applying one prepared SET varbind.
///
/// Validation failures cannot be returned from this phase:
///
/// ```compile_fail
/// use async_snmp::{SetCommitResult, SetTestError};
///
/// let _: SetCommitResult = Err(SetTestError::GeneralFailure);
/// ```
pub type SetCommitResult = ;
/// Failure from the SET commit phase.
///
/// The dedicated type prevents a commit callback from returning validation or
/// undo-only statuses. The agent maps this failure to `commitFailed` and uses
/// the failed varbind's one-based index.
/// Result of rolling back one attempted SET commit.
///
/// Commit failures cannot be returned from this phase:
///
/// ```compile_fail
/// use async_snmp::{SetCommitError, SetUndoResult};
///
/// let _: SetUndoResult = Err(SetCommitError::Failed);
/// ```
pub type SetUndoResult = ;
/// Failure from the SET undo phase.
///
/// The dedicated type prevents an undo callback from returning validation or
/// commit-only statuses. The agent maps this failure to `undoFailed` with
/// error-index zero for SNMPv2c/v3. For SNMPv1, RFC 2576 downgrades the status
/// to `genErr` and uses the failed undo binding's one-based index.
/// Result of a GET operation on a specific OID (RFC 3416).
///
/// This enum distinguishes between the RFC 3416-mandated exception types:
/// - `Value`: The OID exists and has the given value
/// - `NoSuchObject`: The OID's object type is not supported (agent doesn't implement this MIB)
/// - `NoSuchInstance`: The object type exists but this specific instance doesn't
/// (e.g., table row doesn't exist)
///
/// # Version differences
///
/// - **`SNMPv1`**: Both exception types result in a `noSuchName` error response
/// - **SNMPv2c/v3**: Returns the appropriate exception value in the response varbind
///
/// # Choosing `NoSuchObject` or `NoSuchInstance`
///
/// | Situation | Variant |
/// |-----------|---------|
/// | OID prefix not recognized | [`NoSuchObject`](GetResult::NoSuchObject) |
/// | Scalar object not implemented | [`NoSuchObject`](GetResult::NoSuchObject) |
/// | Table column not implemented | [`NoSuchObject`](GetResult::NoSuchObject) |
/// | Table row doesn't exist | [`NoSuchInstance`](GetResult::NoSuchInstance) |
/// | Scalar has no value (optional) | [`NoSuchInstance`](GetResult::NoSuchInstance) |
///
/// # Example: scalar objects
///
/// ```rust
/// use async_snmp::handler::GetResult;
/// use async_snmp::{Value, oid};
///
/// fn get_scalar(oid: &async_snmp::Oid) -> GetResult {
/// if oid == &oid!(1, 3, 6, 1, 2, 1, 1, 1, 0) { // sysDescr.0
/// GetResult::Value(Value::OctetString("My SNMP Agent".into()))
/// } else if oid == &oid!(1, 3, 6, 1, 2, 1, 1, 2, 0) { // sysObjectID.0
/// GetResult::Value(Value::ObjectIdentifier(oid!(1, 3, 6, 1, 4, 1, 99999)))
/// } else {
/// GetResult::NoSuchObject
/// }
/// }
/// ```
///
/// # Example: table objects
///
/// ```rust
/// use async_snmp::handler::GetResult;
/// use async_snmp::{Value, Oid, oid};
///
/// struct IfTable {
/// entries: Vec<(u32, String)>, // (index, description)
/// }
///
/// impl IfTable {
/// fn get(&self, oid: &Oid) -> GetResult {
/// let if_descr_prefix = oid!(1, 3, 6, 1, 2, 1, 2, 2, 1, 2);
///
/// if !oid.starts_with(&if_descr_prefix) {
/// return GetResult::NoSuchObject; // Not our column
/// }
///
/// // Extract index from OID (position after prefix)
/// let arcs = oid.arcs();
/// if arcs.len() != if_descr_prefix.len() + 1 {
/// return GetResult::NoSuchInstance; // Wrong index format
/// }
///
/// let index = arcs[if_descr_prefix.len()];
/// match self.entries.iter().find(|(i, _)| *i == index) {
/// Some((_, desc)) => GetResult::Value(Value::OctetString(desc.clone().into())),
/// None => GetResult::NoSuchInstance, // Row doesn't exist
/// }
/// }
/// }
/// ```
/// Result of a GETNEXT operation (RFC 3416).
///
/// GETNEXT retrieves the lexicographically next OID after the requested one.
/// This is the foundation of SNMP walking (iterating through MIB subtrees)
/// and is also used internally by GETBULK.
///
/// # Version differences
///
/// - **`SNMPv1`**: `EndOfMibView` results in a `noSuchName` error response
/// - **SNMPv2c/v3**: Returns the `endOfMibView` exception value in the response
///
/// # Lexicographic ordering
///
/// OIDs are compared arc-by-arc as unsigned integers:
/// - `1.3.6.1.2` < `1.3.6.1.2.1` (shorter is less than longer with same prefix)
/// - `1.3.6.1.2.1` < `1.3.6.1.3` (compare at first differing arc)
/// - `1.3.6.1.10` > `1.3.6.1.9` (numeric comparison, not lexicographic string)
///
/// # Example
///
/// ```rust
/// use async_snmp::handler::GetNextResult;
/// use async_snmp::{Value, VarBind, Oid, oid};
///
/// struct SimpleTable {
/// oids: Vec<(Oid, Value)>, // Must be sorted!
/// }
///
/// impl SimpleTable {
/// fn get_next(&self, after: &Oid) -> GetNextResult {
/// // Find first OID that is strictly greater than 'after'
/// for (oid, value) in &self.oids {
/// if oid > after {
/// return GetNextResult::Value(VarBind::new(oid.clone(), value.clone()));
/// }
/// }
/// GetNextResult::EndOfMibView
/// }
/// }
///
/// let table = SimpleTable {
/// oids: vec![
/// (oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), Value::OctetString("sysDescr".into())),
/// (oid!(1, 3, 6, 1, 2, 1, 1, 3, 0), Value::TimeTicks(12345)),
/// ],
/// };
///
/// // Before first OID - returns first
/// let result = table.get_next(&oid!(1, 3, 6, 1, 2, 1, 1, 0));
/// assert!(result.is_value());
///
/// // After last OID - returns EndOfMibView
/// let result = table.get_next(&oid!(1, 3, 6, 1, 2, 1, 1, 3, 0));
/// assert!(result.is_end_of_mib_view());
/// ```