//! The phone's IMAP reader for This phone fetches (Post CONTRACT row 12), on the core's own socket //! (`cotton_client::transport::wire`: Security.framework on Apple, rustls with Mozilla's roots elsewhere), so no //! TLS is added to the phone. It reads: LOGIN, EXAMINE (never SELECT), UID SEARCH and UID FETCH with BODY.PEEK, so a //! fetch never marks a message read. The wire parser and the reading commands are the Mac's //! (`cotton-mac/src/mail/{proto,client}.rs`), copied as the Mac copied them from cotton-server. use std::io::{ErrorKind, Read, Write}; use std::time::Duration; use cotton_client::transport::wire::{dial, Origin, Wire}; pub const COMMAND_WAIT: Duration = Duration::from_secs(120); pub const CONNECT_WAIT: Duration = Duration::from_secs(20); #[derive(Debug)] pub enum ImapError { /// The server refused the address and app password: a new one is needed, not a retry. SignIn(String), Refused { command: String, said: String }, Timeout(Duration), Connect(String), Wire(WireError), } impl std::fmt::Display for ImapError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ImapError::SignIn(said) => write!(f, "the mail server refused the sign-in: {said}"), ImapError::Refused { command, said } => write!(f, "the mail server refused {command}: {said}"), ImapError::Timeout(wait) => write!(f, "the mail server did not answer within {} s", wait.as_secs()), ImapError::Connect(why) => write!(f, "cannot reach the mail server: {why}"), ImapError::Wire(error) => write!(f, "{error}"), } } } impl From for ImapError { fn from(error: WireError) -> Self { ImapError::Wire(error) } } /// Where an IMAP server is. `tls: false` is for this machine's loopback alone (a test's scripted server): an app /// password never crosses a network in the clear. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Server { pub host: String, pub port: u16, pub tls: bool, } pub fn connect(server: &Server) -> Result { let loopback = server.host.parse::().is_ok_and(|ip| ip.is_loopback()) || server.host == "localhost"; if !server.tls && !loopback { return Err(ImapError::Connect(format!("{} is not this phone, and Cotton sends a password to another machine only over TLS", server.host))); } let scheme = if server.tls { "https" } else { "http" }; let origin = Origin::parse(&format!("{scheme}://{}:{}", server.host, server.port)).map_err(ImapError::Connect)?; let wire = dial(&origin, CONNECT_WAIT).map_err(ImapError::Connect)?; Ok(wire) } use proto::{complete_response, parse_response, quote, Response, Value, WireError}; /// What EXAMINE said about a mailbox. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct MailboxState { pub uid_validity: u32, pub uid_next: u32, pub exists: u32, /// CONDSTORE's counter, when the server keeps one. pub highest_modseq: Option, } /// One message as a FETCH answered it. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Fetched { pub uid: u32, pub gm_msgid: Option, pub gm_thrid: Option, pub gm_labels: Vec, pub flags: Vec, pub modseq: Option, pub body: Option>, /// INTERNALDATE — when the mailbox received the message — in milliseconds. pub internal_date: Option, /// The Message-ID out of ENVELOPE, as the header spells it. pub message_id: Option, /// RFC822.SIZE: the whole message's bytes. pub size: Option, } /// The special-use mailboxes an account names (RFC 6154). #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct SpecialUse { pub all: Option, pub trash: Option, pub junk: Option, pub archive: Option, } pub struct ImapClient { stream: Wire, buf: Vec, timeout: Option, next_tag: u32, pub capabilities: Vec, } fn timed_out(error: &std::io::Error) -> bool { matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) } impl ImapClient { /// Take a dialled stream and read the greeting. pub fn start(stream: Wire) -> Result { let mut client = ImapClient { stream, buf: Vec::new(), timeout: None, next_tag: 1, capabilities: Vec::new() }; let greeting = client.next(COMMAND_WAIT)?; if greeting.status() == Some("BYE") { return Err(ImapError::Connect(greeting.text)); } Ok(client) } /// The next whole response, or `None` when `wait` passed with none. fn poll(&mut self, wait: Duration) -> Result, ImapError> { loop { if let Some(end) = complete_response(&self.buf)? { let response = parse_response(&self.buf[..end])?; self.buf.drain(..end); return Ok(Some(response)); } if self.timeout != Some(wait) { self.stream.set_read_timeout(wait).map_err(WireError::from)?; self.timeout = Some(wait); } let mut chunk = [0u8; 64 * 1024]; match self.stream.read(&mut chunk) { Ok(0) => return Err(WireError::Closed.into()), Ok(n) => self.buf.extend_from_slice(&chunk[..n]), Err(error) if timed_out(&error) => return Ok(None), Err(error) if error.kind() == ErrorKind::Interrupted => {} Err(error) => return Err(WireError::from(error).into()), } } } fn next(&mut self, wait: Duration) -> Result { self.poll(wait)?.ok_or(ImapError::Timeout(wait)) } fn write_line(&mut self, line: &str) -> Result<(), ImapError> { self.stream .write_all(format!("{line}\r\n").as_bytes()) .map_err(WireError::from)?; self.stream.flush().map_err(WireError::from)?; Ok(()) } fn send(&mut self, line: &str) -> Result { let tag = format!("C{}", self.next_tag); self.next_tag += 1; self.write_line(&format!("{tag} {line}"))?; Ok(tag) } /// Run one command; the untagged answers it drew, once it is OK. /// /// `shown` is how the command is NAMED in an error — never the line itself, /// which for LOGIN holds the password. fn command(&mut self, line: &str, shown: &str) -> Result, ImapError> { let tag = self.send(line)?; let mut untagged = Vec::new(); loop { let response = self.next(COMMAND_WAIT)?; if response.tag == tag { return match response.status() { Some("OK") => Ok(untagged), _ => Err(ImapError::Refused { command: shown.to_string(), said: response.text, }), }; } if response.is_untagged() && response.status() == Some("BYE") { return Err(ImapError::Refused { command: shown.to_string(), said: response.text, }); } untagged.push(response); } } pub fn login(&mut self, user: &str, password: &str) -> Result<(), ImapError> { let (Some(user), Some(password)) = (quote(user), quote(password)) else { return Err(ImapError::SignIn( "the address or app password holds a line break".to_string(), )); }; match self.command(&format!("LOGIN {user} {password}"), "LOGIN") { Ok(_) => {} Err(ImapError::Refused { said, .. }) => return Err(ImapError::SignIn(said)), Err(other) => return Err(other), } let answers = self.command("CAPABILITY", "CAPABILITY")?; self.capabilities = answers .iter() .filter(|r| r.values.first().and_then(Value::as_atom) == Some("CAPABILITY")) .flat_map(|r| r.values[1..].iter().filter_map(Value::as_text)) .map(|cap| cap.to_ascii_uppercase()) .collect(); Ok(()) } pub fn can(&self, capability: &str) -> bool { self.capabilities.iter().any(|c| c == capability) } /// The mailboxes LIST marks `\All`, `\Trash` and `\Junk`, by whatever /// names the account's language gives them. pub fn special_use(&mut self) -> Result { let list_all = format!("LIST {q}{q} {q}*{q}", q = '"'); let answers = self.command(&list_all, "LIST")?; let mut found = SpecialUse::default(); for answer in &answers { if answer.values.first().and_then(Value::as_atom) != Some("LIST") { continue; } let flags = answer.values.get(1).and_then(Value::as_list).unwrap_or(&[]); let Some(name) = answer.values.get(3).and_then(Value::as_text) else { continue; }; for flag in flags.iter().filter_map(Value::as_atom) { let slot = if flag.eq_ignore_ascii_case("\\All") { &mut found.all } else if flag.eq_ignore_ascii_case("\\Trash") { &mut found.trash } else if flag.eq_ignore_ascii_case("\\Junk") { &mut found.junk } else if flag.eq_ignore_ascii_case("\\Archive") { &mut found.archive } else { continue; }; slot.get_or_insert_with(|| name.clone()); } } Ok(found) } /// EXAMINE — read only, so nothing here can change the mailbox. pub fn examine(&mut self, mailbox: &str) -> Result { let name = quote(mailbox).ok_or_else(|| ImapError::Refused { command: "EXAMINE".to_string(), said: "a mailbox name with a line break".to_string(), })?; let condstore = if self.can("CONDSTORE") { " (CONDSTORE)" } else { "" }; let answers = self.command(&format!("EXAMINE {name}{condstore}"), "EXAMINE")?; Ok(state_of(&answers)) } /// `UID FETCH ()`, each answer read into a [`Fetched`]. pub fn uid_fetch(&mut self, set: &str, items: &str, changed_since: Option) -> Result, ImapError> { let modifier = changed_since .map(|modseq| format!(" (CHANGEDSINCE {modseq})")) .unwrap_or_default(); let answers = self.command(&format!("UID FETCH {set} ({items}){modifier}"), "FETCH")?; Ok(answers.iter().filter_map(read_fetch).collect()) } /// `UID SEARCH ` — the UIDs that match, in the server's order. pub fn uid_search(&mut self, criteria: &str) -> Result, ImapError> { let answers = self.command(&format!("UID SEARCH {criteria}"), "SEARCH")?; Ok(answers .iter() .filter(|answer| { answer.is_untagged() && answer.values.first().and_then(Value::as_atom) == Some("SEARCH") }) .flat_map(|answer| answer.values.iter().skip(1)) .filter_map(|value| value.as_atom()?.parse().ok()) .collect()) } pub fn logout(mut self) { let _ = self.command("LOGOUT", "LOGOUT"); } } /// What EXAMINE or SELECT said about the mailbox. fn state_of(answers: &[Response]) -> MailboxState { let mut state = MailboxState::default(); for answer in answers { if let Some((n, "EXISTS")) = answer.numbered() { state.exists = n; } let Some(code) = answer.code() else { continue }; let arg = code.get(1).map(String::as_str).unwrap_or_default(); match code.first().map(String::as_str) { Some("UIDVALIDITY") => state.uid_validity = arg.parse().unwrap_or(0), Some("UIDNEXT") => state.uid_next = arg.parse().unwrap_or(0), Some("HIGHESTMODSEQ") => state.highest_modseq = arg.parse().ok(), _ => {} } } state } fn number(value: Option<&Value>) -> Option { value?.as_atom()?.parse().ok() } fn texts(value: Option<&Value>) -> Vec { value .and_then(Value::as_list) .unwrap_or(&[]) .iter() .filter_map(Value::as_text) .collect() } /// `* n FETCH (UID 4 FLAGS (…) …)` → a [`Fetched`]; anything else → `None`. fn read_fetch(response: &Response) -> Option { if !matches!(response.numbered(), Some((_, "FETCH"))) { return None; } let items = response.values.get(2)?.as_list()?; let mut out = Fetched::default(); let mut i = 0; while i + 1 < items.len() { let key = items[i].as_atom().unwrap_or_default().to_ascii_uppercase(); let value = &items[i + 1]; match key.as_str() { "UID" => out.uid = number(Some(value)).unwrap_or(0) as u32, "X-GM-MSGID" => out.gm_msgid = number(Some(value)), "X-GM-THRID" => out.gm_thrid = number(Some(value)), "X-GM-LABELS" => out.gm_labels = texts(Some(value)), "FLAGS" => out.flags = texts(Some(value)), "INTERNALDATE" => { out.internal_date = value.as_text().and_then(|text| cotton_core::cotton_rules::mail::mail_date::internal_date_ms(&text)); } "RFC822.SIZE" => out.size = number(Some(value)), "MODSEQ" => out.modseq = number(value.as_list().and_then(<[Value]>::first)), // date, subject, from, sender, reply-to, to, cc, bcc, in-reply-to, // message-id (RFC 3501 §7.4.2). "ENVELOPE" => { out.message_id = value .as_list() .and_then(|fields| fields.get(9)) .and_then(Value::as_text); } key if key.starts_with("BODY[") => { if let Value::Bytes(bytes) = value { out.body = Some(bytes.clone()); } } _ => {} } i += 2; } (out.uid > 0).then_some(out) } // ── the wire (cotton-mac/src/mail/proto.rs) ── pub mod proto { //! 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), List(Vec), 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 { 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, /// 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) } /// `* …` — 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> { 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)] pub enum WireError { Closed, LineTooLong, LiteralTooLarge(u64), Malformed(String), Io(std::io::Error), } impl std::fmt::Display for WireError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { WireError::Closed => f.write_str("the mail server closed the connection"), WireError::LineTooLong => f.write_str("the mail server sent a line longer than Cotton reads"), WireError::LiteralTooLarge(n) => write!(f, "the mail server offered a message of {n} bytes, past what Cotton holds in memory"), WireError::Malformed(what) => write!(f, "the mail server sent something Cotton could not read: {what}"), WireError::Io(error) => write!(f, "{error}"), } } } impl From for WireError { fn from(error: std::io::Error) -> Self { WireError::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, 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 { 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 { 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 { // 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 { 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 { 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 { 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) } }