Cotton code
397 lines · 13.5 KB · RustRaw
//! The IMAP wire, read: one server response at a time, literals included.//!//! Copied from `cotton-server`'s `mailbox::imap_proto` (that crate retires on//! its own) and made blocking: a response is cut from a buffer the client//! keeps, so a read that times out mid-line loses nothing.//!//! Only the subset a reading client meets (RFC 3501 + Gmail's X-GM items)://! atoms, quoted strings, `{n}` literals, parenthesised lists and `NIL`. An//! atom may carry a bracketed section (`BODY[]`, `[UIDVALIDITY 7]`), read//! whole so its spaces do not split it./// The largest literal this client holds: a message bigger than this is/// refused by name rather than allocated, since the server, not Cotton, chose/// its size.pub const LITERAL_MAX: u64 = 64 * 1024 * 1024;/// The longest line between two literals. A server that sends a megabyte with/// no CRLF is broken or hostile; either way the read ends.pub const LINE_MAX: usize = 1024 * 1024;#[derive(Debug, Clone, PartialEq, Eq)]pub enum Value {    Atom(String),    /// A quoted string or a literal — the same thing to a reader.    Bytes(Vec<u8>),    List(Vec<Value>),    Nil,}impl Value {    pub fn as_atom(&self) -> Option<&str> {        match self {            Value::Atom(atom) => Some(atom),            _ => None,        }    }    /// An atom or a string, as text.    pub fn as_text(&self) -> Option<String> {        match self {            Value::Atom(atom) => Some(atom.clone()),            Value::Bytes(bytes) => Some(String::from_utf8_lossy(bytes).into_owned()),            _ => None,        }    }    pub fn as_list(&self) -> Option<&[Value]> {        match self {            Value::List(items) => Some(items),            _ => None,        }    }}/// One whole response: its first word (`*`, `+` or a tag) and what follows.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Response {    pub tag: String,    pub values: Vec<Value>,    /// The line as text with literals elided — what a status response says,    /// for an error sentence.    pub text: String,}impl Response {    pub fn is_untagged(&self) -> bool {        self.tag == "*"    }    pub fn is_continuation(&self) -> bool {        self.tag == "+"    }    /// `OK`, `NO`, `BAD`, `BYE`, `PREAUTH` for a status response.    pub fn status(&self) -> Option<&str> {        self.values.first().and_then(Value::as_atom)    }    /// `* <n> <WORD> …` — a numbered untagged response (EXISTS, FETCH, …).    pub fn numbered(&self) -> Option<(u32, &str)> {        let n = self.values.first()?.as_atom()?.parse().ok()?;        Some((n, self.values.get(1)?.as_atom()?))    }    /// The `[CODE arg]` a status response carries, as its words.    pub fn code(&self) -> Option<Vec<String>> {        let atom = self.values.get(1)?.as_atom()?;        let inner = atom.strip_prefix('[')?.strip_suffix(']')?;        Some(inner.split_whitespace().map(str::to_string).collect())    }}#[derive(Debug, thiserror::Error)]pub enum WireError {    #[error("the mail server closed the connection")]    Closed,    #[error("the mail server sent a line longer than Cotton reads")]    LineTooLong,    #[error("the mail server offered a message of {0} bytes, past what Cotton holds in memory")]    LiteralTooLarge(u64),    #[error("the mail server sent something Cotton could not read: {0}")]    Malformed(String),    #[error("{0}")]    Io(#[from] std::io::Error),}/// How long the first whole response in `buf` is, literals included; `None`/// while more bytes are needed.pub fn complete_response(buf: &[u8]) -> Result<Option<usize>, WireError> {    let mut at = 0;    loop {        let rest = &buf[at..];        let Some(newline) = rest.iter().position(|&b| b == b'\n') else {            if rest.len() > LINE_MAX {                return Err(WireError::LineTooLong);            }            return Ok(None);        };        if newline > LINE_MAX {            return Err(WireError::LineTooLong);        }        let line_end = at + newline + 1;        match literal_announced(&buf[at..line_end]) {            Some(size) => {                if size > LITERAL_MAX {                    return Err(WireError::LiteralTooLarge(size));                }                let literal_end = line_end + size as usize;                if buf.len() < literal_end {                    return Ok(None);                }                at = literal_end;            }            None => return Ok(Some(line_end)),        }    }}/// `… {123}\r\n` → 123. `{123+}` (LITERAL+) reads the same.fn literal_announced(line: &[u8]) -> Option<u64> {    let line = line.strip_suffix(b"\n")?;    let line = line.strip_suffix(b"\r").unwrap_or(line);    let line = line.strip_suffix(b"}")?;    let open = line.iter().rposition(|&b| b == b'{')?;    let digits = &line[open + 1..];    let digits = digits.strip_suffix(b"+").unwrap_or(digits);    if digits.is_empty() || !digits.iter().all(u8::is_ascii_digit) {        return None;    }    std::str::from_utf8(digits).ok()?.parse().ok()}/// Parse one response already read whole (literals inline after their `{n}\r\n`).pub fn parse_response(raw: &[u8]) -> Result<Response, WireError> {    let mut cursor = Cursor { raw, at: 0 };    let tag = cursor.word();    if tag.is_empty() {        return Err(WireError::Malformed("an empty line".to_string()));    }    let mut values = Vec::new();    cursor.skip_spaces();    let text_start = cursor.at;    // A continuation's or status response's trailing words are free text; the    // parse still reads them as atoms, which is harmless and keeps one path.    while !cursor.at_end_of_line() {        values.push(cursor.value()?);        cursor.skip_spaces();    }    let text = String::from_utf8_lossy(&first_line(&raw[text_start.min(raw.len())..])).into_owned();    Ok(Response {        tag,        values,        text: text.trim_end().to_string(),    })}fn first_line(raw: &[u8]) -> Vec<u8> {    // Good enough for an error sentence: a status line has no literal anyway.    raw.iter()        .copied()        .take_while(|&b| b != b'\r' && b != b'\n')        .take(300)        .collect()}struct Cursor<'a> {    raw: &'a [u8],    at: usize,}impl Cursor<'_> {    fn peek(&self) -> Option<u8> {        self.raw.get(self.at).copied()    }    fn at_end_of_line(&self) -> bool {        matches!(self.peek(), None | Some(b'\r' | b'\n'))    }    fn skip_spaces(&mut self) {        while self.peek() == Some(b' ') {            self.at += 1;        }    }    /// The tag: up to the first space.    fn word(&mut self) -> String {        let start = self.at;        while let Some(b) = self.peek() {            if b == b' ' || b == b'\r' || b == b'\n' {                break;            }            self.at += 1;        }        String::from_utf8_lossy(&self.raw[start..self.at]).into_owned()    }    fn value(&mut self) -> Result<Value, WireError> {        match self.peek() {            Some(b'(') => {                self.at += 1;                let mut items = Vec::new();                loop {                    self.skip_spaces();                    match self.peek() {                        Some(b')') => {                            self.at += 1;                            return Ok(Value::List(items));                        }                        None | Some(b'\r' | b'\n') => {                            return Err(WireError::Malformed("an unclosed list".to_string()));                        }                        _ => items.push(self.value()?),                    }                }            }            Some(b'"') => {                self.at += 1;                let mut out = Vec::new();                loop {                    match self.peek() {                        Some(b'"') => {                            self.at += 1;                            return Ok(Value::Bytes(out));                        }                        Some(b'\\') => {                            self.at += 1;                            if let Some(b) = self.peek() {                                out.push(b);                                self.at += 1;                            }                        }                        Some(b'\r' | b'\n') | None => {                            return Err(WireError::Malformed("an unclosed string".to_string()));                        }                        Some(b) => {                            out.push(b);                            self.at += 1;                        }                    }                }            }            Some(b'{') => {                let close = self.raw[self.at..]                    .iter()                    .position(|&b| b == b'}')                    .ok_or_else(|| WireError::Malformed("an unclosed literal".to_string()))?;                let digits = &self.raw[self.at + 1..self.at + close];                let digits = digits.strip_suffix(b"+").unwrap_or(digits);                let size: usize = std::str::from_utf8(digits)                    .ok()                    .and_then(|d| d.parse().ok())                    .ok_or_else(|| WireError::Malformed("a literal with no size".to_string()))?;                self.at += close + 1;                if self.raw.get(self.at..self.at + 2) == Some(b"\r\n") {                    self.at += 2;                } else if self.peek() == Some(b'\n') {                    self.at += 1;                }                let end = self.at + size;                let bytes = self                    .raw                    .get(self.at..end)                    .ok_or_else(|| WireError::Malformed("a literal cut short".to_string()))?                    .to_vec();                self.at = end;                Ok(Value::Bytes(bytes))            }            _ => {                let start = self.at;                let mut depth = 0_u32;                while let Some(b) = self.peek() {                    match b {                        b'[' => depth += 1,                        b']' => depth = depth.saturating_sub(1),                        b' ' | b'(' | b')' if depth == 0 => break,                        b'\r' | b'\n' => break,                        _ => {}                    }                    self.at += 1;                }                let atom = String::from_utf8_lossy(&self.raw[start..self.at]).into_owned();                if atom.is_empty() {                    return Err(WireError::Malformed("an empty atom".to_string()));                }                if atom.eq_ignore_ascii_case("NIL") {                    Ok(Value::Nil)                } else {                    Ok(Value::Atom(atom))                }            }        }    }}/// Quote a string for a command argument. A CR or LF cannot be quoted and is/// refused: an app password never holds one, and passing it on would split/// the command.pub fn quote(text: &str) -> Option<String> {    if text.contains(['\r', '\n']) {        return None;    }    let mut out = String::with_capacity(text.len() + 2);    out.push('"');    for ch in text.chars() {        if ch == '"' || ch == '\\' {            out.push('\\');        }        out.push(ch);    }    out.push('"');    Some(out)}#[cfg(test)]mod tests {    use super::*;    fn read(raw: &[u8]) -> Response {        let end = complete_response(raw).expect("reads").expect("a whole response");        parse_response(&raw[..end]).expect("a response")    }    #[test]    fn a_fetch_with_gmail_items_and_a_literal_body_reads_whole() {        let raw = b"* 3 FETCH (UID 41 X-GM-MSGID 1278455344230334865 X-GM-THRID 1266894439832287888 X-GM-LABELS (\\Inbox \"Work stuff\" \\Starred) FLAGS (\\Seen) BODY[] {11}\r\nHello\r\nWorl)\r\n";        let response = read(raw);        assert_eq!(response.numbered(), Some((3, "FETCH")));        let items = response.values[2].as_list().expect("the fetch list");        assert_eq!(items[0], Value::Atom("UID".into()));        assert_eq!(items[1], Value::Atom("41".into()));        assert_eq!(items[6], Value::Atom("X-GM-LABELS".into()));        assert_eq!(            items[7],            Value::List(vec![                Value::Atom("\\Inbox".into()),                Value::Bytes(b"Work stuff".to_vec()),                Value::Atom("\\Starred".into()),            ])        );        assert_eq!(items[10], Value::Atom("BODY[]".into()));        assert_eq!(items[11], Value::Bytes(b"Hello\r\nWorl".to_vec()));    }    #[test]    fn a_status_code_in_brackets_is_one_atom() {        let response = read(b"* OK [UIDVALIDITY 3857529045] UIDs valid\r\n");        assert_eq!(response.status(), Some("OK"));        assert_eq!(            response.code(),            Some(vec!["UIDVALIDITY".to_string(), "3857529045".to_string()])        );    }    #[test]    fn a_message_past_the_ceiling_is_refused_before_it_is_held() {        let raw = format!("* 1 FETCH (BODY[] {{{}}}\r\n", LITERAL_MAX + 1);        assert!(matches!(            complete_response(raw.as_bytes()),            Err(WireError::LiteralTooLarge(_))        ));    }    #[test]    fn a_response_cut_mid_literal_waits_for_the_rest() {        let raw = b"* 1 FETCH (UID 4 BODY[] {10}\r\nabc";        assert_eq!(complete_response(raw).unwrap(), None);        let whole = b"* 1 FETCH (UID 4 BODY[] {3}\r\nabc)\r\nC1 OK done\r\n";        assert_eq!(complete_response(whole).unwrap(), Some(35));    }    #[test]    fn a_password_with_a_line_break_is_never_quoted_into_a_command() {        assert_eq!(quote("ab\"c\\d").as_deref(), Some("\"ab\\\"c\\\\d\""));        assert_eq!(quote("abc\r\nA2 DELETE INBOX"), None);    }}