//! A reading IMAP client: log in, find the mailbox, fetch, IDLE. The reading //! never writes to the mailbox — EXAMINE, never SELECT, and BODY.PEEK so a fetch //! never marks a message read. //! //! The one writing act is the owner's own, asked from the phone: moving one //! sender's mail to the provider's Trash ([`super::trash`]). It alone SELECTs, //! and it only MOVEs (or, on Gmail without MOVE, COPYs into Trash, which Gmail //! makes a move). Nothing here STOREs a flag or EXPUNGEs. //! //! Copied from `cotton-server`'s `mailbox::imap_client` (that crate retires on //! its own) and made blocking. The transport is any [`Stream`]: TLS from the //! first byte for a real server, a plain socket to this Mac's loopback for a //! local bridge or a test's scripted server. use std::io::{ErrorKind, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::sync::Arc; use std::time::{Duration, Instant}; use super::proto::{complete_response, parse_response, quote, Response, Value, WireError}; /// How long one command may wait for the server's next line. Generous — a /// fetch of a large message over a slow link — and finite, so a server that /// stops talking ends the run rather than holding it for ever. pub const COMMAND_WAIT: Duration = Duration::from_secs(120); /// How long to wait for the TCP and TLS handshakes. pub const CONNECT_WAIT: Duration = Duration::from_secs(20); /// How often an IDLE looks up to see whether the app is stopping. const IDLE_TICK: Duration = Duration::from_secs(1); /// A byte stream to the server whose reads can time out. pub trait Stream: Read + Write + Send { fn set_timeout(&mut self, wait: Option) -> std::io::Result<()>; } impl Stream for TcpStream { fn set_timeout(&mut self, wait: Option) -> std::io::Result<()> { self.set_read_timeout(wait) } } impl Stream for rustls::StreamOwned { fn set_timeout(&mut self, wait: Option) -> std::io::Result<()> { self.sock.set_read_timeout(wait) } } #[derive(Debug, thiserror::Error)] pub enum ImapError { /// The server refused the address and app password: the person needs to /// give a new one, not a retry. #[error("the mail server refused the sign-in: {0}")] SignIn(String), #[error("the mail server refused {command}: {said}")] Refused { command: String, said: String }, #[error("the mail server did not answer within {} s", .0.as_secs())] Timeout(Duration), #[error("cannot reach the mail server: {0}")] Connect(String), #[error(transparent)] Wire(#[from] WireError), } /// Where an IMAP server is. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Server { pub host: String, pub port: u16, pub tls: bool, } /// 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, } /// How an IDLE ended. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Idled { /// The mailbox changed: new mail, a flag, an expunge. Changed, /// The window ran out with nothing said. Quiet, /// The app is stopping. Stopped, } /// What [`ImapClient::uid_store`] may set or clear. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Mark { /// Read. Seen, /// Gmail's Inbox label: cleared, the mail is archived (it stays in All Mail). Inbox, } /// 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, } /// Dial `server`: TLS from the first byte (port 993), the only way Cotton /// speaks IMAP to anything but this machine. A plaintext socket is offered to /// a LOOPBACK address only — a local bridge, or a test's fake server — so an /// app password never crosses a network in the clear. pub fn dial(server: &Server) -> Result, ImapError> { let Server { host, port, tls } = server; let addr = (host.as_str(), *port) .to_socket_addrs() .map_err(|error| ImapError::Connect(format!("{host}:{port}: {error}")))? .next() .ok_or_else(|| ImapError::Connect(format!("{host}:{port}: no address")))?; if !tls && !addr.ip().is_loopback() { return Err(ImapError::Connect(format!( "{host}:{port} is not on this machine, and Cotton sends a password to another \ machine only over TLS" ))); } let socket = TcpStream::connect_timeout(&addr, CONNECT_WAIT) .map_err(|error| ImapError::Connect(format!("{host}:{port}: {error}")))?; let _ = socket.set_write_timeout(Some(COMMAND_WAIT)); if !tls { return Ok(Box::new(socket)); } let mut roots = rustls::RootCertStore::empty(); roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); let config = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) .with_safe_default_protocol_versions() .map_err(|error| ImapError::Connect(error.to_string()))? .with_root_certificates(roots) .with_no_client_auth(); let name = rustls::pki_types::ServerName::try_from(host.to_string()) .map_err(|error| ImapError::Connect(format!("{host}: {error}")))?; let connection = rustls::ClientConnection::new(Arc::new(config), name) .map_err(|error| ImapError::Connect(format!("{host}:{port}: {error}")))?; let _ = socket.set_read_timeout(Some(CONNECT_WAIT)); let mut stream = rustls::StreamOwned::new(connection, socket); // The handshake now, so a refused certificate names itself here. while stream.conn.is_handshaking() { stream .conn .complete_io(&mut stream.sock) .map_err(|error| ImapError::Connect(format!("{host}:{port}: {error}")))?; } Ok(Box::new(stream)) } pub struct ImapClient { stream: Box, /// Bytes read and not yet a whole response. buf: Vec, timeout: Option, next_tag: u32, pub capabilities: Vec, } impl std::fmt::Debug for ImapClient { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ImapClient") .field("capabilities", &self.capabilities) .finish_non_exhaustive() } } 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: Box) -> 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_timeout(Some(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()) } /// SELECT — for the Trash move alone ([`super::trash`]): the mailbox opened to be written. pub fn select(&mut self, mailbox: &str) -> Result { let name = quote(mailbox).ok_or_else(|| ImapError::Refused { command: "SELECT".to_string(), said: "a mailbox name with a line break".to_string() })?; let answers = self.command(&format!("SELECT {name}"), "SELECT")?; Ok(state_of(&answers)) } /// `UID MOVE ` (RFC 6851), or `UID COPY` where `copy` (Gmail without MOVE: a copy into Trash is /// Gmail's move). Only the Trash move calls it. pub fn uid_move(&mut self, set: &str, mailbox: &str, copy: bool) -> Result<(), ImapError> { let verb = if copy { "COPY" } else { "MOVE" }; let name = quote(mailbox).ok_or_else(|| ImapError::Refused { command: verb.to_string(), said: "a mailbox name with a line break".to_string() })?; self.command(&format!("UID {verb} {set} {name}"), verb).map(|_| ()) } /// `UID STORE ±`: the only flags the Mac ever writes, the owner's own acts from the phone /// ([`super::acts`]). [`Mark`] can say nothing else: never `\\Deleted`. pub fn uid_store(&mut self, set: &str, mark: Mark, on: bool) -> Result<(), ImapError> { let sign = if on { '+' } else { '-' }; let what = match mark { Mark::Seen => "FLAGS.SILENT (\\Seen)", Mark::Inbox => "X-GM-LABELS.SILENT (\\Inbox)", }; self.command(&format!("UID STORE {set} {sign}{what}"), "STORE").map(|_| ()) } /// `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()) } /// Wait in IDLE for at most `window`, looking up every second to ask /// `stopping`; DONE either way. pub fn idle(&mut self, window: Duration, stopping: &dyn Fn() -> bool) -> Result { let tag = self.send("IDLE")?; let ready = self.next(COMMAND_WAIT)?; if !ready.is_continuation() { return Err(ImapError::Refused { command: "IDLE".to_string(), said: ready.text, }); } let started = Instant::now(); let outcome = loop { if stopping() { break Idled::Stopped; } if started.elapsed() >= window { break Idled::Quiet; } let Some(response) = self.poll(IDLE_TICK.min(window))? else { continue; }; if response.status() == Some("BYE") { return Err(ImapError::Refused { command: "IDLE".to_string(), said: response.text, }); } if matches!(response.numbered(), Some((_, "EXISTS" | "EXPUNGE" | "FETCH"))) { break Idled::Changed; } }; self.write_line("DONE")?; loop { let response = self.next(COMMAND_WAIT)?; if response.tag == tag { return Ok(outcome); } } } 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| super::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) } #[cfg(test)] mod tests { use super::*; use std::io::{BufRead, BufReader}; use std::net::TcpListener; /// A server that answers each tagged command from `script` by its verb. fn scripted(script: fn(&str) -> Vec) -> Server { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); std::thread::spawn(move || { let (stream, _) = listener.accept().unwrap(); let mut writer = stream.try_clone().unwrap(); let mut reader = BufReader::new(stream); writer.write_all(b"* OK ready\r\n").unwrap(); loop { let mut line = String::new(); if reader.read_line(&mut line).unwrap_or(0) == 0 { return; } for out in script(line.trim_end()) { writer.write_all(out.as_bytes()).unwrap(); } } }); Server { host: "127.0.0.1".to_string(), port, tls: false } } #[test] fn a_plain_socket_is_offered_only_to_loopback() { let error = dial(&Server { host: "192.0.2.1".to_string(), port: 1, tls: false }); assert!(error.is_err()); } #[test] fn login_examine_fetch_and_idle_against_a_scripted_server() { let server = scripted(|line| { let (tag, rest) = line.split_once(' ').unwrap_or((line, "")); if line == "DONE" { return vec!["C5 OK idle done\r\n".to_string()]; } let verb = rest.split_whitespace().next().unwrap_or(""); match verb { "LOGIN" => vec![format!("{tag} OK in\r\n")], "CAPABILITY" => vec![ "* CAPABILITY IMAP4rev1 IDLE CONDSTORE\r\n".to_string(), format!("{tag} OK\r\n"), ], "EXAMINE" => vec![ "* 2 EXISTS\r\n".to_string(), "* OK [UIDVALIDITY 7] ok\r\n".to_string(), "* OK [UIDNEXT 3] ok\r\n".to_string(), "* OK [HIGHESTMODSEQ 90] ok\r\n".to_string(), format!("{tag} OK [READ-ONLY] done\r\n"), ], "UID" => vec![ "* 1 FETCH (UID 1 FLAGS (\\Seen) INTERNALDATE \"16-Sep-2024 18:03:30 +0000\" BODY[] {5}\r\nhello)\r\n".to_string(), format!("{tag} OK\r\n"), ], "IDLE" => vec!["+ idling\r\n".to_string(), "* 3 EXISTS\r\n".to_string()], _ => vec![format!("{tag} BAD what\r\n")], } }); let mut client = ImapClient::start(dial(&server).unwrap()).unwrap(); client.login("me@example.com", "pw").unwrap(); assert!(client.can("IDLE")); let state = client.examine("INBOX").unwrap(); assert_eq!(state, MailboxState { uid_validity: 7, uid_next: 3, exists: 2, highest_modseq: Some(90) }); let fetched = client.uid_fetch("1", "UID FLAGS INTERNALDATE BODY.PEEK[]", None).unwrap(); assert_eq!(fetched.len(), 1); assert_eq!(fetched[0].body.as_deref(), Some(&b"hello"[..])); assert_eq!(fetched[0].flags, vec!["\\Seen".to_string()]); assert!(fetched[0].internal_date.is_some()); assert_eq!(client.idle(Duration::from_secs(5), &|| false).unwrap(), Idled::Changed); } }