Cotton code
129 lines · 5.0 KB · RustRaw
//! The body of an iMessage, out of the blob Messages actually stores it in.//!//! WHY THIS IS THE PRIMARY PATH, not a fallback. On this Mac's own `chat.db`//! the `message.text` column is NULL on every row: modern Messages writes the//! body ONLY into `attributedBody`, an `NSAttributedString` archived with//! NSKeyedArchiver's older `typedstream` format. The phone's `sms.db` inside a//! Finder backup still fills `text` on most rows, so the reader tries the//! column first and comes here for everything else — which on the Mac file is//! everything.//!//! The format, as much of it as this needs: somewhere in the stream is the//! class marker `NSString`, and the string that follows it is the attributed//! string's own characters. After the marker comes a `+` (0x2B) —//! typedstream's tag for "bytes follow" — then a length, then that many UTF-8//! bytes. The length is one byte when it is below 0x80; `0x81` introduces a//! little-endian u16 and `0x82` a little-endian u32. Everything after the body//! is attribute runs (fonts, link ranges, the message effect) and is of no//! interest here.//!//! It is deliberately a PARSER and not a search-for-printable-runs heuristic: a//! heuristic pulls a font name or a URL out of the attribute table and files it//! as somebody's sentence. When the bytes do not parse this answers `None` and//! the reader counts a decode failure — a number the panel can show — rather//! than inventing a body./// The class marker the body's characters follow.const NS_STRING: &[u8] = b"NSString";/// Older archives name the mutable class instead; the layout after it is/// identical.const NS_MUTABLE_STRING: &[u8] = b"NSMutableString";/// typedstream's "bytes follow" tag.const PLUS: u8 = 0x2b;/// How far past the class marker the `+` may be before we stop believing it is/// ours. In the archives on this Mac it is four bytes away; the window is loose/// enough for a version that carries another field and tight enough that the/// next object's `+` can never be mistaken for this one's.const PLUS_SEARCH_WINDOW: usize = 64;/// A length prefix, and where the bytes it counts begin.fn read_length(bytes: &[u8], at: usize) -> Option<(usize, usize)> {    let first = *bytes.get(at)?;    if first < 0x80 {        return Some((first as usize, at + 1));    }    if first == 0x81 {        let low = *bytes.get(at + 1)? as usize;        let high = *bytes.get(at + 2)? as usize;        return Some((low | (high << 8), at + 3));    }    if first == 0x82 {        let b1 = *bytes.get(at + 1)? as usize;        let b2 = *bytes.get(at + 2)? as usize;        let b3 = *bytes.get(at + 3)? as usize;        let b4 = *bytes.get(at + 4)? as usize;        return Some((b1 | (b2 << 8) | (b3 << 16) | (b4 << 24), at + 5));    }    // 0x80, 0x83 and up are other typedstream tags — a length this parser does    // not know how to read is a body it must not guess at.    None}/// Where `needle` first appears in `bytes` at or after `from`.fn index_of(bytes: &[u8], needle: &[u8], from: usize) -> Option<usize> {    if needle.is_empty() || from >= bytes.len() {        return None;    }    bytes[from..]        .windows(needle.len())        .position(|window| window == needle)        .map(|at| at + from)}fn decode_from(bytes: &[u8], marker_end: usize) -> Option<String> {    let limit = bytes.len().min(marker_end + PLUS_SEARCH_WINDOW);    for at in marker_end..limit {        if bytes[at] != PLUS {            continue;        }        let (length, body) = read_length(bytes, at + 1)?;        if length == 0 {            return None;        }        let end = body.checked_add(length)?;        // A declared length past the end of the blob is a truncated read or a        // format this parser does not know — either way, not a body.        if end > bytes.len() {            return None;        }        // Lossy on purpose: the blob is somebody's own sentence and a stray        // byte in the middle of it must not throw the whole message away.        let text = String::from_utf8_lossy(&bytes[body..end]).into_owned();        return if text.trim().is_empty() {            None        } else {            Some(text)        };    }    None}/// The message's own words, or `None` when the blob holds none this parser can/// be sure of.////// `None` is a real answer and the caller counts it: a message with no body and/// no attachment is dropped, and a decode failure that silently became an empty/// string would put a blank bubble in somebody's conversation instead.pub fn decode_attributed_body(blob: Option<&[u8]>) -> Option<String> {    let bytes = blob?;    if bytes.is_empty() {        return None;    }    for marker in [NS_STRING, NS_MUTABLE_STRING] {        let mut at = index_of(bytes, marker, 0);        while let Some(start) = at {            if let Some(text) = decode_from(bytes, start + marker.len()) {                return Some(text);            }            at = index_of(bytes, marker, start + 1);        }    }    None}#[cfg(test)]#[path = "attributed_body_tests.rs"]mod tests;