mib-rs 0.10.0

SNMP MIB parser and resolver
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
//! ExtUTCTime date validation for MODULE-IDENTITY dates and revisions.
//!
//! Validates the `LAST-UPDATED` and `REVISION` date strings against the
//! ExtUTCTime format defined in RFC 2578. For vendor compatibility, 2-digit
//! years use a custom `00..69` → `2000..2069`, `70..99` → `1970..1999`
//! pivot. This is not conventional ASN.1 UTCTime interpretation or strict RFC
//! behavior; every 2-digit year still emits a diagnostic. Validation also
//! checks character validity, calendar validity, and chronological ordering,
//! and emits style warnings for dates outside the reasonable SMI range.

use crate::source::SourceRange;
use crate::types::DiagCode;

use super::LoweringContext;

/// Validates date formats and revision ordering for a MODULE-IDENTITY.
///
/// Checks each date for valid ExtUTCTime format, ensures revisions are
/// in reverse chronological order, and warns if any revision is after
/// LAST-UPDATED.
pub(super) fn check_module_identity_dates(
    ctx: &mut LoweringContext,
    last_updated: &str,
    last_updated_range: SourceRange,
    revision_dates: &[(String, SourceRange)],
) {
    let now = now_utc();

    let last_updated_time = check_date(ctx, last_updated, last_updated_range, now);

    // Validate each revision date and collect parsed times for ordering checks.
    let revs: Vec<(Option<DateComponents>, SourceRange)> = revision_dates
        .iter()
        .map(|(date, span)| (check_date(ctx, date, *span, now), *span))
        .collect();

    // Check revision ordering: must be reverse chronological (descending).
    for i in 1..revs.len() {
        if let (Some(prev), Some(curr)) = (&revs[i - 1].0, &revs[i].0)
            && curr >= prev
        {
            ctx.emit_diagnostic(
                DiagCode::RevisionNotDescending,
                revs[i].1,
                format!(
                    "revision {} is not in reverse chronological order",
                    revision_dates[i].0
                ),
            );
        }
    }

    // Check revision-after-update: no revision may exceed LAST-UPDATED.
    if let Some(last_updated_time) = &last_updated_time {
        for (i, rev) in revs.iter().enumerate() {
            if let Some(t) = &rev.0
                && t > last_updated_time
            {
                ctx.emit_diagnostic(
                    DiagCode::RevisionAfterUpdate,
                    rev.1,
                    format!(
                        "revision {} is after LAST-UPDATED {}",
                        revision_dates[i].0, last_updated
                    ),
                );
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct DateComponents {
    year: u32,
    month: u32,
    day: u32,
    hour: u32,
    min: u32,
}

/// Validates a single SMI date string (ExtUTCTime format).
/// Format: YYMMDDHHMMZ (11 chars) or YYYYMMDDHHMMZ (13 chars).
///
/// For vendor compatibility, 2-digit years use the custom pivot `00..69` →
/// `2000..2069` and `70..99` → `1970..1999`. This permissive interpretation is
/// not conventional ASN.1 UTCTime behavior and does not remove the
/// [`DiagCode::DateYear2Digits`] diagnostic.
fn check_date(
    ctx: &mut LoweringContext,
    date: &str,
    range: SourceRange,
    now: DateComponents,
) -> Option<DateComponents> {
    if date.is_empty() {
        return None;
    }

    let bytes = date.as_bytes();

    // Check length: must be 11 (2-digit year) or 13 (4-digit year).
    if bytes.len() != 11 && bytes.len() != 13 {
        ctx.emit_diagnostic(
            DiagCode::DateLength,
            range,
            format!(
                "date {:?} has illegal length {} (expected 11 or 13)",
                date,
                bytes.len()
            ),
        );
        return None;
    }

    // All characters before final must be digits, final must be 'Z'.
    for (i, &b) in bytes[..bytes.len() - 1].iter().enumerate() {
        if !b.is_ascii_digit() {
            ctx.emit_diagnostic(
                DiagCode::DateCharacter,
                range,
                format!(
                    "date {:?} contains illegal character at position {}",
                    date,
                    i + 1
                ),
            );
            return None;
        }
    }
    if bytes[bytes.len() - 1] != b'Z' {
        ctx.emit_diagnostic(
            DiagCode::DateCharacter,
            range,
            format!("date {:?} must end with 'Z'", date),
        );
        return None;
    }

    // Parse numeric components.
    let digit = |i: usize| -> u32 { (bytes[i] - b'0') as u32 };

    let (year, offset) = if bytes.len() == 11 {
        let yy = digit(0) * 10 + digit(1);
        let y = if yy >= 70 { 1900 + yy } else { 2000 + yy };
        ctx.emit_diagnostic(
            DiagCode::DateYear2Digits,
            range,
            format!("date {:?} uses 2-digit year representing {}", date, y),
        );
        (y, 2)
    } else {
        (
            digit(0) * 1000 + digit(1) * 100 + digit(2) * 10 + digit(3),
            4,
        )
    };

    let month = digit(offset) * 10 + digit(offset + 1);
    let day = digit(offset + 2) * 10 + digit(offset + 3);
    let hour = digit(offset + 4) * 10 + digit(offset + 5);
    let min = digit(offset + 6) * 10 + digit(offset + 7);

    // Validate ranges.
    if !(1..=12).contains(&month) {
        ctx.emit_diagnostic(
            DiagCode::DateMonth,
            range,
            format!("date {:?} has illegal month {:02}", date, month),
        );
        return None;
    }
    if !(1..=31).contains(&day) {
        ctx.emit_diagnostic(
            DiagCode::DateDay,
            range,
            format!("date {:?} has illegal day {:02}", date, day),
        );
        return None;
    }
    if hour > 23 {
        ctx.emit_diagnostic(
            DiagCode::DateHour,
            range,
            format!("date {:?} has illegal hour {:02}", date, hour),
        );
        return None;
    }
    if min > 59 {
        ctx.emit_diagnostic(
            DiagCode::DateMinutes,
            range,
            format!("date {:?} has illegal minutes {:02}", date, min),
        );
        return None;
    }

    // Check calendar validity (e.g. Feb 30 is not valid).
    if !is_valid_date(year, month, day) {
        ctx.emit_diagnostic(
            DiagCode::DateValue,
            range,
            format!("date {:?} is not a valid calendar date", date),
        );
        return None;
    }

    let dc = DateComponents {
        year,
        month,
        day,
        hour,
        min,
    };

    // Style warnings for dates outside reasonable range.
    // SMI epoch is Jan 1, 1990.
    let smi_epoch = DateComponents {
        year: 1990,
        month: 1,
        day: 1,
        hour: 0,
        min: 0,
    };
    if dc < smi_epoch {
        ctx.emit_diagnostic(
            DiagCode::DateInPast,
            range,
            format!("date {:?} predates the SMI standard", date),
        );
    }
    if dc > now {
        ctx.emit_diagnostic(
            DiagCode::DateInFuture,
            range,
            format!("date {:?} is in the future", date),
        );
    }

    Some(dc)
}

fn is_leap_year(year: u32) -> bool {
    (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400)
}

fn days_in_month(year: u32, month: u32) -> u32 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => {
            if is_leap_year(year) {
                29
            } else {
                28
            }
        }
        _ => 0,
    }
}

fn is_valid_date(year: u32, month: u32, day: u32) -> bool {
    day <= days_in_month(year, month)
}

fn now_utc() -> DateComponents {
    // Use a simple approach: parse current time from SystemTime.
    // We only need year/month/day/hour/min.
    use std::time::{SystemTime, UNIX_EPOCH};

    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    // Convert seconds since epoch to date components.
    let days = secs / 86400;
    let time_of_day = secs % 86400;
    let hour = (time_of_day / 3600) as u32;
    let min = ((time_of_day % 3600) / 60) as u32;

    // Civil date from days since 1970-01-01 (algorithm from Howard Hinnant).
    let z = days as i64 + 719468;
    let era = if z >= 0 { z } else { z - 146096 } / 146097;
    let doe = (z - era * 146097) as u32;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = if m <= 2 { y + 1 } else { y };

    DateComponents {
        year: year as u32,
        month: m,
        day: d,
        hour,
        min,
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use crate::source::{SourceOrigin, SourceSet};
    use crate::types::DiagnosticConfig;

    #[test]
    fn valid_dates() {
        assert!(is_valid_date(2024, 2, 29)); // leap year
        assert!(!is_valid_date(2023, 2, 29)); // not leap year
        assert!(is_valid_date(2023, 12, 31));
        assert!(!is_valid_date(2023, 4, 31));
    }

    fn with_context<T>(
        config: &DiagnosticConfig,
        f: impl FnOnce(&mut LoweringContext<'_>, SourceRange) -> T,
    ) -> T {
        let mut sources = SourceSet::new();
        let source_id = sources
            .insert(
                SourceOrigin::memory("date-test"),
                "date-test",
                Arc::from(&b""[..]),
            )
            .unwrap();
        let document = sources.get(source_id).unwrap();
        let range = document.empty_range(0).unwrap();
        let mut context = LoweringContext::new(document, config);
        f(&mut context, range)
    }

    fn far_future() -> DateComponents {
        DateComponents {
            year: 2099,
            month: 12,
            day: 31,
            hour: 23,
            min: 59,
        }
    }

    #[test]
    fn two_digit_year_post_2000() {
        let config = DiagnosticConfig::verbose();
        with_context(&config, |ctx, range| {
            let dc = check_date(ctx, "0501010000Z", range, far_future());
            assert_eq!(dc.unwrap().year, 2005);
            // The diagnostic message should mention 2005, not 1905.
            let diag = ctx
                .diagnostics
                .iter()
                .find(|d| d.code == DiagCode::DateYear2Digits)
                .expect("expected DateYear2Digits diagnostic");
            assert!(
                diag.message.contains("2005"),
                "expected 2005 in message: {}",
                diag.message
            );
        });
    }

    #[test]
    fn two_digit_year_boundary() {
        let config = DiagnosticConfig::verbose();

        for (date, expected_year) in [("6901010000Z", 2069), ("7001010000Z", 1970)] {
            with_context(&config, |ctx, range| {
                let dc = check_date(ctx, date, range, far_future());
                assert_eq!(dc.unwrap().year, expected_year);

                let diag = ctx
                    .diagnostics
                    .iter()
                    .find(|d| d.code == DiagCode::DateYear2Digits)
                    .expect("expected DateYear2Digits diagnostic");
                assert!(
                    diag.message.contains(&expected_year.to_string()),
                    "expected {expected_year} in message: {}",
                    diag.message
                );
            });
        }
    }

    #[test]
    fn two_digit_year_high() {
        let config = DiagnosticConfig::default();
        with_context(&config, |ctx, range| {
            let dc = check_date(ctx, "9901010000Z", range, far_future());
            assert_eq!(dc.unwrap().year, 1999);
        });
    }

    #[test]
    fn date_comparison() {
        let d1 = DateComponents {
            year: 2020,
            month: 1,
            day: 1,
            hour: 0,
            min: 0,
        };
        let d2 = DateComponents {
            year: 2021,
            month: 1,
            day: 1,
            hour: 0,
            min: 0,
        };
        assert!(d1 < d2);
        assert!(d2 > d1);
        assert!(d1 <= d2);
    }
}