cmtraceopen-parser 0.1.1

Parse ConfigMgr/SCCM, Intune, CBS, DISM, Panther, MSI, and PSADT logs with format auto-detection, severity classification, and Windows error-code lookup. Pure Rust, no I/O, native + wasm32.
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
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
pub mod burn;
pub mod cbs;
pub mod ccm;
pub mod cmtlog;
pub mod detect;
pub mod dhcp;
pub mod dism;
pub mod dns_debug;
pub mod dns_types;
pub mod iis_w3c;
pub mod intune_macos;
pub mod msi;
pub mod panther;
pub mod patchmypc_detection;
pub mod plain;
pub mod psadt;
pub mod registry;
pub mod reporting_events;
pub mod secureboot_log;
pub mod severity;
pub mod simple;
pub mod timestamped;

use crate::models::log_entry::{LogEntry, ParseResult};
use std::path::Path;

/// Post-process parsed entries to detect error code spans in messages.
pub fn annotate_error_code_spans(entries: &mut [LogEntry]) {
    for entry in entries.iter_mut() {
        let spans = crate::error_db::lookup::detect_error_code_spans(&entry.message);
        if !spans.is_empty() {
            entry.error_code_spans = spans;
        }
    }
}

pub use detect::ResolvedParser;

/// Result of parsing a single batch of records with a preselected parser.
pub struct ParsedChunk {
    pub entries: Vec<LogEntry>,
    pub total_lines: u32,
    pub parse_errors: u32,
}

/// Parse log content that has already been read into memory, auto-detecting its format.
///
/// `file_path` is used only for display/provenance and by format detection heuristics
/// (e.g. extension-based hints) — no filesystem I/O is performed. `file_size` is the
/// source file size in bytes and is passed through to `ParseResult`; callers that do
/// not have a source file (e.g. pasted content) may pass `content.len() as u64`.
///
/// Native-only concerns (reading file bytes, decoding EVTX event logs, etc.) live in
/// the src-tauri parser shim on top of this pure entry point.
pub fn parse_content(
    content: &str,
    file_path: &str,
    file_size: u64,
) -> (ParseResult, ResolvedParser) {
    let path_obj = Path::new(file_path);
    let selection = detect::detect_parser(file_path, content);
    let parsed_chunk = parse_content_with_selection(content, file_path, &selection);

    let result = ParseResult {
        entries: parsed_chunk.entries,
        format_detected: selection.compatibility_format(),
        parser_selection: selection.to_info(),
        total_lines: parsed_chunk.total_lines,
        parse_errors: parsed_chunk.parse_errors,
        file_path: path_obj.to_string_lossy().to_string(),
        file_size,
        byte_offset: file_size,
    };

    (result, selection)
}

/// Parse already-split lines using the backend-owned parser selection.
pub fn parse_lines_with_selection(
    lines: &[&str],
    file_path: &str,
    selection: &ResolvedParser,
) -> (Vec<LogEntry>, u32) {
    let (mut entries, parse_errors) = match selection.implementation {
        crate::models::log_entry::ParserImplementation::Ccm => {
            ccm::parse_lines_with_specialization(lines, file_path, selection.specialization)
        }
        crate::models::log_entry::ParserImplementation::Simple => {
            simple::parse_lines(lines, file_path)
        }
        crate::models::log_entry::ParserImplementation::IisW3c => {
            iis_w3c::parse_lines(lines, file_path)
        }
        crate::models::log_entry::ParserImplementation::ReportingEvents => {
            reporting_events::parse_lines(lines, file_path)
        }
        crate::models::log_entry::ParserImplementation::PlainText => {
            plain::parse_lines(lines, file_path)
        }
        crate::models::log_entry::ParserImplementation::Msi => msi::parse_lines(lines, file_path),
        crate::models::log_entry::ParserImplementation::PsadtLegacy => {
            psadt::parse_lines(lines, file_path)
        }
        crate::models::log_entry::ParserImplementation::IntuneMacOs => {
            intune_macos::parse_lines(lines, file_path)
        }
        crate::models::log_entry::ParserImplementation::Dhcp => dhcp::parse_lines(lines, file_path),
        crate::models::log_entry::ParserImplementation::Burn => burn::parse_lines(lines, file_path),
        crate::models::log_entry::ParserImplementation::PatchMyPcDetection => {
            patchmypc_detection::parse_lines(lines, file_path)
        }
        crate::models::log_entry::ParserImplementation::Registry => {
            // Registry files are parsed via a dedicated IPC command, not the log pipeline.
            (vec![], 0)
        }
        crate::models::log_entry::ParserImplementation::SecureBootLog => {
            secureboot_log::parse_lines(lines, file_path)
        }
        crate::models::log_entry::ParserImplementation::DnsDebug => {
            dns_debug::parse_lines(lines, file_path, selection.date_order)
        }
        crate::models::log_entry::ParserImplementation::DnsAudit => {
            // EVTX files are parsed via the binary path in parse_file(), not the line-based pipeline.
            // SecureBootLog has its own dedicated IPC command; not routed through this pipeline.
            (vec![], 0)
        }
        crate::models::log_entry::ParserImplementation::CmtLog => {
            cmtlog::parse_lines(lines, file_path)
        }
        crate::models::log_entry::ParserImplementation::GenericTimestamped => {
            match selection.parser {
                crate::models::log_entry::ParserKind::Cbs => cbs::parse_lines(lines, file_path),
                crate::models::log_entry::ParserKind::Dism => dism::parse_lines(lines, file_path),
                crate::models::log_entry::ParserKind::Panther => {
                    panther::parse_lines(lines, file_path)
                }
                _ => timestamped::parse_lines(lines, file_path, selection.date_order),
            }
        }
    };
    annotate_error_code_spans(&mut entries);
    (entries, parse_errors)
}

/// Parse text content using the backend-owned parser selection.
pub fn parse_content_with_selection(
    content: &str,
    file_path: &str,
    selection: &ResolvedParser,
) -> ParsedChunk {
    let total_lines = content.lines().count() as u32;
    let (mut entries, parse_errors) = match selection.implementation {
        crate::models::log_entry::ParserImplementation::Ccm => {
            ccm::parse_content(content, file_path, selection.specialization)
        }
        _ => {
            let lines: Vec<&str> = content.lines().collect();
            parse_lines_with_selection(&lines, file_path, selection)
        }
    };
    // For CCM content path (which doesn't go through parse_lines_with_selection),
    // ensure error code spans are annotated.
    if matches!(
        selection.implementation,
        crate::models::log_entry::ParserImplementation::Ccm
    ) {
        annotate_error_code_spans(&mut entries);
    }

    ParsedChunk {
        entries,
        total_lines,
        parse_errors,
    }
}

/// Encoding detected from file BOM, used for both initial read and tailing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileEncoding {
    Utf8,
    Utf16Le,
    Utf16Be,
}

/// Detect encoding from the leading bytes of a file.
pub fn detect_encoding(bytes: &[u8]) -> FileEncoding {
    if bytes.starts_with(&[0xFF, 0xFE]) {
        FileEncoding::Utf16Le
    } else if bytes.starts_with(&[0xFE, 0xFF]) {
        FileEncoding::Utf16Be
    } else {
        FileEncoding::Utf8
    }
}

/// Decode raw bytes to a String based on the detected encoding.
/// For UTF-16, also normalizes CRLF to LF.
pub fn decode_bytes(bytes: &[u8], encoding: FileEncoding) -> Result<String, String> {
    match encoding {
        FileEncoding::Utf16Le => {
            let data = if bytes.starts_with(&[0xFF, 0xFE]) {
                &bytes[2..]
            } else {
                bytes
            };
            let (cow, _, had_errors) = encoding_rs::UTF_16LE.decode(data);
            if had_errors {
                log::warn!("Encoding errors during UTF-16LE decode");
            }
            Ok(cow.into_owned().replace("\r\n", "\n"))
        }
        FileEncoding::Utf16Be => {
            let data = if bytes.starts_with(&[0xFE, 0xFF]) {
                &bytes[2..]
            } else {
                bytes
            };
            let (cow, _, had_errors) = encoding_rs::UTF_16BE.decode(data);
            if had_errors {
                log::warn!("Encoding errors during UTF-16BE decode");
            }
            Ok(cow.into_owned().replace("\r\n", "\n"))
        }
        FileEncoding::Utf8 => {
            let bytes_no_bom = if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
                &bytes[3..]
            } else {
                bytes
            };
            match std::str::from_utf8(bytes_no_bom) {
                Ok(s) => Ok(s.to_string()),
                Err(_) => {
                    let (cow, _, had_errors) = encoding_rs::WINDOWS_1252.decode(bytes_no_bom);
                    if had_errors {
                        log::warn!("Encoding errors during Windows-1252 fallback decode");
                    }
                    Ok(cow.into_owned())
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::log_entry::{
        ParseQuality, ParserImplementation, ParserKind, ParserProvenance, ParserSpecialization,
        RecordFraming,
    };
    use crate::parser::timestamped::DateOrder;

    #[test]
    fn test_parse_lines_with_selection_uses_timestamp_date_order() {
        let selection = ResolvedParser::generic_timestamped(DateOrder::DayFirst);
        let lines = ["15/01/2024 08:00:00 Processing request"];

        let (entries, parse_errors) = parse_lines_with_selection(&lines, "sample.log", &selection);

        assert_eq!(parse_errors, 0);
        assert_eq!(entries.len(), 1);
        assert_eq!(
            entries[0].timestamp_display.as_deref(),
            Some("2024-01-15 08:00:00.000")
        );
    }

    #[test]
    fn test_parse_lines_with_selection_can_use_panther_selection() {
        let selection = ResolvedParser::new(
            ParserKind::Panther,
            ParserImplementation::GenericTimestamped,
            ParserProvenance::Dedicated,
            ParseQuality::SemiStructured,
            RecordFraming::LogicalRecord,
            DateOrder::MonthFirst,
            None,
        );
        let lines = ["2024-01-15 08:00:00, Info SP Setup complete"];

        let (entries, parse_errors) =
            parse_lines_with_selection(&lines, "setupact.log", &selection);

        assert_eq!(parse_errors, 0);
        assert_eq!(entries.len(), 1);
        assert_eq!(
            selection.compatibility_format(),
            crate::models::log_entry::LogFormat::Timestamped
        );
        assert_eq!(entries[0].message, "Setup complete");
        assert_eq!(entries[0].component.as_deref(), Some("SP"));
    }

    #[test]
    fn test_parse_lines_with_selection_can_use_cbs_selection() {
        let selection = ResolvedParser::new(
            ParserKind::Cbs,
            ParserImplementation::GenericTimestamped,
            ParserProvenance::Dedicated,
            ParseQuality::SemiStructured,
            RecordFraming::LogicalRecord,
            DateOrder::MonthFirst,
            None,
        );
        let lines = [
            "2024-01-15 08:00:00, Info                  CBS    Exec: Started servicing",
            "Continuation detail",
        ];

        let (entries, parse_errors) = parse_lines_with_selection(&lines, "CBS.log", &selection);

        assert_eq!(parse_errors, 0);
        assert_eq!(entries.len(), 1);
        assert_eq!(
            selection.compatibility_format(),
            crate::models::log_entry::LogFormat::Timestamped
        );
        assert_eq!(entries[0].component.as_deref(), Some("CBS"));
        assert_eq!(
            entries[0].message,
            "Exec: Started servicing\nContinuation detail"
        );
    }

    #[test]
    fn test_parse_lines_with_selection_can_use_dism_selection() {
        let selection = ResolvedParser::new(
            ParserKind::Dism,
            ParserImplementation::GenericTimestamped,
            ParserProvenance::Dedicated,
            ParseQuality::SemiStructured,
            RecordFraming::LogicalRecord,
            DateOrder::MonthFirst,
            None,
        );
        let lines = [
            "2024-01-15 08:00:00, Warning               DISM   DISM Package Manager: Retry needed",
            "Extra context",
        ];

        let (entries, parse_errors) = parse_lines_with_selection(&lines, "DISM.log", &selection);

        assert_eq!(parse_errors, 0);
        assert_eq!(entries.len(), 1);
        assert_eq!(
            selection.compatibility_format(),
            crate::models::log_entry::LogFormat::Timestamped
        );
        assert_eq!(entries[0].component.as_deref(), Some("DISM"));
        assert_eq!(
            entries[0].message,
            "DISM Package Manager: Retry needed\nExtra context"
        );
    }

    #[test]
    fn test_parse_lines_with_selection_can_use_reporting_events_selection() {
        let selection = ResolvedParser::new(
            ParserKind::ReportingEvents,
            ParserImplementation::ReportingEvents,
            ParserProvenance::Dedicated,
            ParseQuality::Structured,
            RecordFraming::PhysicalLine,
            DateOrder::MonthFirst,
            None,
        );
        let lines = [
            "{11111111-1111-1111-1111-111111111111}\t2024-01-15 08:00:00:123\t1\tSoftware Update\t3\t{22222222-2222-2222-2222-222222222222}\t0x80240022\tWindows Update Agent\tFailure\tInstallation\tInstallation failed for KB5034123",
        ];

        let (entries, parse_errors) =
            parse_lines_with_selection(&lines, "ReportingEvents.log", &selection);

        assert_eq!(parse_errors, 0);
        assert_eq!(entries.len(), 1);
        assert_eq!(
            selection.compatibility_format(),
            crate::models::log_entry::LogFormat::Timestamped
        );
        assert_eq!(
            entries[0].component.as_deref(),
            Some("Windows Update Agent")
        );
        assert_eq!(
            entries[0].severity,
            crate::models::log_entry::Severity::Error
        );
    }

    #[test]
    fn test_parse_lines_with_selection_can_use_ime_specialization() {
        let selection = ResolvedParser::new(
            ParserKind::Ccm,
            ParserImplementation::Ccm,
            ParserProvenance::Dedicated,
            ParseQuality::Structured,
            RecordFraming::LogicalRecord,
            DateOrder::MonthFirst,
            Some(ParserSpecialization::Ime),
        );
        let lines = [
            r#"<![LOG[Powershell execution is done, exitCode = 1]LOG]!><time="11:16:37.3093207" date="3-12-2026" component="HealthScripts" context="" type="1" thread="50" file="">"#,
            r#"<![LOG[[HS] err output = Downloaded profile payload is not valid JSON."#,
            r#"At C:\Windows\IMECache\HealthScripts\script.ps1:457 char:9"#,
            r#"]LOG]!><time="11:16:42.3322734" date="3-12-2026" component="HealthScripts" context="" type="1" thread="50" file="">"#,
        ];

        let (entries, parse_errors) =
            parse_lines_with_selection(&lines, "HealthScripts.log", &selection);

        assert_eq!(parse_errors, 0);
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].line_number, 1);
        assert_eq!(entries[1].line_number, 2);
        assert!(entries[1]
            .message
            .contains("Downloaded profile payload is not valid JSON"));
        assert!(entries[1]
            .message
            .contains("At C:\\Windows\\IMECache\\HealthScripts\\script.ps1:457 char:9"));
    }

    #[test]
    fn test_parse_content_with_selection_can_use_ime_specialization() {
        let selection = ResolvedParser::new(
            ParserKind::Ccm,
            ParserImplementation::Ccm,
            ParserProvenance::Dedicated,
            ParseQuality::Structured,
            RecordFraming::LogicalRecord,
            DateOrder::MonthFirst,
            Some(ParserSpecialization::Ime),
        );
        let content = concat!(
            "<![LOG[Client Health evaluation starts.]LOG]!><time=\"23:00:10.6893636\" date=\"11-12-2025\" component=\"ClientHealth\" context=\"\" type=\"1\" thread=\"1\" file=\"\">\n",
            "<![LOG[Set MdmDeviceCertificate : 3788C1E384FDCB3F173A3222CB4191883A94224E\n",
            "More detail]LOG]!><time=\"23:00:11.4573058\" date=\"11-12-2025\" component=\"ClientHealth\" context=\"\" type=\"3\" thread=\"1\" file=\"\">"
        );

        let parsed = parse_content_with_selection(content, "ClientHealth.log", &selection);

        assert_eq!(parsed.total_lines, 3);
        assert_eq!(parsed.parse_errors, 0);
        assert_eq!(parsed.entries.len(), 2);
        assert_eq!(
            parsed.entries[0].format,
            crate::models::log_entry::LogFormat::Ccm
        );
        assert_eq!(parsed.entries[1].line_number, 2);
        assert_eq!(
            parsed.entries[1].severity,
            crate::models::log_entry::Severity::Error
        );
        assert!(parsed.entries[1].message.contains("More detail"));
    }

    #[test]
    fn test_parse_content_with_selection_keeps_non_ime_ccm_physical_line_behavior() {
        let selection = ResolvedParser::ccm();
        let content = concat!(
            "<![LOG[Normal CCM record]LOG]!><time=\"08:00:00.000+000\" date=\"01-01-2024\" component=\"Test\" context=\"\" type=\"1\" thread=\"100\" file=\"\">\n",
            "Continuation that should remain a plain fallback line"
        );

        let parsed = parse_content_with_selection(content, "sample.log", &selection);

        assert_eq!(parsed.total_lines, 2);
        assert_eq!(parsed.parse_errors, 1);
        assert_eq!(parsed.entries.len(), 2);
        assert_eq!(
            parsed.entries[0].format,
            crate::models::log_entry::LogFormat::Ccm
        );
        assert_eq!(
            parsed.entries[1].format,
            crate::models::log_entry::LogFormat::Plain
        );
        assert_eq!(parsed.entries[1].line_number, 2);
    }

    #[test]
    fn test_parsed_entries_have_error_spans() {
        let content = r#"<![LOG[Installation failed with error 0x80070005 access denied]LOG]!><time="10:00:00.000+000" date="01-01-2024" component="TestComp" context="" type="3" thread="1234" file="">"#;
        let selection = ResolvedParser::ccm();
        let parsed = parse_content_with_selection(content, "test.log", &selection);
        assert_eq!(parsed.entries.len(), 1);
        assert!(!parsed.entries[0].error_code_spans.is_empty());
        assert_eq!(parsed.entries[0].error_code_spans[0].code_hex, "0x80070005");
    }

    #[test]
    fn test_parse_lines_with_dns_debug_selection() {
        let selection = ResolvedParser::dns_debug(DateOrder::MonthFirst);
        let lines = [
            "4/11/2026 3:29:17 PM 0294 PACKET  000002DAEC36D650 UDP Rcv 127.0.0.1       d07e   Q [0001   D   NOERROR] SOA    (4)home(4)gell(3)one(0)",
            "4/11/2026 3:29:17 PM 0294 PACKET  000002DAEC36D650 UDP Snd 127.0.0.1       d07e R Q [8085 A DR  NOERROR] SOA    (4)home(4)gell(3)one(0)",
        ];

        let (entries, parse_errors) = parse_lines_with_selection(&lines, "dns.log", &selection);

        assert_eq!(parse_errors, 0);
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].query_name.as_deref(), Some("home.gell.one"));
        assert_eq!(
            entries[0].format,
            crate::models::log_entry::LogFormat::DnsDebug
        );
    }
}