interplane.Get Omega
Read in your language

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

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
10use std::fmt;
11use 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)]
15pub 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.
32const ENTRY_COST: usize = 64;
33
34impl 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)]
48pub 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
68impl 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
87impl 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)]
92pub enum Section {
93 Header,
94 Full,
95}
96
97pub struct Client<S> {
98 stream: S,
99 limits: Limits,
100 /// Bytes read from the stream and not yet consumed.
101 buf: Vec<u8>,
102 next_tag: u32,
103}
104
105/// One server response: the text around each literal, then the literals.
106/// `text.len() == literals.len() + 1`.
107struct Response {
108 text: Vec<Vec<u8>>,
109 literals: Vec<Vec<u8>>,
110}
111
112/// One encoded command argument.
113enum Arg<'a> {
114 Atom(&'a str),
115 Quoted(Vec<u8>),
116 /// Sent as a synchronizing literal: `{n}`, wait for `+`, then the bytes.
117 Literal(&'a [u8]),
118}
119
120impl<'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<Self, ImapError> {
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
144impl<S: Read + Write> Client<S> {
145 /// Read the server greeting with the default limits.
146 pub fn connect(stream: S) -> Result<Self, ImapError> {
147 Self::with_limits(stream, Limits::default())
148 }
149
150 pub fn with_limits(stream: S, limits: Limits) -> Result<Self, ImapError> {
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<Vec<u32>, 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<Option<Vec<u8>>, 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<Vec<Response>, 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<Response, ImapError> {
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<Vec<u8>, 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<u8> = 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<Vec<u8>, 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<usize, ImapError> {
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
410fn 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}`.
418fn literal_len(line: &[u8]) -> Result<Option<usize>, 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
439fn 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.
447fn 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
452fn tagged<'a>(line: &'a [u8], tag: &str) -> Option<&'a [u8]> {
453 line.strip_prefix(tag.as_bytes())?.strip_prefix(b" ")
454}
455
456fn 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.
471fn 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
479fn parse_uid(token: &[u8]) -> Option<u32> {
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::<u32>()
486 .ok()
487 .filter(|&uid| uid != 0)
488}
489
490/// `* <n> FETCH ...`
491fn 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.
503fn fetch_uid(response: &Response) -> Option<u32> {
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[] "..."`.
521fn 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(&quoted) && 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}`.
531fn 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)]
542mod 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<Vec<u8>>,
550 chunk: usize,
551 written: Vec<u8>,
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<usize> {
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<usize> {
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<Script> {
592 let mut all = GREETING.to_vec();
593 all.extend_from_slice(replies);
594 Client::connect(Script::new(&all)).expect("greeting accepted")
595 }
596
597 fn small(replies: &[u8], limits: Limits) -> Result<Client<Script>, ImapError> {
598 let mut all = GREETING.to_vec();
599 all.extend_from_slice(replies);
600 Client::with_limits(Script::new(&all), limits)
601 }
602
603 fn written(client: &Client<Script>) -> String {
604 String::from_utf8_lossy(&client.stream.written).into_owned()
605 }
606
607 #[test]
608 fn reads_headers_and_bodies_through_the_five_commands() {
609 let header = b"From: a@example.com\r\nSubject: hi\r\n\r\n";
610 let body = b"From: a@example.com\r\nSubject: hi\r\n\r\nhello\r\n";
611 let mut replies = Vec::new();
612 replies.extend_from_slice(b"A0001 OK Logged in\r\n");
613 replies.extend_from_slice(
614 b"* 3 EXISTS\r\n* FLAGS (\\Seen)\r\nA0002 OK [READ-ONLY] Examine completed\r\n",
615 );
616 replies.extend_from_slice(b"* SEARCH 4 9 12\r\nA0003 OK Search completed\r\n");
617 replies.extend_from_slice(
618 format!("* 2 FETCH (UID 9 BODY[HEADER] {{{}}}\r\n", header.len()).as_bytes(),
619 );
620 replies.extend_from_slice(header);
621 replies.extend_from_slice(b")\r\nA0004 OK Fetch completed\r\n");
622 replies.extend_from_slice(
623 format!("* 3 FETCH (UID 12 BODY[] {{{}}}\r\n", body.len()).as_bytes(),
624 );
625 replies.extend_from_slice(body);
626 replies.extend_from_slice(b")\r\nA0005 OK Fetch completed\r\n");
627 replies.extend_from_slice(b"* BYE Logging out\r\nA0006 OK Logout completed\r\n");
628 let mut c = client(&replies);
629 c.login("aien@aienos.com", "pw").unwrap();
630 c.examine("INBOX").unwrap();
631 assert_eq!(c.uid_search_all().unwrap(), vec![4, 9, 12]);
632 assert_eq!(
633 c.uid_fetch(9, Section::Header).unwrap().as_deref(),
634 Some(&header[..])
635 );
636 assert_eq!(
637 c.uid_fetch(12, Section::Full).unwrap().as_deref(),
638 Some(&body[..])
639 );
640 c.logout().unwrap();
641 assert_eq!(
642 written(&c),
643 "A0001 LOGIN \"aien@aienos.com\" \"pw\"\r\n\
644 A0002 EXAMINE \"INBOX\"\r\n\
645 A0003 UID SEARCH ALL\r\n\
646 A0004 UID FETCH 9 BODY.PEEK[HEADER]\r\n\
647 A0005 UID FETCH 12 BODY.PEEK[]\r\n\
648 A0006 LOGOUT\r\n"
649 );
650 }
651
652 #[test]
653 fn login_quotes_and_escapes_backslash_and_double_quote() {
654 let mut c = client(b"A0001 OK Logged in\r\n");
655 c.login("u", r#"a"b\c"#).unwrap();
656 assert_eq!(written(&c), "A0001 LOGIN \"u\" \"a\\\"b\\\\c\"\r\n");
657 }
658
659 #[test]
660 fn login_sends_eight_bit_password_as_a_literal_after_continuation() {
661 let mut c = client(b"+ OK\r\nA0001 OK Logged in\r\n");
662 c.login("u", "pässword").unwrap();
663 let mut expected = b"A0001 LOGIN \"u\" {9}\r\n".to_vec();
664 expected.extend_from_slice("pässword".as_bytes());
665 expected.extend_from_slice(b"\r\n");
666 assert_eq!(c.stream.written, expected);
667 }
668
669 #[test]
670 fn login_refuses_cr_lf_nul_before_sending_anything() {
671 for bad in ["pw\r\nA0002 DELETE INBOX", "pw\n", "pw\0"] {
672 let mut c = client(b"");
673 assert_eq!(c.login("u", bad), Err(ImapError::UnsafeArgument));
674 assert!(
675 c.stream.written.is_empty(),
676 "nothing may be sent for {bad:?}"
677 );
678 }
679 }
680
681 #[test]
682 fn errors_never_carry_the_password() {
683 let secret = "s3cr3t-Pa55";
684 let mut c = client(b"A0001 NO [AUTHENTICATIONFAILED] Authentication failed.\r\n");
685 let err = c.login("u", secret).unwrap_err();
686 assert!(matches!(err, ImapError::No(_)));
687 assert!(!format!("{err} {err:?}").contains(secret));
688 let mut c = client(b"");
689 let err = c.login("u", &format!("{secret}\r\n")).unwrap_err();
690 assert!(!format!("{err} {err:?}").contains(secret));
691 }
692
693 #[test]
694 fn tagged_no_and_bad_are_typed_refusals() {
695 let mut c = client(b"A0001 NO Authentication failed\r\n");
696 assert_eq!(
697 c.login("u", "p"),
698 Err(ImapError::No("Authentication failed".into()))
699 );
700 let mut c = client(b"A0001 OK\r\nA0002 BAD Unknown mailbox syntax\r\n");
701 c.login("u", "p").unwrap();
702 assert_eq!(
703 c.examine("INBOX"),
704 Err(ImapError::Bad("Unknown mailbox syntax".into()))
705 );
706 }
707
708 #[test]
709 fn server_text_is_reduced_to_printable_ascii() {
710 let mut c = client(b"A0001 NO bad\x1b[31m\x07 news\r\n");
711 assert_eq!(c.login("u", "p"), Err(ImapError::No("bad[31m news".into())));
712 }
713
714 #[test]
715 fn oversized_literal_is_refused_without_reading_it() {
716 let mut c = client(b"A0001 OK\r\n* 1 FETCH (UID 5 BODY[] {99999999999999999999}\r\nxx");
717 c.login("u", "p").unwrap();
718 assert_eq!(
719 c.uid_fetch(5, Section::Full),
720 Err(ImapError::LiteralTooLarge)
721 );
722 let limits = Limits {
723 literal: 8,
724 ..Limits::default()
725 };
726 let mut c = small(
727 b"A0001 OK\r\n* 1 FETCH (UID 5 BODY[] {9}\r\n123456789)\r\nA0002 OK\r\n",
728 limits,
729 )
730 .unwrap();
731 c.login("u", "p").unwrap();
732 assert_eq!(
733 c.uid_fetch(5, Section::Full),
734 Err(ImapError::LiteralTooLarge)
735 );
736 }
737
738 #[test]
739 fn truncated_line_and_truncated_literal_are_refused() {
740 let mut c = client(b"A0001 OK Logged");
741 assert_eq!(c.login("u", "p"), Err(ImapError::Truncated));
742 let mut c = client(b"A0001 OK\r\n* 1 FETCH (UID 5 BODY[] {10}\r\nshort");
743 c.login("u", "p").unwrap();
744 assert_eq!(c.uid_fetch(5, Section::Full), Err(ImapError::Truncated));
745 }
746
747 #[test]
748 fn overlong_line_is_refused() {
749 let limits = Limits {
750 line: 48,
751 ..Limits::default()
752 };
753 let mut replies = b"A0001 OK\r\n* SEARCH ".to_vec();
754 replies.extend(std::iter::repeat_n(b'7', 64));
755 let mut c = small(&replies, limits).unwrap();
756 c.login("u", "p").unwrap();
757 assert_eq!(c.uid_search_all(), Err(ImapError::LineTooLong));
758 }
759
760 #[test]
761 fn response_flood_and_byte_flood_are_refused() {
762 let limits = Limits {
763 responses: 3,
764 ..Limits::default()
765 };
766 let mut c = small(
767 b"A0001 OK\r\n* 1 EXISTS\r\n* 2 EXISTS\r\n* 3 EXISTS\r\n* 4 EXISTS\r\nA0002 OK\r\n",
768 limits,
769 )
770 .unwrap();
771 c.login("u", "p").unwrap();
772 assert_eq!(c.examine("INBOX"), Err(ImapError::TooManyResponses));
773 let limits = Limits {
774 // The FETCH line (94 with its overhead) fits; its 16-byte literal (80) does not.
775 command_bytes: 2 * ENTRY_COST + 40,
776 ..Limits::default()
777 };
778 let mut c = small(
779 b"A0001 OK\r\n* 1 FETCH (UID 5 BODY[] {16}\r\n0123456789abcdef)\r\nA0002 OK\r\n",
780 limits,
781 )
782 .unwrap();
783 c.login("u", "p").unwrap();
784 assert_eq!(
785 c.uid_fetch(5, Section::Full),
786 Err(ImapError::CommandTooLarge)
787 );
788 }
789
790 #[test]
791 fn search_refuses_too_many_or_non_uid_results() {
792 let limits = Limits {
793 uids: 2,
794 ..Limits::default()
795 };
796 let mut c = small(b"A0001 OK\r\n* SEARCH 1 2 3\r\nA0002 OK\r\n", limits).unwrap();
797 c.login("u", "p").unwrap();
798 assert_eq!(c.uid_search_all(), Err(ImapError::TooManyUids));
799 for bad in [
800 &b"* SEARCH 1 x\r\n"[..],
801 b"* SEARCH 0\r\n",
802 b"* SEARCH 4294967296\r\n",
803 ] {
804 let mut replies = b"A0001 OK\r\n".to_vec();
805 replies.extend_from_slice(bad);
806 replies.extend_from_slice(b"A0002 OK\r\n");
807 let mut c = client(&replies);
808 c.login("u", "p").unwrap();
809 assert!(
810 matches!(c.uid_search_all(), Err(ImapError::Malformed(_))),
811 "{bad:?}"
812 );
813 }
814 let mut c = client(b"A0001 OK\r\n* SEARCH\r\nA0002 OK\r\n");
815 c.login("u", "p").unwrap();
816 assert_eq!(c.uid_search_all().unwrap(), Vec::<u32>::new());
817 }
818
819 #[test]
820 fn fetch_ignores_other_messages_and_unrequested_sections() {
821 let mut c = client(
822 b"A0001 OK\r\n\
823 * 1 FETCH (FLAGS (\\Seen))\r\n\
824 * 2 FETCH (UID 6 BODY[] {3}\r\nnot)\r\n\
825 * 3 FETCH (UID 7 BODY[HEADER] {3}\r\nhdr)\r\n\
826 * 3 FETCH (UID 7 BODY[] {4}\r\nmine)\r\n\
827 A0002 OK\r\n",
828 );
829 c.login("u", "p").unwrap();
830 assert_eq!(
831 c.uid_fetch(7, Section::Full).unwrap().as_deref(),
832 Some(&b"mine"[..])
833 );
834 }
835
836 #[test]
837 fn fetch_of_a_missing_uid_is_none() {
838 let mut c = client(b"A0001 OK\r\nA0002 OK Fetch completed\r\n");
839 c.login("u", "p").unwrap();
840 assert_eq!(c.uid_fetch(41, Section::Header).unwrap(), None);
841 }
842
843 #[test]
844 fn unexpected_bye_foreign_tag_and_stray_continuation_are_refused() {
845 let mut c = client(b"A0001 OK\r\n* BYE Server shutting down\r\n");
846 c.login("u", "p").unwrap();
847 assert_eq!(
848 c.examine("INBOX"),
849 Err(ImapError::Bye("Server shutting down".into()))
850 );
851 let mut c = client(b"A0001 OK\r\nB0002 OK\r\n");
852 c.login("u", "p").unwrap();
853 assert!(matches!(c.examine("INBOX"), Err(ImapError::Malformed(_))));
854 let mut c = client(b"A0001 OK\r\n+ go ahead\r\n");
855 c.login("u", "p").unwrap();
856 assert!(matches!(c.examine("INBOX"), Err(ImapError::Malformed(_))));
857 }
858
859 #[test]
860 fn literal_login_refused_by_server_does_not_send_the_password() {
861 let mut c = client(b"A0001 NO Literal refused\r\n");
862 assert_eq!(
863 c.login("u", "pässword"),
864 Err(ImapError::No("Literal refused".into()))
865 );
866 assert_eq!(written(&c), "A0001 LOGIN \"u\" {9}\r\n");
867 }
868
869 #[test]
870 fn greeting_must_be_ok() {
871 let bye = Client::connect(Script::new(b"* BYE Too many connections\r\n"));
872 assert_eq!(
873 bye.err(),
874 Some(ImapError::Bye("Too many connections".into()))
875 );
876 let preauth = Client::connect(Script::new(b"* PREAUTH ready\r\n"));
877 assert!(matches!(preauth.err(), Some(ImapError::Malformed(_))));
878 let junk = Client::connect(Script::new(b"HTTP/1.1 400 Bad Request\r\n"));
879 assert!(matches!(junk.err(), Some(ImapError::Malformed(_))));
880 let empty = Client::connect(Script::new(b""));
881 assert_eq!(empty.err(), Some(ImapError::Truncated));
882 }
883
884 #[test]
885 fn one_byte_per_read_gives_the_same_transcript() {
886 // A 20 KiB literal crosses many fills; CRLFs split across reads resume the scan.
887 let body: Vec<u8> = (0..20 * 1024).map(|i| b'a' + (i % 26) as u8).collect();
888 let mut replies = GREETING.to_vec();
889 replies.extend_from_slice(b"A0001 OK Logged in\r\n");
890 replies.extend_from_slice(b"* 1 EXISTS\r\nA0002 OK [READ-ONLY] Examine completed\r\n");
891 replies.extend_from_slice(b"* SEARCH 12\r\nA0003 OK Search completed\r\n");
892 // The UID item may follow the literal.
893 replies.extend_from_slice(format!("* 1 FETCH (BODY[] {{{}}}\r\n", body.len()).as_bytes());
894 replies.extend_from_slice(&body);
895 replies.extend_from_slice(b" UID 12)\r\nA0004 OK Fetch completed\r\n");
896 replies.extend_from_slice(b"* BYE Logging out\r\nA0005 OK Logout completed\r\n");
897 let mut c = Client::connect(Script::trickle(&replies)).unwrap();
898 c.login("u", "p").unwrap();
899 c.examine("INBOX").unwrap();
900 assert_eq!(c.uid_search_all().unwrap(), vec![12]);
901 assert_eq!(c.uid_fetch(12, Section::Full).unwrap(), Some(body));
902 c.logout().unwrap();
903 }
904
905 #[test]
906 fn line_exactly_at_the_limit_is_accepted_one_byte_per_read() {
907 let limits = Limits {
908 line: 48,
909 ..Limits::default()
910 };
911 let mut at = b"* SEARCH ".to_vec();
912 at.extend(std::iter::repeat_n(b'7', 48 - at.len()));
913 let mut replies = GREETING.to_vec();
914 replies.extend_from_slice(b"A0001 OK\r\n");
915 replies.extend_from_slice(&at);
916 replies.extend_from_slice(b"\r\nA0002 OK\r\n");
917 let mut c = Client::with_limits(Script::trickle(&replies), limits).unwrap();
918 c.login("u", "p").unwrap();
919 assert_eq!(
920 c.uid_search_all(),
921 Err(ImapError::Malformed("search result is not a UID"))
922 );
923 // One byte more is refused.
924 let mut over = GREETING.to_vec();
925 over.extend_from_slice(b"A0001 OK\r\n");
926 over.extend_from_slice(&at);
927 over.extend_from_slice(b"7\r\nA0002 OK\r\n");
928 let mut c = Client::with_limits(Script::trickle(&over), limits).unwrap();
929 c.login("u", "p").unwrap();
930 assert_eq!(c.uid_search_all(), Err(ImapError::LineTooLong));
931 }
932
933 #[test]
934 fn empty_literal_flood_is_charged_against_the_command_budget() {
935 // 2,000 `{0}` literals are 10 kB on the wire but 4,000 allocations; each line and
936 // literal is charged a fixed overhead, so the flood hits the command budget.
937 let limits = Limits {
938 command_bytes: 64 * 1024,
939 ..Limits::default()
940 };
941 let mut replies = b"A0001 OK\r\n* 1 FETCH (UID 5 X {0}\r\n".to_vec();
942 for _ in 0..2_000 {
943 replies.extend_from_slice(b"{0}\r\n");
944 }
945 replies.extend_from_slice(b")\r\nA0002 OK\r\n");
946 let mut c = small(&replies, limits).unwrap();
947 c.login("u", "p").unwrap();
948 assert_eq!(
949 c.uid_fetch(5, Section::Full),
950 Err(ImapError::CommandTooLarge)
951 );
952 }
953
954 #[test]
955 fn tagged_and_continuation_lines_never_announce_literals() {
956 // A tagged status or `+` line ending in `{n}` is not followed by n bytes.
957 let mut c = client(b"A0001 OK done {5}\r\nA0002 OK {9}\r\n");
958 c.login("u", "p").unwrap();
959 c.examine("INBOX").unwrap();
960 let mut c = client(b"+ ready {4}\r\nA0001 OK\r\n");
961 c.login("u", "pässword").unwrap();
962 }
963
964 #[test]
965 fn tagged_no_after_a_fetch_literal_and_bye_before_continuation_are_refused() {
966 let mut c =
967 client(b"A0001 OK\r\n* 1 FETCH (UID 5 BODY[] {3}\r\nabc)\r\nA0002 NO denied\r\n");
968 c.login("u", "p").unwrap();
969 assert_eq!(
970 c.uid_fetch(5, Section::Full),
971 Err(ImapError::No("denied".into()))
972 );
973 let mut c = client(b"* BYE going away\r\n");
974 assert_eq!(
975 c.login("u", "pässword"),
976 Err(ImapError::Bye("going away".into()))
977 );
978 }
979
980 #[test]
981 fn section_sent_as_a_quoted_string_is_malformed_and_nil_is_none() {
982 let mut c = client(b"A0001 OK\r\n* 1 FETCH (UID 5 BODY[] \"hello\")\r\nA0002 OK\r\n");
983 c.login("u", "p").unwrap();
984 assert!(matches!(
985 c.uid_fetch(5, Section::Full),
986 Err(ImapError::Malformed(_))
987 ));
988 let mut c = client(b"A0001 OK\r\n* 1 FETCH (UID 5 BODY[HEADER] NIL)\r\nA0002 OK\r\n");
989 c.login("u", "p").unwrap();
990 assert_eq!(c.uid_fetch(5, Section::Header).unwrap(), None);
991 }
992}