Skip to main content

cmtraceopen_parser/parser/
msi.rs

1//! MSI verbose log parser.
2//!
3//! Parses Windows Installer verbose log output generated by `msiexec /l*v`.
4//!
5//! Recognized line patterns:
6//! - Engine messages: `MSI (c) (PID:TID) [HH:MM:SS:mmm]: message`
7//! - Header/footer: `=== Verbose logging started/stopped: ... ===`
8//! - Action start/ended/top-level: `Action start HH:MM:SS: ActionName.`
9//! - Property dumps: `Property(C): Name = Value`
10//! - MainEngineThread return: `MainEngineThread is returning NNNN`
11//! - Plain text fallback for unrecognized lines
12
13use chrono::{Datelike, NaiveDate, Timelike};
14use regex::Regex;
15
16use super::severity::detect_severity_from_text;
17use crate::models::log_entry::{LogEntry, LogFormat, Severity};
18use std::sync::OnceLock;
19
20// ---------------------------------------------------------------------------
21// Compiled regexes
22// ---------------------------------------------------------------------------
23
24/// Engine message: MSI (c) (8C:98) [07:42:28:452]: message text
25fn engine_re() -> &'static Regex {
26    static CELL: OnceLock<Regex> = OnceLock::new();
27    CELL.get_or_init(|| {
28    Regex::new(
29        r"^MSI\s+\(([csaN])\)\s+\(([0-9A-Fa-f]+):([0-9A-Fa-f]+)\)\s+\[(\d{2}):(\d{2}):(\d{2}):(\d{3})\]:\s+(.*)$",
30    )
31    .expect("MSI engine regex must compile")
32})
33}
34
35/// Header: === Verbose logging started: M/D/YYYY  H:MM:SS  Build type: ... ===
36fn header_re() -> &'static Regex {
37    static CELL: OnceLock<Regex> = OnceLock::new();
38    CELL.get_or_init(|| {
39    Regex::new(
40        r"^===\s+(?:Verbose\s+)?[Ll]ogging\s+started:\s+(\d{1,2}/\d{1,2}/\d{4})\s+(\d{1,2}:\d{2}:\d{2})\s+(.*)===\s*$",
41    )
42    .expect("MSI header regex must compile")
43})
44}
45
46/// Footer: === Verbose logging stopped: ... ===
47fn footer_re() -> &'static Regex {
48    static CELL: OnceLock<Regex> = OnceLock::new();
49    CELL.get_or_init(|| {
50        Regex::new(r"^===\s+(?:Verbose\s+)?[Ll]ogging\s+stopped:\s+.*===\s*$")
51            .expect("MSI footer regex must compile")
52    })
53}
54
55/// Action start: Action start 16:34:29: InstallFiles.
56fn action_start_re() -> &'static Regex {
57    static CELL: OnceLock<Regex> = OnceLock::new();
58    CELL.get_or_init(|| {
59        Regex::new(r"^Action start (\d{1,2}):(\d{2}):(\d{2}):\s+(\w+)\.\s*$")
60            .expect("MSI action start regex must compile")
61    })
62}
63
64/// Action ended: Action ended 16:34:29: InstallFiles. Return value 1.
65fn action_ended_re() -> &'static Regex {
66    static CELL: OnceLock<Regex> = OnceLock::new();
67    CELL.get_or_init(|| {
68        Regex::new(r"^Action ended (\d{1,2}):(\d{2}):(\d{2}):\s+(\w+)\.\s+Return value (\d+)\.\s*$")
69            .expect("MSI action ended regex must compile")
70    })
71}
72
73/// Top-level action: Action 16:34:29: INSTALL.
74fn action_top_re() -> &'static Regex {
75    static CELL: OnceLock<Regex> = OnceLock::new();
76    CELL.get_or_init(|| {
77        Regex::new(r"^Action (\d{1,2}):(\d{2}):(\d{2}):\s+(\w+)\.\s*$")
78            .expect("MSI top-level action regex must compile")
79    })
80}
81
82/// Property dump: Property(C): ProductCode = {GUID}
83fn property_re() -> &'static Regex {
84    static CELL: OnceLock<Regex> = OnceLock::new();
85    CELL.get_or_init(|| {
86        Regex::new(r"^Property\([CScs]\):\s+(.*)$").expect("MSI property regex must compile")
87    })
88}
89
90/// MainEngineThread return: MainEngineThread is returning 1603
91fn main_engine_return_re() -> &'static Regex {
92    static CELL: OnceLock<Regex> = OnceLock::new();
93    CELL.get_or_init(|| {
94        Regex::new(r"^MainEngineThread is returning (\d+)")
95            .expect("MSI MainEngineThread regex must compile")
96    })
97}
98
99/// Note error code pattern: Note: 1: NNNN
100fn note_error_re() -> &'static Regex {
101    static CELL: OnceLock<Regex> = OnceLock::new();
102    CELL.get_or_init(|| {
103        Regex::new(r"Note:\s+1:\s+(\d+)").expect("MSI note error regex must compile")
104    })
105}
106
107// ---------------------------------------------------------------------------
108// Detection helper (used by detect.rs)
109// ---------------------------------------------------------------------------
110
111/// Returns a weight indicating how likely this line is from an MSI verbose log.
112/// Higher weight = stronger signal.
113pub fn matches_msi_content(line: &str) -> u32 {
114    let trimmed = line.trim();
115
116    if trimmed.starts_with("=== Verbose logging started:")
117        || trimmed.starts_with("=== Logging started:")
118        || trimmed.starts_with("=== verbose logging started:")
119        || trimmed.starts_with("=== logging started:")
120    {
121        return 3;
122    }
123
124    if trimmed.starts_with("MSI (c)")
125        || trimmed.starts_with("MSI (s)")
126        || trimmed.starts_with("MSI (a)")
127        || trimmed.starts_with("MSI (N)")
128    {
129        return 2;
130    }
131
132    if trimmed.starts_with("MainEngineThread is returning") {
133        return 2;
134    }
135
136    if action_start_re().is_match(trimmed) || action_ended_re().is_match(trimmed) {
137        return 1;
138    }
139
140    if trimmed.starts_with("Property(S):") || trimmed.starts_with("Property(C):") {
141        return 1;
142    }
143
144    0
145}
146
147// ---------------------------------------------------------------------------
148// Parser state
149// ---------------------------------------------------------------------------
150
151/// Mutable state carried across lines during parsing.
152struct MsiParserState {
153    /// Date extracted from the header line, applied to subsequent time-only entries.
154    current_date: Option<NaiveDate>,
155    /// Previous time-of-day in seconds, used for midnight rollover detection.
156    prev_time_secs: Option<u32>,
157}
158
159impl MsiParserState {
160    fn new() -> Self {
161        Self {
162            current_date: None,
163            prev_time_secs: None,
164        }
165    }
166
167    /// Update date state, detecting midnight rollover.
168    /// Returns the date to use for this entry's timestamp.
169    fn advance_time(&mut self, h: u32, m: u32, s: u32) -> Option<NaiveDate> {
170        let current_secs = h * 3600 + m * 60 + s;
171
172        if let Some(prev_secs) = self.prev_time_secs {
173            // If time jumped back by more than 23 hours, assume midnight rollover
174            if current_secs < prev_secs && (prev_secs - current_secs) > 82800 {
175                if let Some(date) = self.current_date {
176                    self.current_date = date.succ_opt();
177                }
178            }
179        }
180        self.prev_time_secs = Some(current_secs);
181
182        self.current_date
183    }
184}
185
186// ---------------------------------------------------------------------------
187// Public parse entry point
188// ---------------------------------------------------------------------------
189
190/// Parse all lines as MSI verbose log format.
191pub fn parse_lines(lines: &[&str], file_path: &str) -> (Vec<LogEntry>, u32) {
192    let mut entries = Vec::with_capacity(lines.len());
193    let mut errors = 0u32;
194    let mut id_counter = 0u64;
195    let mut state = MsiParserState::new();
196
197    for (i, line) in lines.iter().enumerate() {
198        if line.trim().is_empty() {
199            continue;
200        }
201
202        let entry = parse_msi_line(line, file_path, &mut state, id_counter, (i + 1) as u32);
203        let is_fallback = entry.component.is_none()
204            && entry.timestamp.is_none()
205            && !footer_re().is_match(line.trim());
206
207        entries.push(entry);
208
209        if is_fallback {
210            errors += 1;
211        }
212
213        id_counter += 1;
214    }
215
216    (entries, errors)
217}
218
219// ---------------------------------------------------------------------------
220// Line-level parsing
221// ---------------------------------------------------------------------------
222
223fn parse_msi_line(
224    line: &str,
225    file_path: &str,
226    state: &mut MsiParserState,
227    id: u64,
228    line_number: u32,
229) -> LogEntry {
230    let trimmed = line.trim_end();
231
232    // 1. Header line
233    if let Some(caps) = header_re().captures(trimmed) {
234        return parse_header(caps, file_path, state, id, line_number, trimmed);
235    }
236
237    // 2. Footer line
238    if footer_re().is_match(trimmed) {
239        return make_entry(
240            id,
241            line_number,
242            trimmed.to_string(),
243            Some("MSI-header".to_string()),
244            None,
245            None,
246            Severity::Info,
247            None,
248            None,
249            file_path,
250        );
251    }
252
253    // 3. Engine message
254    if let Some(caps) = engine_re().captures(trimmed) {
255        return parse_engine(caps, file_path, state, id, line_number);
256    }
257
258    // 4. Action ended (check before action start — "ended" is more specific)
259    if let Some(caps) = action_ended_re().captures(trimmed) {
260        return parse_action_ended(caps, file_path, state, id, line_number, trimmed);
261    }
262
263    // 5. Action start
264    if let Some(caps) = action_start_re().captures(trimmed) {
265        return parse_action_start(caps, file_path, state, id, line_number, trimmed);
266    }
267
268    // 6. Top-level action
269    if let Some(caps) = action_top_re().captures(trimmed) {
270        return parse_action_top(caps, file_path, state, id, line_number, trimmed);
271    }
272
273    // 7. Property dump
274    if let Some(caps) = property_re().captures(trimmed) {
275        return make_entry(
276            id,
277            line_number,
278            caps.get(1).map_or("", |m| m.as_str()).to_string(),
279            Some("MSI-properties".to_string()),
280            None,
281            None,
282            Severity::Info,
283            None,
284            None,
285            file_path,
286        );
287    }
288
289    // 8. MainEngineThread return
290    if let Some(caps) = main_engine_return_re().captures(trimmed) {
291        let code: u32 = caps
292            .get(1)
293            .and_then(|m| m.as_str().parse().ok())
294            .unwrap_or(0);
295        let severity = severity_from_msi_exit_code(code);
296        return make_entry(
297            id,
298            line_number,
299            trimmed.to_string(),
300            Some("MSI-engine".to_string()),
301            None,
302            None,
303            severity,
304            None,
305            None,
306            file_path,
307        );
308    }
309
310    // 9. Fallback — plain text with keyword-based severity
311    let severity = msi_text_severity(trimmed);
312    make_entry(
313        id,
314        line_number,
315        trimmed.to_string(),
316        None,
317        None,
318        None,
319        severity,
320        None,
321        None,
322        file_path,
323    )
324}
325
326// ---------------------------------------------------------------------------
327// Per-pattern parsers
328// ---------------------------------------------------------------------------
329
330fn parse_header(
331    caps: regex::Captures,
332    file_path: &str,
333    state: &mut MsiParserState,
334    id: u64,
335    line_number: u32,
336    raw: &str,
337) -> LogEntry {
338    // Extract date: M/D/YYYY
339    let date_str = caps.get(1).map(|m| m.as_str()).unwrap_or("");
340    let time_str = caps.get(2).map(|m| m.as_str()).unwrap_or("");
341
342    let parsed_date = parse_us_date(date_str);
343    if let Some(d) = parsed_date {
344        state.current_date = Some(d);
345    }
346
347    // Parse time H:MM:SS
348    let time_parts: Vec<u32> = time_str.split(':').filter_map(|p| p.parse().ok()).collect();
349    let (h, m, s) = if time_parts.len() == 3 {
350        (time_parts[0], time_parts[1], time_parts[2])
351    } else {
352        (0, 0, 0)
353    };
354
355    let (timestamp, timestamp_display) = if let Some(date) = parsed_date {
356        build_timestamp(date, h, m, s, 0)
357    } else {
358        (None, None)
359    };
360
361    if time_parts.len() == 3 {
362        state.prev_time_secs = Some(h * 3600 + m * 60 + s);
363    }
364
365    make_entry(
366        id,
367        line_number,
368        raw.to_string(),
369        Some("MSI-header".to_string()),
370        timestamp,
371        timestamp_display,
372        Severity::Info,
373        None,
374        None,
375        file_path,
376    )
377}
378
379fn parse_engine(
380    caps: regex::Captures,
381    file_path: &str,
382    state: &mut MsiParserState,
383    id: u64,
384    line_number: u32,
385) -> LogEntry {
386    let context_char = caps.get(1).map(|m| m.as_str()).unwrap_or("c");
387    let pid_hex = caps.get(2).map(|m| m.as_str()).unwrap_or("0");
388    let tid_hex = caps.get(3).map(|m| m.as_str()).unwrap_or("0");
389    let h: u32 = caps
390        .get(4)
391        .and_then(|m| m.as_str().parse().ok())
392        .unwrap_or(0);
393    let m: u32 = caps
394        .get(5)
395        .and_then(|m| m.as_str().parse().ok())
396        .unwrap_or(0);
397    let s: u32 = caps
398        .get(6)
399        .and_then(|m| m.as_str().parse().ok())
400        .unwrap_or(0);
401    let ms: u32 = caps
402        .get(7)
403        .and_then(|m| m.as_str().parse().ok())
404        .unwrap_or(0);
405    let message = caps.get(8).map(|m| m.as_str()).unwrap_or("").to_string();
406
407    let component = match context_char {
408        "c" => "MSI-client",
409        "s" => "MSI-server",
410        "a" => "MSI-action",
411        "N" => "MSI-nested",
412        _ => "MSI-client",
413    }
414    .to_string();
415
416    let thread_num = u32::from_str_radix(tid_hex, 16).ok();
417    let thread_display = Some(format!("{}:{}", pid_hex, tid_hex));
418
419    let date = state.advance_time(h, m, s);
420    let (timestamp, timestamp_display) = if let Some(d) = date {
421        build_timestamp(d, h, m, s, ms)
422    } else {
423        (None, Some(format!("{:02}:{:02}:{:02}.{:03}", h, m, s, ms)))
424    };
425
426    // Severity: check MainEngineThread return in message, note error codes, keyword patterns
427    let severity = determine_engine_severity(&message);
428
429    make_entry(
430        id,
431        line_number,
432        message,
433        Some(component),
434        timestamp,
435        timestamp_display,
436        severity,
437        thread_num,
438        thread_display,
439        file_path,
440    )
441}
442
443fn parse_action_start(
444    caps: regex::Captures,
445    file_path: &str,
446    state: &mut MsiParserState,
447    id: u64,
448    line_number: u32,
449    raw: &str,
450) -> LogEntry {
451    let h: u32 = caps
452        .get(1)
453        .and_then(|m| m.as_str().parse().ok())
454        .unwrap_or(0);
455    let m: u32 = caps
456        .get(2)
457        .and_then(|m| m.as_str().parse().ok())
458        .unwrap_or(0);
459    let s: u32 = caps
460        .get(3)
461        .and_then(|m| m.as_str().parse().ok())
462        .unwrap_or(0);
463    let action = caps.get(4).map(|m| m.as_str()).unwrap_or("Unknown");
464
465    let date = state.advance_time(h, m, s);
466    let (timestamp, timestamp_display) = if let Some(d) = date {
467        build_timestamp(d, h, m, s, 0)
468    } else {
469        (None, Some(format!("{:02}:{:02}:{:02}.000", h, m, s)))
470    };
471
472    make_entry(
473        id,
474        line_number,
475        raw.to_string(),
476        Some(action.to_string()),
477        timestamp,
478        timestamp_display,
479        Severity::Info,
480        None,
481        None,
482        file_path,
483    )
484}
485
486fn parse_action_ended(
487    caps: regex::Captures,
488    file_path: &str,
489    state: &mut MsiParserState,
490    id: u64,
491    line_number: u32,
492    raw: &str,
493) -> LogEntry {
494    let h: u32 = caps
495        .get(1)
496        .and_then(|m| m.as_str().parse().ok())
497        .unwrap_or(0);
498    let m: u32 = caps
499        .get(2)
500        .and_then(|m| m.as_str().parse().ok())
501        .unwrap_or(0);
502    let s: u32 = caps
503        .get(3)
504        .and_then(|m| m.as_str().parse().ok())
505        .unwrap_or(0);
506    let action = caps.get(4).map(|m| m.as_str()).unwrap_or("Unknown");
507    let return_val: u32 = caps
508        .get(5)
509        .and_then(|m| m.as_str().parse().ok())
510        .unwrap_or(0);
511
512    let date = state.advance_time(h, m, s);
513    let (timestamp, timestamp_display) = if let Some(d) = date {
514        build_timestamp(d, h, m, s, 0)
515    } else {
516        (None, Some(format!("{:02}:{:02}:{:02}.000", h, m, s)))
517    };
518
519    let severity = severity_from_action_return(return_val);
520
521    make_entry(
522        id,
523        line_number,
524        raw.to_string(),
525        Some(action.to_string()),
526        timestamp,
527        timestamp_display,
528        severity,
529        None,
530        None,
531        file_path,
532    )
533}
534
535fn parse_action_top(
536    caps: regex::Captures,
537    file_path: &str,
538    state: &mut MsiParserState,
539    id: u64,
540    line_number: u32,
541    raw: &str,
542) -> LogEntry {
543    let h: u32 = caps
544        .get(1)
545        .and_then(|m| m.as_str().parse().ok())
546        .unwrap_or(0);
547    let m: u32 = caps
548        .get(2)
549        .and_then(|m| m.as_str().parse().ok())
550        .unwrap_or(0);
551    let s: u32 = caps
552        .get(3)
553        .and_then(|m| m.as_str().parse().ok())
554        .unwrap_or(0);
555    let action = caps.get(4).map(|m| m.as_str()).unwrap_or("Unknown");
556
557    let date = state.advance_time(h, m, s);
558    let (timestamp, timestamp_display) = if let Some(d) = date {
559        build_timestamp(d, h, m, s, 0)
560    } else {
561        (None, Some(format!("{:02}:{:02}:{:02}.000", h, m, s)))
562    };
563
564    make_entry(
565        id,
566        line_number,
567        raw.to_string(),
568        Some(action.to_string()),
569        timestamp,
570        timestamp_display,
571        Severity::Info,
572        None,
573        None,
574        file_path,
575    )
576}
577
578// ---------------------------------------------------------------------------
579// Severity helpers
580// ---------------------------------------------------------------------------
581
582/// Determine severity for an engine message body.
583/// Priority: MainEngineThread return code > note error codes > keyword patterns > text fallback.
584fn determine_engine_severity(message: &str) -> Severity {
585    // Check for MainEngineThread return code embedded in message
586    if let Some(caps) = main_engine_return_re().captures(message) {
587        if let Some(code) = caps.get(1).and_then(|m| m.as_str().parse::<u32>().ok()) {
588            return severity_from_msi_exit_code(code);
589        }
590    }
591
592    // Check for Note: 1: NNNN error codes
593    if let Some(caps) = note_error_re().captures(message) {
594        if let Some(code) = caps.get(1).and_then(|m| m.as_str().parse::<u32>().ok()) {
595            // Common MSI note error codes that indicate real problems
596            if matches!(
597                code,
598                2318 | 2329
599                    | 2331
600                    | 2335
601                    | 2337
602                    | 2343
603                    | 2345
604                    | 2350
605                    | 2351
606                    | 2352
607                    | 2355
608                    | 2356
609                    | 2357
610                    | 2358
611                    | 2359
612                    | 2360
613                    | 2361
614                    | 2362
615                    | 2371
616                    | 2372
617                    | 2373
618                    | 2374
619                    | 2375
620                    | 2379
621                    | 2380
622                    | 2381
623                    | 2382
624            ) {
625                return Severity::Error;
626            }
627            // Most "Note: 1:" entries are informational in MSI logs
628            return Severity::Info;
629        }
630    }
631
632    // Keyword patterns specific to MSI logs
633    let lower = message.to_lowercase();
634    if lower.contains("installation failed")
635        || lower.contains("error status: 1603")
636        || lower.contains("error status: 1618")
637        || lower.contains("product: error")
638    {
639        return Severity::Error;
640    }
641
642    // General text-based fallback
643    detect_severity_from_text(message)
644}
645
646/// Map MSI exit/return codes to severity.
647fn severity_from_msi_exit_code(code: u32) -> Severity {
648    match code {
649        0 => Severity::Info,       // SUCCESS
650        1707 => Severity::Info,    // SUCCESS (alternate)
651        3010 => Severity::Info,    // SUCCESS_REBOOT_REQUIRED
652        1602 => Severity::Warning, // ERROR_INSTALL_USEREXIT
653        1618 => Severity::Error,   // ERROR_INSTALL_ALREADY_RUNNING
654        1603 => Severity::Error,   // ERROR_INSTALL_FAILURE
655        1604 => Severity::Error,   // ERROR_INSTALL_SUSPEND
656        1605 => Severity::Error,   // ERROR_UNKNOWN_PRODUCT
657        1610 => Severity::Error,   // ERROR_BAD_CONFIGURATION
658        1612 => Severity::Error,   // ERROR_INSTALL_SOURCE_ABSENT
659        1613 => Severity::Error,   // ERROR_INSTALL_PACKAGE_VERSION
660        1619 => Severity::Error,   // ERROR_INSTALL_PACKAGE_OPEN_FAILED
661        1620 => Severity::Error,   // ERROR_INSTALL_PACKAGE_INVALID
662        1622 => Severity::Error,   // ERROR_INSTALL_LOG_FAILURE
663        1623 => Severity::Error,   // ERROR_INSTALL_LANGUAGE_UNSUPPORTED
664        1624 => Severity::Error,   // ERROR_INSTALL_TRANSFORM_FAILURE
665        1625 => Severity::Warning, // ERROR_INSTALL_PACKAGE_REJECTED (policy)
666        1638 => Severity::Warning, // ERROR_PRODUCT_VERSION (another version installed)
667        _ => {
668            // Codes >= 1600 are generally MSI-specific errors
669            if (1600..1700).contains(&code) {
670                Severity::Error
671            } else {
672                Severity::Info
673            }
674        }
675    }
676}
677
678/// Map action "Return value" to severity.
679fn severity_from_action_return(code: u32) -> Severity {
680    match code {
681        0 => Severity::Info,    // Failure (but many logs use 0 as success)
682        1 => Severity::Info,    // Success
683        2 => Severity::Warning, // User cancel
684        3 => Severity::Error,   // Fatal error
685        4 => Severity::Warning, // Suspend
686        _ => Severity::Info,
687    }
688}
689
690/// MSI-specific text severity: check for known MSI patterns before general fallback.
691fn msi_text_severity(text: &str) -> Severity {
692    let lower = text.to_lowercase();
693    if lower.contains("installation failed") || lower.contains("error status: 1603") {
694        return Severity::Error;
695    }
696    detect_severity_from_text(text)
697}
698
699// ---------------------------------------------------------------------------
700// Timestamp and date utilities
701// ---------------------------------------------------------------------------
702
703/// Parse a US-format date string: M/D/YYYY
704fn parse_us_date(s: &str) -> Option<NaiveDate> {
705    let parts: Vec<&str> = s.split('/').collect();
706    if parts.len() != 3 {
707        return None;
708    }
709    let month: u32 = parts[0].parse().ok()?;
710    let day: u32 = parts[1].parse().ok()?;
711    let year: i32 = parts[2].parse().ok()?;
712    NaiveDate::from_ymd_opt(year, month, day)
713}
714
715/// Build unix-millis timestamp and display string from date + time components.
716fn build_timestamp(
717    date: NaiveDate,
718    h: u32,
719    m: u32,
720    s: u32,
721    ms: u32,
722) -> (Option<i64>, Option<String>) {
723    let dt = date.and_hms_milli_opt(h, m, s, ms);
724    let timestamp = dt.map(|ndt| ndt.and_utc().timestamp_millis());
725    let display = dt.map(|ndt| {
726        format!(
727            "{:02}-{:02}-{:04} {:02}:{:02}:{:02}.{:03}",
728            date.month(),
729            date.day(),
730            date.year(),
731            ndt.hour(),
732            ndt.minute(),
733            ndt.second(),
734            ms,
735        )
736    });
737    (timestamp, display)
738}
739
740// ---------------------------------------------------------------------------
741// LogEntry constructor
742// ---------------------------------------------------------------------------
743
744#[allow(clippy::too_many_arguments)]
745fn make_entry(
746    id: u64,
747    line_number: u32,
748    message: String,
749    component: Option<String>,
750    timestamp: Option<i64>,
751    timestamp_display: Option<String>,
752    severity: Severity,
753    thread: Option<u32>,
754    thread_display: Option<String>,
755    file_path: &str,
756) -> LogEntry {
757    LogEntry {
758        id,
759        line_number,
760        message,
761        component,
762        timestamp,
763        timestamp_display,
764        severity,
765        thread,
766        thread_display,
767        source_file: None,
768        format: LogFormat::Timestamped,
769        file_path: file_path.to_string(),
770        timezone_offset: None,
771        error_code_spans: Vec::new(),
772        ip_address: None,
773        host_name: None,
774        mac_address: None,
775        result_code: None,
776        gle_code: None,
777        setup_phase: None,
778        operation_name: None,
779        http_method: None,
780        uri_stem: None,
781        uri_query: None,
782        status_code: None,
783        sub_status: None,
784        time_taken_ms: None,
785        client_ip: None,
786        server_ip: None,
787        user_agent: None,
788        server_port: None,
789        username: None,
790        win32_status: None,
791        query_name: None,
792        query_type: None,
793        response_code: None,
794        dns_direction: None,
795        dns_protocol: None,
796        source_ip: None,
797        dns_flags: None,
798        dns_event_id: None,
799        zone_name: None,
800        entry_kind: None,
801        whatif: None,
802        section_name: None,
803        section_color: None,
804        iteration: None,
805        tags: None,
806    }
807}
808
809// ---------------------------------------------------------------------------
810// Tests
811// ---------------------------------------------------------------------------
812
813#[cfg(test)]
814mod tests {
815    use super::*;
816
817    // -- Detection weight tests --
818
819    #[test]
820    fn test_matches_header() {
821        assert_eq!(
822            matches_msi_content("=== Verbose logging started: 6/13/2023  9:02:46  Build type: SHIP UNICODE 5.00.10011.00  Calling process: ... ==="),
823            3
824        );
825    }
826
827    #[test]
828    fn test_matches_logging_started_variant() {
829        assert_eq!(
830            matches_msi_content("=== Logging started: 1/2/2024  10:00:00  Build type: SHIP ==="),
831            3
832        );
833    }
834
835    #[test]
836    fn test_matches_engine_client() {
837        assert_eq!(
838            matches_msi_content("MSI (c) (8C:98) [07:42:28:452]: Resetting cached policy values"),
839            2
840        );
841    }
842
843    #[test]
844    fn test_matches_engine_server() {
845        assert_eq!(
846            matches_msi_content("MSI (s) (8C:98) [07:42:28:452]: Running server"),
847            2
848        );
849    }
850
851    #[test]
852    fn test_matches_main_engine_thread() {
853        assert_eq!(matches_msi_content("MainEngineThread is returning 0"), 2);
854    }
855
856    #[test]
857    fn test_matches_action_start() {
858        assert_eq!(
859            matches_msi_content("Action start 16:34:29: InstallFiles."),
860            1
861        );
862    }
863
864    #[test]
865    fn test_matches_action_ended() {
866        assert_eq!(
867            matches_msi_content("Action ended 16:34:29: InstallFiles. Return value 1."),
868            1
869        );
870    }
871
872    #[test]
873    fn test_matches_property() {
874        assert_eq!(
875            matches_msi_content(
876                "Property(C): ProductCode = {C64CA371-0000-0000-0000-000000000000}"
877            ),
878            1
879        );
880    }
881
882    #[test]
883    fn test_matches_plain_text_zero() {
884        assert_eq!(matches_msi_content("Just some random text"), 0);
885    }
886
887    // -- Header parsing --
888
889    #[test]
890    fn test_parse_header_extracts_date() {
891        let lines = [
892            "=== Verbose logging started: 6/13/2023  9:02:46  Build type: SHIP UNICODE 5.00.10011.00  Calling process: C:\\Windows\\System32\\msiexec.exe ===",
893            "MSI (c) (8C:98) [09:02:46:452]: Resetting cached policy values",
894        ];
895
896        let (entries, errors) = parse_lines(&lines, "install.log");
897
898        assert_eq!(errors, 0);
899        assert_eq!(entries.len(), 2);
900
901        // Header entry
902        assert_eq!(entries[0].component.as_deref(), Some("MSI-header"));
903        assert_eq!(entries[0].severity, Severity::Info);
904        assert!(entries[0].timestamp.is_some());
905        assert_eq!(
906            entries[0].timestamp_display.as_deref(),
907            Some("06-13-2023 09:02:46.000")
908        );
909
910        // Engine entry inherits the date
911        assert_eq!(entries[1].component.as_deref(), Some("MSI-client"));
912        assert!(entries[1].timestamp.is_some());
913        assert_eq!(
914            entries[1].timestamp_display.as_deref(),
915            Some("06-13-2023 09:02:46.452")
916        );
917    }
918
919    // -- Engine message parsing --
920
921    #[test]
922    fn test_parse_engine_message() {
923        let lines = [
924            "=== Verbose logging started: 1/15/2024  7:42:28  Build type: SHIP ===",
925            "MSI (c) (8C:98) [07:42:28:452]: Resetting cached policy values",
926        ];
927
928        let (entries, _) = parse_lines(&lines, "test.log");
929
930        assert_eq!(entries[1].message, "Resetting cached policy values");
931        assert_eq!(entries[1].component.as_deref(), Some("MSI-client"));
932        assert_eq!(entries[1].thread_display.as_deref(), Some("8C:98"));
933        assert_eq!(entries[1].thread, Some(0x98));
934        assert_eq!(entries[1].severity, Severity::Info);
935    }
936
937    #[test]
938    fn test_parse_engine_server_context() {
939        let lines = ["MSI (s) (4A:B0) [10:00:00:000]: Server running"];
940
941        let (entries, _) = parse_lines(&lines, "test.log");
942
943        assert_eq!(entries[0].component.as_deref(), Some("MSI-server"));
944        assert_eq!(entries[0].thread_display.as_deref(), Some("4A:B0"));
945        assert_eq!(entries[0].thread, Some(0xB0));
946    }
947
948    #[test]
949    fn test_parse_engine_action_context() {
950        let lines = ["MSI (a) (4A:B0) [10:00:00:000]: Custom action started"];
951
952        let (entries, _) = parse_lines(&lines, "test.log");
953        assert_eq!(entries[0].component.as_deref(), Some("MSI-action"));
954    }
955
956    // -- Action lines --
957
958    #[test]
959    fn test_parse_action_start() {
960        let lines = [
961            "=== Verbose logging started: 1/1/2024  16:34:00  Build type: SHIP ===",
962            "Action start 16:34:29: InstallFiles.",
963        ];
964
965        let (entries, _) = parse_lines(&lines, "test.log");
966
967        assert_eq!(entries[1].component.as_deref(), Some("InstallFiles"));
968        assert_eq!(entries[1].severity, Severity::Info);
969        assert!(entries[1].timestamp.is_some());
970    }
971
972    #[test]
973    fn test_parse_action_ended_success() {
974        let lines = [
975            "=== Verbose logging started: 1/1/2024  16:34:00  Build type: SHIP ===",
976            "Action ended 16:34:29: InstallFiles. Return value 1.",
977        ];
978
979        let (entries, _) = parse_lines(&lines, "test.log");
980
981        assert_eq!(entries[1].component.as_deref(), Some("InstallFiles"));
982        assert_eq!(entries[1].severity, Severity::Info);
983    }
984
985    #[test]
986    fn test_parse_action_ended_error() {
987        let lines = [
988            "=== Verbose logging started: 1/1/2024  16:34:00  Build type: SHIP ===",
989            "Action ended 16:34:29: InstallFiles. Return value 3.",
990        ];
991
992        let (entries, _) = parse_lines(&lines, "test.log");
993        assert_eq!(entries[1].severity, Severity::Error);
994    }
995
996    #[test]
997    fn test_parse_action_ended_warning() {
998        let lines = ["Action ended 16:34:29: InstallFiles. Return value 2."];
999
1000        let (entries, _) = parse_lines(&lines, "test.log");
1001        assert_eq!(entries[0].severity, Severity::Warning);
1002    }
1003
1004    // -- Property dump --
1005
1006    #[test]
1007    fn test_parse_property() {
1008        let lines = ["Property(C): ProductCode = {C64CA371-1234-5678-9ABC-DEF012345678}"];
1009
1010        let (entries, _) = parse_lines(&lines, "test.log");
1011
1012        assert_eq!(entries[0].component.as_deref(), Some("MSI-properties"));
1013        assert_eq!(
1014            entries[0].message,
1015            "ProductCode = {C64CA371-1234-5678-9ABC-DEF012345678}"
1016        );
1017        assert_eq!(entries[0].severity, Severity::Info);
1018        assert!(entries[0].timestamp.is_none());
1019    }
1020
1021    // -- MainEngineThread --
1022
1023    #[test]
1024    fn test_main_engine_thread_success() {
1025        let lines = ["MainEngineThread is returning 0"];
1026
1027        let (entries, _) = parse_lines(&lines, "test.log");
1028        assert_eq!(entries[0].severity, Severity::Info);
1029        assert_eq!(entries[0].component.as_deref(), Some("MSI-engine"));
1030    }
1031
1032    #[test]
1033    fn test_main_engine_thread_error_1603() {
1034        let lines = ["MainEngineThread is returning 1603"];
1035
1036        let (entries, _) = parse_lines(&lines, "test.log");
1037        assert_eq!(entries[0].severity, Severity::Error);
1038    }
1039
1040    #[test]
1041    fn test_main_engine_thread_warning_1602() {
1042        let lines = ["MainEngineThread is returning 1602"];
1043
1044        let (entries, _) = parse_lines(&lines, "test.log");
1045        assert_eq!(entries[0].severity, Severity::Warning);
1046    }
1047
1048    // -- Footer --
1049
1050    #[test]
1051    fn test_parse_footer() {
1052        let lines = ["=== Verbose logging stopped: 6/13/2023  9:03:15 ==="];
1053
1054        let (entries, errors) = parse_lines(&lines, "test.log");
1055
1056        assert_eq!(errors, 0);
1057        assert_eq!(entries[0].severity, Severity::Info);
1058        assert_eq!(entries[0].component.as_deref(), Some("MSI-header"));
1059    }
1060
1061    // -- Fallback and error severity --
1062
1063    #[test]
1064    fn test_plain_text_fallback() {
1065        let lines = ["Some random unstructured text"];
1066
1067        let (entries, errors) = parse_lines(&lines, "test.log");
1068
1069        assert_eq!(errors, 1);
1070        assert_eq!(entries[0].severity, Severity::Info);
1071        assert!(entries[0].component.is_none());
1072    }
1073
1074    #[test]
1075    fn test_engine_error_keyword_severity() {
1076        let lines = ["MSI (c) (8C:98) [10:00:00:000]: Installation failed with error status: 1603"];
1077
1078        let (entries, _) = parse_lines(&lines, "test.log");
1079        assert_eq!(entries[0].severity, Severity::Error);
1080    }
1081
1082    // -- Midnight rollover --
1083
1084    #[test]
1085    fn test_midnight_rollover() {
1086        let lines = [
1087            "=== Verbose logging started: 1/15/2024  23:59:50  Build type: SHIP ===",
1088            "MSI (c) (8C:98) [23:59:55:000]: Before midnight",
1089            "MSI (c) (8C:98) [00:00:05:000]: After midnight",
1090        ];
1091
1092        let (entries, _) = parse_lines(&lines, "test.log");
1093
1094        // After midnight should be Jan 16
1095        assert!(entries[2].timestamp.is_some());
1096        assert_eq!(
1097            entries[2].timestamp_display.as_deref(),
1098            Some("01-16-2024 00:00:05.000")
1099        );
1100    }
1101
1102    // -- Empty and whitespace lines --
1103
1104    #[test]
1105    fn test_empty_lines_skipped() {
1106        let lines = ["", "  ", "MSI (c) (8C:98) [10:00:00:000]: Hello", ""];
1107
1108        let (entries, _) = parse_lines(&lines, "test.log");
1109        assert_eq!(entries.len(), 1);
1110        assert_eq!(entries[0].message, "Hello");
1111    }
1112
1113    // -- Sequential IDs and line numbers --
1114
1115    #[test]
1116    fn test_ids_and_line_numbers() {
1117        let lines = [
1118            "=== Verbose logging started: 1/1/2024  10:00:00  Build type: SHIP ===",
1119            "MSI (c) (8C:98) [10:00:01:000]: First",
1120            "MSI (c) (8C:98) [10:00:02:000]: Second",
1121        ];
1122
1123        let (entries, _) = parse_lines(&lines, "test.log");
1124
1125        assert_eq!(entries[0].id, 0);
1126        assert_eq!(entries[0].line_number, 1);
1127        assert_eq!(entries[1].id, 1);
1128        assert_eq!(entries[1].line_number, 2);
1129        assert_eq!(entries[2].id, 2);
1130        assert_eq!(entries[2].line_number, 3);
1131    }
1132
1133    // -- Timestamp display format --
1134
1135    #[test]
1136    fn test_timestamp_display_format() {
1137        let lines = [
1138            "=== Verbose logging started: 12/25/2023  8:30:15  Build type: SHIP ===",
1139            "MSI (c) (FF:01) [08:30:15:007]: Test message",
1140        ];
1141
1142        let (entries, _) = parse_lines(&lines, "test.log");
1143
1144        // Display should be MM-dd-yyyy HH:mm:ss.fff
1145        assert_eq!(
1146            entries[1].timestamp_display.as_deref(),
1147            Some("12-25-2023 08:30:15.007")
1148        );
1149    }
1150
1151    // -- No date: time-only display --
1152
1153    #[test]
1154    fn test_engine_without_header_has_time_only_display() {
1155        let lines = ["MSI (c) (8C:98) [14:30:00:123]: No header yet"];
1156
1157        let (entries, _) = parse_lines(&lines, "test.log");
1158
1159        assert!(entries[0].timestamp.is_none());
1160        assert_eq!(
1161            entries[0].timestamp_display.as_deref(),
1162            Some("14:30:00.123")
1163        );
1164    }
1165
1166    // -- File path propagation --
1167
1168    #[test]
1169    fn test_file_path_propagated() {
1170        let lines = ["MSI (c) (8C:98) [10:00:00:000]: Test"];
1171
1172        let (entries, _) = parse_lines(&lines, "C:/Logs/install.log");
1173        assert_eq!(entries[0].file_path, "C:/Logs/install.log");
1174    }
1175
1176    // -- LogFormat is Timestamped --
1177
1178    #[test]
1179    fn test_log_format_is_timestamped() {
1180        let lines = [
1181            "MSI (c) (8C:98) [10:00:00:000]: Test",
1182            "Property(C): Foo = Bar",
1183            "Random line",
1184        ];
1185
1186        let (entries, _) = parse_lines(&lines, "test.log");
1187
1188        for entry in &entries {
1189            assert_eq!(entry.format, LogFormat::Timestamped);
1190        }
1191    }
1192}