Skip to main content

cmtraceopen_parser/esp/
normalize.rs

1use chrono::{DateTime, FixedOffset, NaiveDateTime, SecondsFormat, TimeZone, Utc};
2use thiserror::Error;
3
4use super::models::{
5    EspNormalizedStatus, EspOobeConfig, EspRawStatus, EspStatus, EspStatusDetail, EspTimestamp,
6    EspTimestampKind,
7};
8
9pub const MAX_PERCENT_DECODE_INPUT_BYTES: usize = 4096;
10
11#[derive(Debug, Clone, Error, PartialEq, Eq)]
12pub enum EspNormalizationError {
13    #[error("percent-encoded input is {actual} bytes; maximum is {maximum}")]
14    InputTooLong { actual: usize, maximum: usize },
15    #[error("invalid percent escape at byte {index}")]
16    InvalidPercentEscape { index: usize },
17    #[error("percent-decoded value is not UTF-8")]
18    InvalidUtf8,
19}
20
21pub fn normalize_office_detail_status(raw: EspRawStatus) -> EspStatus {
22    let mapping = match raw_number(&raw) {
23        Some(0) => Some((EspNormalizedStatus::NotStarted, "None")),
24        Some(10) => Some((EspNormalizedStatus::Initialized, "Initialized")),
25        Some(20) => Some((EspNormalizedStatus::Downloading, "Download In Progress")),
26        Some(25) => Some((EspNormalizedStatus::Pending, "Pending Download Retry")),
27        Some(30) => Some((EspNormalizedStatus::Failed, "Download Failed")),
28        Some(40) => Some((EspNormalizedStatus::Downloaded, "Download Completed")),
29        Some(48) => Some((EspNormalizedStatus::Pending, "Pending User Session")),
30        Some(50) => Some((EspNormalizedStatus::Installing, "Enforcement In Progress")),
31        Some(55) => Some((EspNormalizedStatus::Pending, "Pending Enforcement Retry")),
32        Some(60) => Some((EspNormalizedStatus::Failed, "Enforcement Failed")),
33        Some(70) => Some((
34            EspNormalizedStatus::Succeeded,
35            "Success / Enforcement Completed",
36        )),
37        _ => None,
38    };
39    mapped_status(raw, mapping)
40}
41
42pub fn normalize_classic_esp_status(raw: EspRawStatus) -> EspStatus {
43    let mapping = match raw_number(&raw) {
44        Some(1) => Some((EspNormalizedStatus::NotInstalled, "Not Installed")),
45        Some(2) => Some((EspNormalizedStatus::InProgress, "Downloading / Installing")),
46        Some(3) => Some((EspNormalizedStatus::Succeeded, "Success / Installed")),
47        Some(4) => Some((EspNormalizedStatus::Failed, "Error / Failed")),
48        _ => None,
49    };
50    mapped_status(raw, mapping)
51}
52
53pub fn normalize_policy_status(raw: EspRawStatus) -> EspStatus {
54    let mapping = match raw_number(&raw) {
55        Some(0) => Some((EspNormalizedStatus::NotStarted, "Not Processed")),
56        Some(1) => Some((EspNormalizedStatus::Processed, "Processed")),
57        _ => None,
58    };
59    mapped_status(raw, mapping)
60}
61
62pub fn normalize_v2_status(raw: EspRawStatus) -> EspStatus {
63    let mapping = match &raw {
64        EspRawStatus::Number(value) => v2_mapping_by_number(*value),
65        EspRawStatus::Text(value) => value
66            .trim()
67            .parse::<i64>()
68            .ok()
69            .and_then(v2_mapping_by_number)
70            .or_else(|| v2_mapping_by_name(value.trim())),
71        EspRawStatus::Other(_) => None,
72    };
73    mapped_status(raw, mapping)
74}
75
76pub fn normalize_office_status(
77    outer_raw: EspRawStatus,
78    detailed_raw: Option<EspRawStatus>,
79) -> EspStatus {
80    let mut outer = normalize_policy_status(outer_raw);
81    let Some(detailed_raw) = detailed_raw else {
82        return outer;
83    };
84    let detailed = normalize_office_detail_status(detailed_raw);
85
86    if !matches!(
87        detailed.normalized,
88        EspNormalizedStatus::Unknown | EspNormalizedStatus::NotStarted
89    ) {
90        outer.normalized = detailed.normalized.clone();
91    }
92    outer.display = format!("{} / {}", outer.display, detailed.display);
93    outer.detail = Some(EspStatusDetail {
94        raw: detailed.raw,
95        normalized: detailed.normalized,
96        display: detailed.display,
97    });
98    outer
99}
100
101pub fn percent_decode_bounded(input: &str) -> Result<String, EspNormalizationError> {
102    if input.len() > MAX_PERCENT_DECODE_INPUT_BYTES {
103        return Err(EspNormalizationError::InputTooLong {
104            actual: input.len(),
105            maximum: MAX_PERCENT_DECODE_INPUT_BYTES,
106        });
107    }
108
109    let bytes = input.as_bytes();
110    let mut output = Vec::with_capacity(bytes.len());
111    let mut index = 0;
112    while index < bytes.len() {
113        if bytes[index] != b'%' {
114            output.push(bytes[index]);
115            index += 1;
116            continue;
117        }
118        if index + 2 >= bytes.len() {
119            return Err(EspNormalizationError::InvalidPercentEscape { index });
120        }
121        let Some(high) = hex_nibble(bytes[index + 1]) else {
122            return Err(EspNormalizationError::InvalidPercentEscape { index });
123        };
124        let Some(low) = hex_nibble(bytes[index + 2]) else {
125            return Err(EspNormalizationError::InvalidPercentEscape { index });
126        };
127        output.push((high << 4) | low);
128        index += 3;
129    }
130
131    String::from_utf8(output).map_err(|_| EspNormalizationError::InvalidUtf8)
132}
133
134pub fn extract_guid(input: &str) -> Option<String> {
135    let decoded = percent_decode_bounded(input).ok()?;
136    let bytes = decoded.as_bytes();
137    if bytes.len() < 36 {
138        return None;
139    }
140
141    for window in bytes.windows(36) {
142        if is_guid_window(window) {
143            return Some(
144                window
145                    .iter()
146                    .map(|byte| {
147                        if *byte == b'_' {
148                            '-'
149                        } else {
150                            char::from(byte.to_ascii_lowercase())
151                        }
152                    })
153                    .collect(),
154            );
155        }
156    }
157    None
158}
159
160pub fn decode_oobe_config(raw_mask: u64) -> EspOobeConfig {
161    EspOobeConfig {
162        raw_mask,
163        skip_keyboard: raw_mask & 1024 != 0,
164        enable_patch_download: raw_mask & 512 != 0,
165        skip_windows_upgrade_ux: raw_mask & 256 != 0,
166        aad_tpm_required: raw_mask & 128 != 0,
167        aad_device_authentication: raw_mask & 64 != 0,
168        tpm_attestation: raw_mask & 32 != 0,
169        skip_eula: raw_mask & 16 != 0,
170        skip_oem_registration: raw_mask & 8 != 0,
171        skip_express_settings: raw_mask & 4 != 0,
172        disallow_admin: raw_mask & 2 != 0,
173    }
174}
175
176pub fn normalize_timestamp(raw: &str, explicit_local_offset: Option<&str>) -> EspTimestamp {
177    if let Ok(parsed) = DateTime::parse_from_rfc3339(raw) {
178        let is_utc_text = raw.ends_with('Z') || raw.ends_with('z');
179        return EspTimestamp {
180            raw_text: raw.to_string(),
181            original_offset: Some(if is_utc_text {
182                "Z".to_string()
183            } else {
184                parsed.offset().to_string()
185            }),
186            normalized_utc: Some(format_utc(parsed.with_timezone(&Utc))),
187            kind: if is_utc_text {
188                EspTimestampKind::Utc
189            } else {
190                EspTimestampKind::Offset
191            },
192        };
193    }
194
195    let Some(naive) = parse_naive_timestamp(raw) else {
196        return unresolved_timestamp(raw, EspTimestampKind::Invalid, explicit_local_offset);
197    };
198    let Some(offset_text) = explicit_local_offset else {
199        return unresolved_timestamp(raw, EspTimestampKind::Unspecified, None);
200    };
201    let Some(offset) = parse_fixed_offset(offset_text) else {
202        return unresolved_timestamp(raw, EspTimestampKind::Invalid, Some(offset_text));
203    };
204    let Some(with_offset) = offset.from_local_datetime(&naive).single() else {
205        return unresolved_timestamp(raw, EspTimestampKind::Invalid, Some(offset_text));
206    };
207
208    EspTimestamp {
209        raw_text: raw.to_string(),
210        original_offset: Some(offset.to_string()),
211        normalized_utc: Some(format_utc(with_offset.with_timezone(&Utc))),
212        kind: EspTimestampKind::Local,
213    }
214}
215
216fn mapped_status(
217    raw: EspRawStatus,
218    mapping: Option<(EspNormalizedStatus, &'static str)>,
219) -> EspStatus {
220    let fallback_display = raw_display(&raw);
221    let (normalized, display) = mapping
222        .map(|(normalized, display)| (normalized, display.to_string()))
223        .unwrap_or((EspNormalizedStatus::Unknown, fallback_display));
224    EspStatus {
225        raw,
226        normalized,
227        display,
228        detail: None,
229    }
230}
231
232fn raw_number(raw: &EspRawStatus) -> Option<i64> {
233    match raw {
234        EspRawStatus::Number(value) => Some(*value),
235        EspRawStatus::Text(value) => value.trim().parse().ok(),
236        EspRawStatus::Other(_) => None,
237    }
238}
239
240fn raw_display(raw: &EspRawStatus) -> String {
241    match raw {
242        EspRawStatus::Number(value) => value.to_string(),
243        EspRawStatus::Text(value) => value.clone(),
244        EspRawStatus::Other(value) => value.to_string(),
245    }
246}
247
248fn v2_mapping_by_number(value: i64) -> Option<(EspNormalizedStatus, &'static str)> {
249    match value {
250        0 => Some((EspNormalizedStatus::NotStarted, "NotStarted")),
251        1 => Some((EspNormalizedStatus::Succeeded, "Completed")),
252        2 => Some((EspNormalizedStatus::Skipped, "Skipped")),
253        3 => Some((EspNormalizedStatus::Uninstalled, "Uninstalled")),
254        4 => Some((EspNormalizedStatus::Failed, "Failed")),
255        5 => Some((EspNormalizedStatus::InProgress, "InProgress")),
256        6 => Some((EspNormalizedStatus::RebootRequired, "RebootRequired")),
257        7 => Some((EspNormalizedStatus::Cancelled, "Cancelled")),
258        _ => None,
259    }
260}
261
262fn v2_mapping_by_name(value: &str) -> Option<(EspNormalizedStatus, &'static str)> {
263    if value.eq_ignore_ascii_case("NotStarted") {
264        Some((EspNormalizedStatus::NotStarted, "NotStarted"))
265    } else if value.eq_ignore_ascii_case("Completed") {
266        Some((EspNormalizedStatus::Succeeded, "Completed"))
267    } else if value.eq_ignore_ascii_case("Skipped") {
268        Some((EspNormalizedStatus::Skipped, "Skipped"))
269    } else if value.eq_ignore_ascii_case("Uninstalled") {
270        Some((EspNormalizedStatus::Uninstalled, "Uninstalled"))
271    } else if value.eq_ignore_ascii_case("Failed") {
272        Some((EspNormalizedStatus::Failed, "Failed"))
273    } else if value.eq_ignore_ascii_case("InProgress") {
274        Some((EspNormalizedStatus::InProgress, "InProgress"))
275    } else if value.eq_ignore_ascii_case("RebootRequired") {
276        Some((EspNormalizedStatus::RebootRequired, "RebootRequired"))
277    } else if value.eq_ignore_ascii_case("Cancelled") {
278        Some((EspNormalizedStatus::Cancelled, "Cancelled"))
279    } else {
280        None
281    }
282}
283
284fn hex_nibble(byte: u8) -> Option<u8> {
285    match byte {
286        b'0'..=b'9' => Some(byte - b'0'),
287        b'a'..=b'f' => Some(byte - b'a' + 10),
288        b'A'..=b'F' => Some(byte - b'A' + 10),
289        _ => None,
290    }
291}
292
293fn is_guid_window(window: &[u8]) -> bool {
294    window.iter().enumerate().all(|(index, byte)| {
295        if matches!(index, 8 | 13 | 18 | 23) {
296            *byte == b'-' || *byte == b'_'
297        } else {
298            byte.is_ascii_hexdigit()
299        }
300    })
301}
302
303fn parse_naive_timestamp(raw: &str) -> Option<NaiveDateTime> {
304    [
305        "%Y-%m-%dT%H:%M:%S%.f",
306        "%Y-%m-%d %H:%M:%S%.f",
307        "%m/%d/%Y %H:%M:%S%.f",
308    ]
309    .iter()
310    .find_map(|format| NaiveDateTime::parse_from_str(raw, format).ok())
311}
312
313fn parse_fixed_offset(raw: &str) -> Option<FixedOffset> {
314    if raw == "Z" || raw == "z" {
315        return FixedOffset::east_opt(0);
316    }
317    let bytes = raw.as_bytes();
318    if bytes.len() != 6 || bytes[3] != b':' {
319        return None;
320    }
321    let sign = match bytes[0] {
322        b'+' => 1,
323        b'-' => -1,
324        _ => return None,
325    };
326    let hours = decimal_pair(bytes[1], bytes[2])?;
327    let minutes = decimal_pair(bytes[4], bytes[5])?;
328    if hours > 23 || minutes > 59 {
329        return None;
330    }
331    FixedOffset::east_opt(sign * (hours * 3600 + minutes * 60))
332}
333
334fn decimal_pair(first: u8, second: u8) -> Option<i32> {
335    if !first.is_ascii_digit() || !second.is_ascii_digit() {
336        return None;
337    }
338    Some(i32::from(first - b'0') * 10 + i32::from(second - b'0'))
339}
340
341fn format_utc(value: DateTime<Utc>) -> String {
342    // AutoSi is the single canonical `normalized_utc` serialization across the
343    // ESP pipeline (mirrored by reducer.rs and correlation.rs) so that equal
344    // instants always render to byte-identical RFC 3339 strings.
345    value.to_rfc3339_opts(SecondsFormat::AutoSi, true)
346}
347
348fn unresolved_timestamp(
349    raw: &str,
350    kind: EspTimestampKind,
351    original_offset: Option<&str>,
352) -> EspTimestamp {
353    EspTimestamp {
354        raw_text: raw.to_string(),
355        original_offset: original_offset.map(str::to_string),
356        normalized_utc: None,
357        kind,
358    }
359}