//! Attachment names from mail are hostile: `../../evil.exe`, `CON.txt`, `invoice\u{202E}fdp.exe`. /// The longest name kept, in characters (the extension is kept when cutting). pub const MAX_FILENAME_CHARS: usize = 120; const FALLBACK: &str = "attachment"; fn is_bidi_or_invisible(c: char) -> bool { matches!(c, '\u{200B}'..='\u{200F}' // zero width, LRM, RLM | '\u{061C}' // Arabic letter mark | '\u{202A}'..='\u{202E}' // embeddings and overrides | '\u{2066}'..='\u{2069}' // isolates | '\u{FEFF}') } fn is_reserved_windows_name(stem: &str) -> bool { let upper = stem.trim_end_matches([' ', '.']).to_ascii_uppercase(); match upper.as_str() { "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" => true, s if s.len() == 4 && (s.starts_with("COM") || s.starts_with("LPT")) => s.as_bytes()[3].is_ascii_digit(), // COM¹ COM² COM³ LPT¹ … (Windows reserves the superscript digits too) s if (s.starts_with("COM") || s.starts_with("LPT")) && s.chars().count() == 4 => { matches!(s.chars().nth(3), Some('¹' | '²' | '³')) } _ => false, } } /// A name that is safe to create in any directory on Windows, Android and iOS, and that shows what it is. pub fn safe_filename(raw: &str) -> String { // Only the last path component, whatever the separator. let last = raw.rsplit(['/', '\\']).next().unwrap_or(""); // A drive prefix like `C:` that had no separator after it. let last = match last.find(':') { Some(i) if i == 1 => &last[2..], _ => last, }; let mut name: String = last .chars() .filter(|c| !c.is_control() && !is_bidi_or_invisible(*c)) .map(|c| match c { '<' | '>' | ':' | '"' | '|' | '?' | '*' => '_', c => c, }) .collect(); // No leading dots (hidden files, `..`), no trailing dots or spaces (Windows strips them). name = name.trim_start_matches(['.', ' ']).trim_end_matches(['.', ' ']).to_string(); // `..` inside a name is harmless as a path once separators are gone, but never keep the sequence. while name.contains("..") { name = name.replace("..", "."); } if name.is_empty() { return FALLBACK.to_string(); } let stem = name.split('.').next().unwrap_or(""); if is_reserved_windows_name(stem) { name.insert(0, '_'); } cut(&name) } /// Cut to `MAX_FILENAME_CHARS`, keeping a short extension. fn cut(name: &str) -> String { let count = name.chars().count(); if count <= MAX_FILENAME_CHARS { return name.to_string(); } let ext = match name.rfind('.') { Some(i) if name[i..].chars().count() <= 16 && i > 0 => &name[i..], _ => "", }; let keep = MAX_FILENAME_CHARS - ext.chars().count(); let stem: String = name.chars().take(keep).collect(); let stem = stem.trim_end_matches(['.', ' ']); let mut out = format!("{stem}{ext}"); // Trimming can make it shorter; pad is not needed, but never return something ending in a dot. while out.ends_with(['.', ' ']) { out.pop(); } if out.is_empty() { FALLBACK.to_string() } else { out } }