use serde::{Deserialize, Serialize};
use crate::error::ShunError;
pub const ERROR_APPLICATION_CONTROL_POLICY_BLOCKED: i32 = 4551;
pub const ERROR_ACCESS_DISABLED_BY_POLICY: i32 = 1260;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum FinishStage {
Shortcuts,
Launch,
Install,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum FailureKind {
AppControlBlocked,
MissingExecutable,
Permissions,
DiskFull,
FileInUse,
PathTooLong,
Network,
Io,
Other,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FinishFailure {
pub stage: FinishStage,
pub kind: FailureKind,
pub message: String,
pub os_error: Option<i32>,
pub help_topic: Option<String>,
}
impl FinishFailure {
pub fn from_error(stage: FinishStage, error: &ShunError) -> Self {
let (kind, os_error, help_topic) = classify_error(error);
Self {
stage,
kind,
message: error.to_string(),
os_error,
help_topic,
}
}
pub fn other(stage: FinishStage, message: impl Into<String>) -> Self {
Self {
stage,
kind: FailureKind::Other,
message: message.into(),
os_error: None,
help_topic: None,
}
}
pub fn from_os_error(stage: FinishStage, code: i32, message: impl Into<String>) -> Self {
let kind = classify_os_error(code);
Self {
stage,
kind,
message: message.into(),
os_error: Some(code),
help_topic: help_topic_for(kind),
}
}
pub fn from_message(stage: FinishStage, message: impl Into<String>) -> Self {
let message = message.into();
let (kind, os_error) = classify_message(&message);
Self {
stage,
kind,
message,
os_error,
help_topic: help_topic_for(kind),
}
}
pub fn has_help(&self) -> bool {
self.help_topic.is_some()
}
}
fn classify_error(error: &ShunError) -> (FailureKind, Option<i32>, Option<String>) {
match error {
ShunError::Io(io) => match io.raw_os_error() {
Some(code) => {
let kind = classify_os_error(code);
(kind, Some(code), help_topic_for(kind))
}
None => (FailureKind::Io, None, None),
},
ShunError::MissingEntry(_) => {
let kind = FailureKind::MissingExecutable;
(kind, None, help_topic_for(kind))
}
_ => (FailureKind::Other, None, None),
}
}
#[cfg(all(not(windows), not(target_os = "macos")))]
pub(crate) const ENAMETOOLONG: i32 = 36;
#[cfg(target_os = "macos")]
pub(crate) const ENAMETOOLONG: i32 = 63;
#[cfg(all(unix, not(target_os = "macos")))]
pub(crate) const UNIX_NETWORK_ERRNOS: [i32; 5] = [101, 110, 111, 112, 113];
#[cfg(target_os = "macos")]
pub(crate) const UNIX_NETWORK_ERRNOS: [i32; 5] = [61, 60, 51, 64, 65];
pub fn classify_os_error(code: i32) -> FailureKind {
match code {
ERROR_APPLICATION_CONTROL_POLICY_BLOCKED | ERROR_ACCESS_DISABLED_BY_POLICY => {
FailureKind::AppControlBlocked
}
#[cfg(windows)]
5 | 1314 => FailureKind::Permissions,
#[cfg(windows)]
112 | 39 => FailureKind::DiskFull,
#[cfg(windows)]
32 | 1224 => FailureKind::FileInUse,
#[cfg(windows)]
206 | 161 => FailureKind::PathTooLong,
#[cfg(windows)]
10060 | 10061 | 10051 | 10053 | 10054 | 12002 | 12007 | 12029 => FailureKind::Network,
#[cfg(not(windows))]
1 | 13 | 30 => FailureKind::Permissions,
#[cfg(not(windows))]
28 => FailureKind::DiskFull,
#[cfg(not(windows))]
26 => FailureKind::FileInUse,
#[cfg(not(windows))]
ENAMETOOLONG => FailureKind::PathTooLong,
#[cfg(unix)]
code if UNIX_NETWORK_ERRNOS.contains(&code) => FailureKind::Network,
_ => FailureKind::Io,
}
}
pub(crate) fn help_topic_for(kind: FailureKind) -> Option<String> {
match kind {
FailureKind::AppControlBlocked => Some(crate::help::TOPIC_APP_CONTROL.to_string()),
FailureKind::Permissions => Some(crate::help::TOPIC_PERMISSIONS.to_string()),
FailureKind::DiskFull => Some(crate::help::TOPIC_DISK_SPACE.to_string()),
FailureKind::FileInUse => Some(crate::help::TOPIC_FILE_IN_USE.to_string()),
FailureKind::PathTooLong => Some(crate::help::TOPIC_PATH_TOO_LONG.to_string()),
FailureKind::Network => Some(crate::help::TOPIC_NETWORK.to_string()),
FailureKind::MissingExecutable => Some(crate::help::TOPIC_MISSING_FILES.to_string()),
FailureKind::Io | FailureKind::Other => None,
}
}
pub fn classify_message(message: &str) -> (FailureKind, Option<i32>) {
let mut best: Option<(FailureKind, i32)> = None;
let mut rest = message;
while let Some(at) = find_os_error(rest) {
let code = at.code;
let kind = classify_os_error(code);
if !matches!(kind, FailureKind::Io) {
best = Some((kind, code));
break;
}
rest = &rest[at.end..];
}
if let Some((kind, code)) = best {
return (kind, Some(code));
}
let pattern: Vec<char> = "0x11c7".chars().collect();
let chars: Vec<char> = message.chars().collect();
let bounded = |c: Option<char>| c.map(|c| !c.is_ascii_hexdigit()).unwrap_or(true);
let mut index = 0usize;
while index + pattern.len() <= chars.len() {
if chars[index..index + pattern.len()]
.iter()
.zip(pattern.iter())
.all(|(c, p)| c.to_ascii_lowercase() == *p)
{
let before = index.checked_sub(1).and_then(|i| chars.get(i)).copied();
let after = chars.get(index + pattern.len()).copied();
if bounded(before) && bounded(after) {
return (
FailureKind::AppControlBlocked,
Some(ERROR_APPLICATION_CONTROL_POLICY_BLOCKED),
);
}
}
index += 1;
}
let lowered = message.to_lowercase();
const NETWORK_MARKERS: [&str; 8] = [
"connection closed",
"connection refused",
"connection reset",
"timed out",
"timeout",
"dns error",
"name or service not known",
"unreachable",
];
if NETWORK_MARKERS
.iter()
.any(|marker| lowered.contains(marker))
{
return (FailureKind::Network, None);
}
(FailureKind::Io, None)
}
fn find_os_error(text: &str) -> Option<OsErrorHit> {
let needle = "os error ";
let mut search_from = 0;
while let Some(rel) = text[search_from..].find(needle) {
let start = search_from + rel + needle.len();
let digits: String = text[start..]
.chars()
.take_while(|c| c.is_ascii_digit())
.collect();
if !digits.is_empty() {
if let Ok(code) = digits.parse::<i32>() {
return Some(OsErrorHit {
code,
end: start + digits.len(),
});
}
}
search_from = start;
}
None
}
struct OsErrorHit {
code: i32,
end: usize,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn app_control_codes_are_blocked_with_the_guide_topic() {
for code in [
ERROR_APPLICATION_CONTROL_POLICY_BLOCKED,
ERROR_ACCESS_DISABLED_BY_POLICY,
] {
let failure = FinishFailure::from_os_error(FinishStage::Launch, code, "blocked");
assert_eq!(failure.kind, FailureKind::AppControlBlocked, "code {code}");
assert_eq!(failure.os_error, Some(code));
assert_eq!(
failure.help_topic.as_deref(),
Some(crate::help::TOPIC_APP_CONTROL)
);
assert!(failure.has_help());
}
}
#[test]
fn other_io_codes_stay_plain_io_without_a_topic() {
let failure = FinishFailure::from_os_error(FinishStage::Launch, 2, "not found");
assert_eq!(failure.kind, FailureKind::Io);
assert_eq!(failure.os_error, Some(2));
assert!(failure.help_topic.is_none());
assert!(!failure.has_help());
}
#[test]
fn io_errors_classify_through_the_os_code() {
let error = ShunError::Io(std::io::Error::from_raw_os_error(
ERROR_APPLICATION_CONTROL_POLICY_BLOCKED,
));
let failure = FinishFailure::from_error(FinishStage::Launch, &error);
assert_eq!(failure.kind, FailureKind::AppControlBlocked);
assert_eq!(
failure.os_error,
Some(ERROR_APPLICATION_CONTROL_POLICY_BLOCKED)
);
assert!(
failure.message.starts_with("io error:"),
"the raw message stays available: {}",
failure.message
);
assert_eq!(failure.stage, FinishStage::Launch);
}
#[test]
fn missing_entry_is_its_own_kind() {
let error = ShunError::MissingEntry(std::path::PathBuf::from("bin/app.exe"));
let failure = FinishFailure::from_error(FinishStage::Launch, &error);
assert_eq!(failure.kind, FailureKind::MissingExecutable);
assert_eq!(
failure.help_topic.as_deref(),
Some(crate::help::TOPIC_MISSING_FILES)
);
assert!(failure.has_help());
}
#[test]
fn the_wire_shape_is_camel_case_with_kebab_kinds() {
let failure = FinishFailure::from_os_error(
FinishStage::Launch,
ERROR_APPLICATION_CONTROL_POLICY_BLOCKED,
"io error: blocked",
);
let json = serde_json::to_value(&failure).expect("serializes");
assert_eq!(json["stage"], "launch");
assert_eq!(json["kind"], "app-control-blocked");
assert_eq!(json["osError"], 4551);
assert_eq!(json["helpTopic"], "app-control");
assert_eq!(json["message"], "io error: blocked");
let back: FinishFailure = serde_json::from_value(json).expect("deserializes");
assert_eq!(back, failure);
}
#[test]
fn the_other_constructor_carries_no_help() {
let failure = FinishFailure::other(FinishStage::Shortcuts, "boom");
assert_eq!(failure.kind, FailureKind::Other);
assert_eq!(failure.os_error, None);
assert!(!failure.has_help());
}
#[cfg(windows)]
#[test]
fn windows_os_codes_map_to_their_families() {
let cases: [(i32, FailureKind); 10] = [
(5, FailureKind::Permissions), (1314, FailureKind::Permissions), (112, FailureKind::DiskFull), (39, FailureKind::DiskFull), (32, FailureKind::FileInUse), (1224, FailureKind::FileInUse), (206, FailureKind::PathTooLong), (161, FailureKind::PathTooLong), (10061, FailureKind::Network), (12029, FailureKind::Network), ];
for (code, kind) in cases {
assert_eq!(classify_os_error(code), kind, "windows code {code}");
}
for code in [1, 13, 26, 28, 30, 36] {
assert_eq!(
classify_os_error(code),
FailureKind::Io,
"unix code {code} on windows"
);
}
}
#[cfg(not(windows))]
#[test]
fn unix_os_codes_map_to_their_families() {
let cases: [(i32, FailureKind); 6] = [
(1, FailureKind::Permissions), (13, FailureKind::Permissions), (30, FailureKind::Permissions), (28, FailureKind::DiskFull), (26, FailureKind::FileInUse), (ENAMETOOLONG, FailureKind::PathTooLong),
];
for (code, kind) in cases {
assert_eq!(classify_os_error(code), kind, "unix code {code}");
}
for code in UNIX_NETWORK_ERRNOS {
assert_eq!(
classify_os_error(code),
FailureKind::Network,
"unix network code {code}"
);
}
let other_enametoolang: i32 = if cfg!(target_os = "macos") { 36 } else { 63 };
assert_eq!(classify_os_error(other_enametoolang), FailureKind::Io);
for code in [
5, 1314, 39, 32, 1224, 206, 161, 10060, 10061, 10051, 10053, 10054, 12002, 12007, 12029,
] {
assert_eq!(
classify_os_error(code),
FailureKind::Io,
"windows code {code} on unix"
);
}
let mut sorted = UNIX_NETWORK_ERRNOS;
sorted.sort_unstable();
assert!(
sorted.windows(2).all(|pair| pair[0] < pair[1]),
"UNIX_NETWORK_ERRNOS has no duplicates: {sorted:?}"
);
}
#[test]
fn every_family_names_a_known_topic() {
for kind in [
FailureKind::AppControlBlocked,
FailureKind::Permissions,
FailureKind::DiskFull,
FailureKind::FileInUse,
FailureKind::PathTooLong,
FailureKind::Network,
FailureKind::MissingExecutable,
] {
let topic = help_topic_for(kind).expect("family carries a topic");
assert!(
crate::help::TOPICS.contains(&topic.as_str()),
"{:?}: {}",
kind,
topic
);
}
assert_eq!(classify_os_error(2), FailureKind::Io);
assert!(help_topic_for(FailureKind::Io).is_none());
}
#[test]
fn install_stage_is_a_first_class_wire_value() {
let failure = FinishFailure::from_os_error(FinishStage::Install, 28, "disk full");
let json = serde_json::to_value(&failure).expect("serializes");
assert_eq!(json["stage"], "install");
assert_eq!(json["kind"], "disk-full");
assert_eq!(json["helpTopic"], "disk-space");
}
#[test]
fn flow_messages_classify_through_their_embedded_os_code() {
let denied: i32 = if cfg!(windows) { 5 } else { 13 };
let (kind, code) =
classify_message(&format!("io error: Access is denied. (os error {denied})"));
assert_eq!(kind, FailureKind::Permissions);
assert_eq!(code, Some(denied));
let in_use: i32 = if cfg!(windows) { 32 } else { 26 };
let (kind, code) = classify_message(&format!(
"io error: Extract of WoWSP.exe failed: file is busy (os error {in_use})"
));
assert_eq!(kind, FailureKind::FileInUse);
assert_eq!(code, Some(in_use));
}
#[test]
fn transport_wording_classifies_as_network() {
for message in [
"download failed: Network connect timed out: Connection refused (os error 111)",
"fetch https://example.invalid/mirror: Dns Error: Failed to lookup address information",
"download failed: connection closed before message completed",
] {
let (kind, _) = classify_message(message);
assert_eq!(kind, FailureKind::Network, "{message}");
}
}
#[test]
fn plain_errors_stay_unclassified() {
let (kind, code) = classify_message("the configuration declares no install target");
assert_eq!(kind, FailureKind::Io);
assert_eq!(code, None);
}
#[test]
fn the_hex_form_of_the_block_code_classifies() {
let (kind, code) = classify_message("CreateProcess failed: 0x11C7 before any output");
assert_eq!(kind, FailureKind::AppControlBlocked);
assert_eq!(code, Some(ERROR_APPLICATION_CONTROL_POLICY_BLOCKED));
}
#[test]
fn the_hex_form_is_token_bounded_and_case_insensitive() {
for message in ["CreateProcess failed: 0x11C7", "blocked: 0x11c7 (?)"] {
let (kind, code) = classify_message(message);
assert_eq!(kind, FailureKind::AppControlBlocked, "{message}");
assert_eq!(code, Some(ERROR_APPLICATION_CONTROL_POLICY_BLOCKED));
}
let (kind, code) = classify_message("script prepare: fault at 0x11C7F00A in module two");
assert_ne!(
kind,
FailureKind::AppControlBlocked,
"0x11C7F00A is not the block"
);
assert_eq!(code, None);
let (kind, code) = classify_message("blocked (see 0x11c7.)");
assert_eq!(kind, FailureKind::AppControlBlocked);
assert_eq!(code, Some(ERROR_APPLICATION_CONTROL_POLICY_BLOCKED));
let (kind, _) = classify_message("C:\\Users\\\u{0130}brahim\\app.exe blocked 0x11C7");
assert_eq!(kind, FailureKind::AppControlBlocked);
}
#[test]
fn multiple_os_codes_walk_forward_and_the_narrower_one_wins() {
let denied: i32 = if cfg!(windows) { 5 } else { 13 };
let (kind, code) = classify_message(&format!(
"io error: absent (os error 2) during write to X (os error {denied})"
));
assert_eq!(kind, FailureKind::Permissions);
assert_eq!(code, Some(denied));
}
#[test]
fn the_os_error_walk_survives_an_overflowing_code() {
let denied: i32 = if cfg!(windows) { 5 } else { 13 };
let (kind, code) = classify_message(&format!(
"io error: first (os error 99999999999) then denied (os error {denied})"
));
assert_eq!(kind, FailureKind::Permissions);
assert_eq!(code, Some(denied));
}
}