Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/spark-mail-rs/src/imap.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / spark-mail-rs / src / imap.rs` 992 lines · 36253 bytes Raw Blame History 1 //! Minimal IMAP4rev1 client (RFC 3501) for the Gandi mailbox reader. 2 //! 3 //! It speaks only the five commands the reader sends: LOGIN, EXAMINE, 4 //! UID SEARCH, UID FETCH and LOGOUT. The caller owns the stream (TLS stays on 5 //! native-tls). This module never logs, and no error it returns carries a 6 //! credential. Every server reply is bounded: line length, literal size, 7 //! untagged responses and bytes per command, and search results all have hard 8 //! caps, and overflow is a typed refusal, never a silent truncation. 9 10 use std::fmt; 11 use std::io::{ErrorKind, Read, Write}; 12 13 /// Hard caps on what a server may send. Overflow is refused, never truncated. 14 #[derive(Clone, Copy, Debug)] 15 pub struct Limits { 16 /// Longest response line, CRLF excluded (a whole `* SEARCH` reply is one line). 17 pub line: usize, 18 /// Largest single `{n}` literal. 19 pub literal: usize, 20 /// Most untagged responses accepted for one command. 21 pub responses: usize, 22 /// Most response bytes (lines plus literals) accepted for one command. Every line 23 /// and literal also costs `ENTRY_COST` bytes, so a flood of empty literals is bounded 24 /// by the memory it really takes, not only by its size on the wire. 25 pub command_bytes: usize, 26 /// Most UIDs accepted from one search. 27 pub uids: usize, 28 } 29 30 /// Budget charged for each line and literal on top of its bytes: the allocation and 31 /// bookkeeping one entry costs whatever its length. 32 const ENTRY_COST: usize = 64; 33 34 impl Default for Limits { 35 fn default() -> Self { 36 Self { 37 line: 1024 * 1024, 38 literal: 32 * 1024 * 1024, 39 responses: 10_000, 40 command_bytes: 64 * 1024 * 1024, 41 uids: 200_000, 42 } 43 } 44 } 45 46 /// Why an IMAP exchange was refused. No variant carries a credential. 47 #[derive(Debug, Eq, PartialEq)] 48 pub enum ImapError { 49 Io(ErrorKind), 50 /// The server closed the stream in the middle of a line or literal. 51 Truncated, 52 LineTooLong, 53 LiteralTooLarge, 54 TooManyResponses, 55 CommandTooLarge, 56 TooManyUids, 57 Malformed(&'static str), 58 /// A command argument holds CR, LF or NUL, which IMAP cannot carry. 59 UnsafeArgument, 60 /// Tagged NO, with the server's text reduced to printable ASCII. 61 No(String), 62 /// Tagged BAD, with the server's text reduced to printable ASCII. 63 Bad(String), 64 /// Untagged BYE where none was expected. 65 Bye(String), 66 } 67 68 impl fmt::Display for ImapError { 69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 70 match self { 71 Self::Io(kind) => write!(f, "IMAP stream error: {kind}"), 72 Self::Truncated => f.write_str("IMAP server closed the stream mid-response"), 73 Self::LineTooLong => f.write_str("IMAP response line exceeds the line limit"), 74 Self::LiteralTooLarge => f.write_str("IMAP literal exceeds the literal limit"), 75 Self::TooManyResponses => f.write_str("IMAP command drew too many responses"), 76 Self::CommandTooLarge => f.write_str("IMAP command drew too many response bytes"), 77 Self::TooManyUids => f.write_str("IMAP search returned too many UIDs"), 78 Self::Malformed(what) => write!(f, "malformed IMAP response: {what}"), 79 Self::UnsafeArgument => f.write_str("IMAP argument holds CR, LF or NUL"), 80 Self::No(text) => write!(f, "IMAP server said NO: {text}"), 81 Self::Bad(text) => write!(f, "IMAP server said BAD: {text}"), 82 Self::Bye(text) => write!(f, "IMAP server said BYE: {text}"), 83 } 84 } 85 } 86 87 impl std::error::Error for ImapError {} 88 89 /// Which part of a message `uid_fetch` returns. Both use `BODY.PEEK`, so the 90 /// read never sets the `\Seen` flag. 91 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 92 pub enum Section { 93 Header, 94 Full, 95 } 96 97 pub struct Client { 98 stream: S, 99 limits: Limits, 100 /// Bytes read from the stream and not yet consumed. 101 buf: Vec, 102 next_tag: u32, 103 } 104 105 /// One server response: the text around each literal, then the literals. 106 /// `text.len() == literals.len() + 1`. 107 struct Response { 108 text: Vec>, 109 literals: Vec>, 110 } 111 112 /// One encoded command argument. 113 enum Arg<'a> { 114 Atom(&'a str), 115 Quoted(Vec), 116 /// Sent as a synchronizing literal: `{n}`, wait for `+`, then the bytes. 117 Literal(&'a [u8]), 118 } 119 120 impl<'a> Arg<'a> { 121 /// An IMAP string: quoted when 7-bit, a literal when it holds 8-bit 122 /// bytes, refused when it holds CR, LF or NUL (RFC 3501 section 4.3). 123 fn string(value: &'a str) -> Result { 124 let bytes = value.as_bytes(); 125 if bytes.iter().any(|&b| matches!(b, b'\r' | b'\n' | 0)) { 126 return Err(ImapError::UnsafeArgument); 127 } 128 if !bytes.is_ascii() { 129 return Ok(Self::Literal(bytes)); 130 } 131 let mut quoted = Vec::with_capacity(bytes.len() + 2); 132 quoted.push(b'"'); 133 for &b in bytes { 134 if b == b'"' || b == b'\\' { 135 quoted.push(b'\\'); 136 } 137 quoted.push(b); 138 } 139 quoted.push(b'"'); 140 Ok(Self::Quoted(quoted)) 141 } 142 } 143 144 impl Client { 145 /// Read the server greeting with the default limits. 146 pub fn connect(stream: S) -> Result { 147 Self::with_limits(stream, Limits::default()) 148 } 149 150 pub fn with_limits(stream: S, limits: Limits) -> Result { 151 let mut client = Self { 152 stream, 153 limits, 154 buf: Vec::new(), 155 next_tag: 1, 156 }; 157 // A greeting is one line; it gets one line's worth of budget. 158 let mut budget = limits.line.saturating_add(2 + ENTRY_COST); 159 let greeting = client.read_response(&mut budget)?; 160 if let Some(text) = untagged(&greeting.text[0], b"BYE") { 161 return Err(ImapError::Bye(printable(text))); 162 } 163 if untagged(&greeting.text[0], b"OK").is_none() { 164 return Err(ImapError::Malformed("server greeting is not * OK")); 165 } 166 Ok(client) 167 } 168 169 pub fn login(&mut self, user: &str, password: &str) -> Result<(), ImapError> { 170 let args = [ 171 Arg::Atom("LOGIN"), 172 Arg::string(user)?, 173 Arg::string(password)?, 174 ]; 175 self.run(&args, false).map(drop) 176 } 177 178 /// Open a mailbox read-only. 179 pub fn examine(&mut self, mailbox: &str) -> Result<(), ImapError> { 180 self.run(&[Arg::Atom("EXAMINE"), Arg::string(mailbox)?], false) 181 .map(drop) 182 } 183 184 pub fn uid_search_all(&mut self) -> Result, ImapError> { 185 let args = [Arg::Atom("UID"), Arg::Atom("SEARCH"), Arg::Atom("ALL")]; 186 let mut uids = Vec::new(); 187 for response in self.run(&args, false)? { 188 let Some(rest) = untagged(&response.text[0], b"SEARCH") else { 189 continue; 190 }; 191 if !response.literals.is_empty() { 192 return Err(ImapError::Malformed("search result carries a literal")); 193 } 194 for token in rest.split(|&b| b == b' ').filter(|t| !t.is_empty()) { 195 if uids.len() == self.limits.uids { 196 return Err(ImapError::TooManyUids); 197 } 198 uids.push( 199 parse_uid(token).ok_or(ImapError::Malformed("search result is not a UID"))?, 200 ); 201 } 202 } 203 Ok(uids) 204 } 205 206 /// The requested section of message `uid`, or `None` when the server 207 /// returns no such message. 208 pub fn uid_fetch(&mut self, uid: u32, section: Section) -> Result>, ImapError> { 209 let (request, reply) = match section { 210 Section::Header => ("BODY.PEEK[HEADER]", &b"BODY[HEADER]"[..]), 211 Section::Full => ("BODY.PEEK[]", &b"BODY[]"[..]), 212 }; 213 let uid_text = uid.to_string(); 214 let args = [ 215 Arg::Atom("UID"), 216 Arg::Atom("FETCH"), 217 Arg::Atom(&uid_text), 218 Arg::Atom(request), 219 ]; 220 for response in self.run(&args, false)? { 221 // Servers may interleave unsolicited FETCH data for other messages. 222 if !is_fetch(&response.text[0]) || fetch_uid(&response) != Some(uid) { 223 continue; 224 } 225 // A body sent as a quoted string would read as missing; refuse it. NIL (no 226 // such section) stays `None`. 227 if response.text.iter().any(|text| quotes_section(text, reply)) { 228 return Err(ImapError::Malformed("section sent as a quoted string")); 229 } 230 for (text, literal) in response.text.iter().zip(response.literals) { 231 if names_section(text, reply) { 232 return Ok(Some(literal)); 233 } 234 } 235 } 236 Ok(None) 237 } 238 239 pub fn logout(&mut self) -> Result<(), ImapError> { 240 self.run(&[Arg::Atom("LOGOUT")], true).map(drop) 241 } 242 243 /// Send one tagged command and collect its untagged responses up to the 244 /// tagged OK. Arguments are encoded before anything is sent, so a refused 245 /// argument leaves the stream untouched. 246 fn run(&mut self, args: &[Arg<'_>], expect_bye: bool) -> Result, ImapError> { 247 let tag = format!("A{:04}", self.next_tag); 248 self.next_tag += 1; 249 let mut budget = self.limits.command_bytes; 250 let mut seen = 0; 251 let mut line = tag.clone().into_bytes(); 252 for arg in args { 253 line.push(b' '); 254 match arg { 255 Arg::Atom(atom) => line.extend_from_slice(atom.as_bytes()), 256 Arg::Quoted(quoted) => line.extend_from_slice(quoted), 257 Arg::Literal(bytes) => { 258 line.extend_from_slice(format!("{{{}}}\r\n", bytes.len()).as_bytes()); 259 self.send(&line)?; 260 line.clear(); 261 self.await_continuation(&tag, &mut budget, &mut seen)?; 262 line.extend_from_slice(bytes); 263 } 264 } 265 } 266 line.extend_from_slice(b"\r\n"); 267 self.send(&line)?; 268 let mut responses = Vec::new(); 269 loop { 270 let response = self.read_response(&mut budget)?; 271 if let Some(rest) = tagged(&response.text[0], &tag) { 272 return tagged_status(rest).map(|()| responses); 273 } 274 self.check_untagged(&response.text[0], expect_bye, &mut seen)?; 275 responses.push(response); 276 } 277 } 278 279 /// Wait for the `+` that lets a literal be sent. A tagged NO or BAD here 280 /// means the server refused the command, and the literal is never sent. 281 fn await_continuation( 282 &mut self, 283 tag: &str, 284 budget: &mut usize, 285 seen: &mut usize, 286 ) -> Result<(), ImapError> { 287 loop { 288 let response = self.read_response(budget)?; 289 let first = &response.text[0]; 290 if first.starts_with(b"+") { 291 return Ok(()); 292 } 293 if let Some(rest) = tagged(first, tag) { 294 tagged_status(rest)?; 295 return Err(ImapError::Malformed( 296 "tagged OK before the literal was sent", 297 )); 298 } 299 self.check_untagged(first, false, seen)?; 300 } 301 } 302 303 fn check_untagged( 304 &self, 305 first: &[u8], 306 expect_bye: bool, 307 seen: &mut usize, 308 ) -> Result<(), ImapError> { 309 if first.starts_with(b"+") { 310 return Err(ImapError::Malformed("unexpected continuation request")); 311 } 312 if !first.starts_with(b"* ") { 313 return Err(ImapError::Malformed("response with a foreign tag")); 314 } 315 if let Some(text) = untagged(first, b"BYE") 316 && !expect_bye 317 { 318 return Err(ImapError::Bye(printable(text))); 319 } 320 if *seen == self.limits.responses { 321 return Err(ImapError::TooManyResponses); 322 } 323 *seen += 1; 324 Ok(()) 325 } 326 327 fn send(&mut self, bytes: &[u8]) -> Result<(), ImapError> { 328 self.stream 329 .write_all(bytes) 330 .map_err(|e| ImapError::Io(e.kind()))?; 331 self.stream.flush().map_err(|e| ImapError::Io(e.kind())) 332 } 333 334 /// One response: a line, plus a literal and a further line for every 335 /// line that ends in `{n}`. Only untagged responses carry literals: a tagged 336 /// status or `+` line ending in `{n}` is just text. 337 fn read_response(&mut self, budget: &mut usize) -> Result { 338 let mut text = Vec::new(); 339 let mut literals = Vec::new(); 340 loop { 341 let line = self.read_line(budget)?; 342 let literal = if text.is_empty() && !line.starts_with(b"* ") { 343 None 344 } else { 345 literal_len(&line)? 346 }; 347 text.push(line); 348 let Some(len) = literal else { 349 return Ok(Response { text, literals }); 350 }; 351 if len > self.limits.literal { 352 return Err(ImapError::LiteralTooLarge); 353 } 354 charge(budget, len.saturating_add(ENTRY_COST))?; 355 literals.push(self.read_exact(len)?); 356 } 357 } 358 359 /// The next CRLF-terminated line, CRLF removed. 360 fn read_line(&mut self, budget: &mut usize) -> Result, ImapError> { 361 let mut scanned = 0; 362 loop { 363 if let Some(pos) = self.buf[scanned..].windows(2).position(|w| w == b"\r\n") { 364 let pos = scanned + pos; 365 if pos > self.limits.line { 366 return Err(ImapError::LineTooLong); 367 } 368 charge(budget, pos + 2 + ENTRY_COST)?; 369 let mut line: Vec = self.buf.drain(..pos + 2).collect(); 370 line.truncate(pos); 371 return Ok(line); 372 } 373 // The buffer may end in the CR of a line exactly at the limit. 374 if self.buf.len() > self.limits.line.saturating_add(1) { 375 return Err(ImapError::LineTooLong); 376 } 377 scanned = self.buf.len().saturating_sub(1); 378 if self.fill()? == 0 { 379 return Err(ImapError::Truncated); 380 } 381 } 382 } 383 384 /// Exactly `len` bytes. Nothing is reserved up front, so a server that 385 /// announces a literal and then stops costs only what it really sent. 386 fn read_exact(&mut self, len: usize) -> Result, ImapError> { 387 while self.buf.len() < len { 388 if self.fill()? == 0 { 389 return Err(ImapError::Truncated); 390 } 391 } 392 Ok(self.buf.drain(..len).collect()) 393 } 394 395 fn fill(&mut self) -> Result { 396 let mut chunk = [0u8; 16 * 1024]; 397 loop { 398 match self.stream.read(&mut chunk) { 399 Ok(n) => { 400 self.buf.extend_from_slice(&chunk[..n]); 401 return Ok(n); 402 } 403 Err(e) if e.kind() == ErrorKind::Interrupted => continue, 404 Err(e) => return Err(ImapError::Io(e.kind())), 405 } 406 } 407 } 408 } 409 410 fn charge(budget: &mut usize, bytes: usize) -> Result<(), ImapError> { 411 *budget = budget 412 .checked_sub(bytes) 413 .ok_or(ImapError::CommandTooLarge)?; 414 Ok(()) 415 } 416 417 /// `Some(n)` when the line ends in a literal announcement `{n}`. 418 fn literal_len(line: &[u8]) -> Result, ImapError> { 419 let Some(body) = line.strip_suffix(b"}") else { 420 return Ok(None); 421 }; 422 let Some(open) = body.iter().rposition(|&b| b == b'{') else { 423 return Ok(None); 424 }; 425 let digits = &body[open + 1..]; 426 if digits.is_empty() || !digits.iter().all(u8::is_ascii_digit) { 427 return Ok(None); 428 } 429 let mut len: usize = 0; 430 for &d in digits { 431 len = len 432 .checked_mul(10) 433 .and_then(|len| len.checked_add(usize::from(d - b'0'))) 434 .ok_or(ImapError::LiteralTooLarge)?; 435 } 436 Ok(Some(len)) 437 } 438 439 fn split_word(s: &[u8]) -> (&[u8], &[u8]) { 440 match s.iter().position(|&b| b == b' ') { 441 Some(p) => (&s[..p], &s[p + 1..]), 442 None => (s, &[]), 443 } 444 } 445 446 /// The text after `* WORD`, when the line is that untagged response. 447 fn untagged<'a>(line: &'a [u8], word: &[u8]) -> Option<&'a [u8]> { 448 let (first, text) = split_word(line.strip_prefix(b"* ")?); 449 first.eq_ignore_ascii_case(word).then_some(text) 450 } 451 452 fn tagged<'a>(line: &'a [u8], tag: &str) -> Option<&'a [u8]> { 453 line.strip_prefix(tag.as_bytes())?.strip_prefix(b" ") 454 } 455 456 fn tagged_status(rest: &[u8]) -> Result<(), ImapError> { 457 let (word, text) = split_word(rest); 458 if word.eq_ignore_ascii_case(b"OK") { 459 Ok(()) 460 } else if word.eq_ignore_ascii_case(b"NO") { 461 Err(ImapError::No(printable(text))) 462 } else if word.eq_ignore_ascii_case(b"BAD") { 463 Err(ImapError::Bad(printable(text))) 464 } else { 465 Err(ImapError::Malformed("tagged response is not OK, NO or BAD")) 466 } 467 } 468 469 /// Server text reduced to printable ASCII and at most 200 characters, so it 470 /// can be shown without carrying terminal escapes. 471 fn printable(text: &[u8]) -> String { 472 text.iter() 473 .filter(|b| (0x20..=0x7e).contains(*b)) 474 .take(200) 475 .map(|&b| char::from(b)) 476 .collect() 477 } 478 479 fn parse_uid(token: &[u8]) -> Option { 480 if token.is_empty() || token.len() > 10 || !token.iter().all(u8::is_ascii_digit) { 481 return None; 482 } 483 std::str::from_utf8(token) 484 .ok()? 485 .parse::() 486 .ok() 487 .filter(|&uid| uid != 0) 488 } 489 490 /// `* FETCH ...` 491 fn is_fetch(line: &[u8]) -> bool { 492 let Some(rest) = line.strip_prefix(b"* ") else { 493 return false; 494 }; 495 let (number, rest) = split_word(rest); 496 !number.is_empty() 497 && number.iter().all(u8::is_ascii_digit) 498 && rest.len() >= 5 499 && rest[..5].eq_ignore_ascii_case(b"FETCH") 500 } 501 502 /// The value of the `UID` item in a FETCH response. 503 fn fetch_uid(response: &Response) -> Option { 504 response.text.iter().find_map(|text| { 505 (1..text.len().saturating_sub(3)).find_map(|i| { 506 if !matches!(text[i - 1], b'(' | b' ') || !text[i..i + 4].eq_ignore_ascii_case(b"UID ") 507 { 508 return None; 509 } 510 let digits = &text[i + 4..]; 511 let end = digits 512 .iter() 513 .position(|b| !b.is_ascii_digit()) 514 .unwrap_or(digits.len()); 515 parse_uid(&digits[..end]) 516 }) 517 }) 518 } 519 520 /// Whether `text` carries `name` as a quoted string, as in `... BODY[] "..."`. 521 fn quotes_section(text: &[u8], name: &[u8]) -> bool { 522 let mut quoted = name.to_vec(); 523 quoted.extend_from_slice(b" \""); 524 text.windows(quoted.len()).enumerate().any(|(i, w)| { 525 w.eq_ignore_ascii_case("ed) && i > 0 && matches!(text[i - 1], b'(' | b' ') 526 }) 527 } 528 529 /// Whether the text before a literal names `name` as the item it carries, 530 /// as in `... BODY[HEADER] {123}`. 531 fn names_section(text: &[u8], name: &[u8]) -> bool { 532 let Some(open) = text.iter().rposition(|&b| b == b'{') else { 533 return false; 534 }; 535 let head = text[..open].trim_ascii_end(); 536 head.len() > name.len() 537 && head[head.len() - name.len()..].eq_ignore_ascii_case(name) 538 && matches!(head[head.len() - name.len() - 1], b'(' | b' ') 539 } 540 541 #[cfg(test)] 542 mod tests { 543 use super::*; 544 use std::io::Cursor; 545 546 /// A scripted server: replies are read from `input`, at most `chunk` bytes per 547 /// read, and client writes are kept. 548 struct Script { 549 input: Cursor>, 550 chunk: usize, 551 written: Vec, 552 } 553 554 impl Script { 555 fn new(replies: &[u8]) -> Self { 556 Self { 557 input: Cursor::new(replies.to_vec()), 558 chunk: usize::MAX, 559 written: Vec::new(), 560 } 561 } 562 563 /// A server that hands over one byte per read. 564 fn trickle(replies: &[u8]) -> Self { 565 Self { 566 chunk: 1, 567 ..Self::new(replies) 568 } 569 } 570 } 571 572 impl Read for Script { 573 fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 574 let n = buf.len().min(self.chunk); 575 self.input.read(&mut buf[..n]) 576 } 577 } 578 579 impl Write for Script { 580 fn write(&mut self, buf: &[u8]) -> std::io::Result { 581 self.written.extend_from_slice(buf); 582 Ok(buf.len()) 583 } 584 fn flush(&mut self) -> std::io::Result<()> { 585 Ok(()) 586 } 587 } 588 589 const GREETING: &[u8] = b"* OK [CAPABILITY IMAP4rev1] Dovecot ready.\r\n"; 590 591 fn client(replies: &[u8]) -> Client