oxedyne/fe2o3/fe2o3_net/src/imap/search.rs
25.0 KiB, 45 runs
created by r1870400018:74760, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! IMAP SEARCH criteria (RFC 3501 §6.4.4): parsing and matching. |
| 2 | //! |
| 3 | //! Every search key of RFC 3501 is read, with `CHARSET UTF-8` or `US-ASCII`, sequence sets and |
| 4 | //! parenthesised lists, and string keys match as case-insensitive substrings. A key outside the |
| 5 | //! standard is refused, never read as `ALL`: a client acts on what SEARCH names, so an answer |
| 6 | //! wider than the question turns a narrow move or delete into one on every message. |
| 7 | //! |
| 8 | //! 2026-10-26 (F2a, D-20261026-01): before this module the server knew ALL, the flags and |
| 9 | //! `UID <set>`, and answered anything else with the whole mailbox. |
| 10 | //! |
| 11 | //! Header keys (HEADER, FROM, TO, CC, BCC, SUBJECT and TEXT's header part) match the value with |
| 12 | //! its RFC 2047 encoded-words decoded, so `SUBJECT Grüße` finds `=?UTF-8?B?R3LDvMOfZQ==?=` |
| 13 | //! (F2a part 2, 2026-10-26). BODY and TEXT's body part match the decoded text of the message's |
| 14 | //! text parts, walked by boundary, out of base64 or quoted-printable and their charset, so |
| 15 | //! neither the encoding, a multipart's preamble nor an attachment is searched (F2b, 2026-10-26). |
| 16 | //! |
| 17 | //! A client writes a key with `SearchKey::wire`, which `parse` reads back as the same key. |
| 18 | |
| 19 | use crate::mail::store::MessageMeta; |
| 20 | |
| 21 | use oxedyne_fe2o3_core::prelude::*; |
| 22 | use oxedyne_fe2o3_text::mime::{ |
| 23 | decode_words, |
| 24 | headers, |
| 25 | leaf_parts, |
| 26 | }; |
| 27 | |
| 28 | use std::time::UNIX_EPOCH; |
| 29 | |
| 30 | |
| 31 | /// One piece of a SEARCH command as it came off the wire: command text, or the contents of a |
| 32 | /// literal, which is a string whatever it holds. |
| 33 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 34 | pub enum Segment { |
| 35 | Text(String), |
| 36 | Literal(String), |
| 37 | } |
| 38 | |
| 39 | /// Why a SEARCH was refused. |
| 40 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 41 | pub enum SearchError { |
| 42 | Bad(String), // tagged BAD with this text |
| 43 | BadCharset, // tagged NO [BADCHARSET (UTF-8 US-ASCII)] |
| 44 | } |
| 45 | |
| 46 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 47 | pub enum Flag { |
| 48 | Answered, |
| 49 | Deleted, |
| 50 | Draft, |
| 51 | Flagged, |
| 52 | Recent, |
| 53 | Seen, |
| 54 | } |
| 55 | |
| 56 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 57 | pub enum SearchKey { |
| 58 | All, |
| 59 | Flag(Flag, bool), // the flag, and whether it must be set |
| 60 | New, // RECENT UNSEEN |
| 61 | Old, // NOT RECENT |
| 62 | Keyword(bool), // KEYWORD (true) or UNKEYWORD: this server keeps no keywords |
| 63 | Header(String, String), // field name and needle, both lower case |
| 64 | Body(String), |
| 65 | Text(String), |
| 66 | Before(i64), // days since the epoch, against INTERNALDATE |
| 67 | On(i64), |
| 68 | Since(i64), |
| 69 | SentBefore(i64), // days since the epoch, against the Date: field |
| 70 | SentOn(i64), |
| 71 | SentSince(i64), |
| 72 | Larger(u64), |
| 73 | Smaller(u64), |
| 74 | Seq(String), // a validated sequence set |
| 75 | Uid(String), // a validated UID set |
| 76 | Not(Box<SearchKey>), |
| 77 | Or(Box<SearchKey>, Box<SearchKey>), |
| 78 | And(Vec<SearchKey>), |
| 79 | GmRaw(String), // Gmail's `X-GM-RAW`, sent to a server with `X-GM-EXT-1`, never parsed |
| 80 | } |
| 81 | |
| 82 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 83 | enum Token { |
| 84 | Atom(String), |
| 85 | Str(String), // quoted or literal |
| 86 | Open, |
| 87 | Close, |
| 88 | } |
| 89 | |
| 90 | /// Reads the arguments of SEARCH or UID SEARCH into one key, the AND of all given. |
| 91 | pub fn parse(segments: &[Segment]) -> Result<SearchKey, SearchError> { |
| 92 | let mut toks: Vec<Token> = Vec::new(); |
| 93 | for seg in segments { |
| 94 | match seg { |
| 95 | Segment::Text(t) => ok!(tokenise(t, &mut toks)), |
| 96 | Segment::Literal(s) => toks.push(Token::Str(s.clone())), |
| 97 | } |
| 98 | } |
| 99 | let mut pos = 0usize; |
| 100 | if let Some(Token::Atom(a)) = toks.first() { |
| 101 | if a.eq_ignore_ascii_case("CHARSET") { |
| 102 | match toks.get(1) { |
| 103 | Some(Token::Atom(cs)) | Some(Token::Str(cs)) => { |
| 104 | if !cs.eq_ignore_ascii_case("UTF-8") && !cs.eq_ignore_ascii_case("US-ASCII") { |
| 105 | return Err(SearchError::BadCharset); |
| 106 | } |
| 107 | }, |
| 108 | _ => return Err(bad("CHARSET needs a charset name")), |
| 109 | } |
| 110 | pos = 2; |
| 111 | } |
| 112 | } |
| 113 | let mut keys = Vec::new(); |
| 114 | while pos < toks.len() { |
| 115 | keys.push(ok!(parse_key(&toks, &mut pos))); |
| 116 | } |
| 117 | match keys.len() { |
| 118 | 0 => Err(bad("SEARCH needs at least one search key")), |
| 119 | 1 => Ok(keys.remove(0)), |
| 120 | _ => Ok(SearchKey::And(keys)), |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | fn bad(text: &str) -> SearchError { |
| 125 | SearchError::Bad(text.to_string()) |
| 126 | } |
| 127 | |
| 128 | fn tokenise(text: &str, out: &mut Vec<Token>) -> Result<(), SearchError> { |
| 129 | let mut chars = text.chars().peekable(); |
| 130 | while let Some(&c) = chars.peek() { |
| 131 | match c { |
| 132 | ' ' | '\t' => { chars.next(); }, |
| 133 | '(' => { chars.next(); out.push(Token::Open); }, |
| 134 | ')' => { chars.next(); out.push(Token::Close); }, |
| 135 | '"' => { |
| 136 | chars.next(); |
| 137 | let mut s = String::new(); |
| 138 | loop { |
| 139 | match chars.next() { |
| 140 | Some('"') => break, |
| 141 | Some('\\') => match chars.next() { |
| 142 | Some(e) => s.push(e), |
| 143 | None => return Err(bad("Unterminated quoted string")), |
| 144 | }, |
| 145 | Some(x) => s.push(x), |
| 146 | None => return Err(bad("Unterminated quoted string")), |
| 147 | } |
| 148 | } |
| 149 | out.push(Token::Str(s)); |
| 150 | }, |
| 151 | _ => { |
| 152 | let mut a = String::new(); |
| 153 | while let Some(&x) = chars.peek() { |
| 154 | if x == ' ' || x == '\t' || x == '(' || x == ')' || x == '"' { break; } |
| 155 | a.push(x); |
| 156 | chars.next(); |
| 157 | } |
| 158 | out.push(Token::Atom(a)); |
| 159 | }, |
| 160 | } |
| 161 | } |
| 162 | Ok(()) |
| 163 | } |
| 164 | |
| 165 | fn parse_key(toks: &[Token], pos: &mut usize) -> Result<SearchKey, SearchError> { |
| 166 | let tok = match toks.get(*pos) { |
| 167 | Some(t) => t.clone(), |
| 168 | None => return Err(bad("A search key is missing")), |
| 169 | }; |
| 170 | *pos += 1; |
| 171 | let name = match tok { |
| 172 | Token::Open => { |
| 173 | let mut keys = Vec::new(); |
| 174 | loop { |
| 175 | match toks.get(*pos) { |
| 176 | Some(Token::Close) => { *pos += 1; break; }, |
| 177 | Some(_) => keys.push(ok!(parse_key(toks, pos))), |
| 178 | None => return Err(bad("Unclosed parenthesis")), |
| 179 | } |
| 180 | } |
| 181 | if keys.is_empty() { return Err(bad("Empty parenthesised list")); } |
| 182 | return Ok(SearchKey::And(keys)); |
| 183 | }, |
| 184 | Token::Close => return Err(bad("Unexpected ')'")), |
| 185 | Token::Str(s) => return Err(SearchError::Bad(fmt!("{:?} is not a search key", s))), |
| 186 | Token::Atom(a) => a, |
| 187 | }; |
| 188 | let upper = name.to_ascii_uppercase(); |
| 189 | if let Some(k) = flag_key(&upper) { return Ok(k); } |
| 190 | let key = match upper.as_str() { |
| 191 | "ALL" => SearchKey::All, |
| 192 | "NEW" => SearchKey::New, |
| 193 | "OLD" => SearchKey::Old, |
| 194 | "KEYWORD" => { ok!(take_atom(toks, pos, "KEYWORD")); SearchKey::Keyword(true) }, |
| 195 | "UNKEYWORD" => { ok!(take_atom(toks, pos, "UNKEYWORD")); SearchKey::Keyword(false) }, |
| 196 | "BCC" | "CC" | "FROM" | "SUBJECT" | "TO" => { |
| 197 | let needle = ok!(take_string(toks, pos, &upper)); |
| 198 | SearchKey::Header(name.to_ascii_lowercase(), needle.to_lowercase()) |
| 199 | }, |
| 200 | "HEADER" => { |
| 201 | let field = ok!(take_string(toks, pos, "HEADER")); |
| 202 | let needle = ok!(take_string(toks, pos, "HEADER")); |
| 203 | SearchKey::Header(field.to_ascii_lowercase(), needle.to_lowercase()) |
| 204 | }, |
| 205 | "BODY" => SearchKey::Body(ok!(take_string(toks, pos, "BODY")).to_lowercase()), |
| 206 | "TEXT" => SearchKey::Text(ok!(take_string(toks, pos, "TEXT")).to_lowercase()), |
| 207 | "BEFORE" => SearchKey::Before(ok!(take_date(toks, pos, "BEFORE"))), |
| 208 | "ON" => SearchKey::On(ok!(take_date(toks, pos, "ON"))), |
| 209 | "SINCE" => SearchKey::Since(ok!(take_date(toks, pos, "SINCE"))), |
| 210 | "SENTBEFORE" => SearchKey::SentBefore(ok!(take_date(toks, pos, "SENTBEFORE"))), |
| 211 | "SENTON" => SearchKey::SentOn(ok!(take_date(toks, pos, "SENTON"))), |
| 212 | "SENTSINCE" => SearchKey::SentSince(ok!(take_date(toks, pos, "SENTSINCE"))), |
| 213 | "LARGER" => SearchKey::Larger(ok!(take_number(toks, pos, "LARGER"))), |
| 214 | "SMALLER" => SearchKey::Smaller(ok!(take_number(toks, pos, "SMALLER"))), |
| 215 | "UID" => { |
| 216 | let set = ok!(take_atom(toks, pos, "UID")); |
| 217 | if !valid_set(&set) { |
| 218 | return Err(SearchError::Bad(fmt!("UID {:?} is not a sequence set", set))); |
| 219 | } |
| 220 | SearchKey::Uid(set) |
| 221 | }, |
| 222 | "NOT" => SearchKey::Not(Box::new(ok!(parse_key(toks, pos)))), |
| 223 | "OR" => { |
| 224 | let a = ok!(parse_key(toks, pos)); |
| 225 | let b = ok!(parse_key(toks, pos)); |
| 226 | SearchKey::Or(Box::new(a), Box::new(b)) |
| 227 | }, |
| 228 | _ if valid_set(&name) => SearchKey::Seq(name), |
| 229 | _ => return Err(SearchError::Bad(fmt!("Unknown search key {}", name))), |
| 230 | }; |
| 231 | Ok(key) |
| 232 | } |
| 233 | |
| 234 | // fixed: RFC 3501's flag keys, each set or, after `UN`, clear; RECENT is cleared only as OLD. |
| 235 | const FLAGS: [(&str, Flag); 6] = [("ANSWERED", Flag::Answered), ("DELETED", Flag::Deleted), ("DRAFT", Flag::Draft), |
| 236 | ("FLAGGED", Flag::Flagged), ("RECENT", Flag::Recent), ("SEEN", Flag::Seen)]; |
| 237 | |
| 238 | fn flag_key(name: &str) -> Option<SearchKey> { |
| 239 | let (n, set) = name.strip_prefix("UN").map_or((name, true), |n| (n, false)); |
| 240 | FLAGS.iter().find(|(w, f)| *w == n && (set || *f != Flag::Recent)).map(|(_, f)| SearchKey::Flag(*f, set)) |
| 241 | } |
| 242 | |
| 243 | fn take_atom(toks: &[Token], pos: &mut usize, key: &str) -> Result<String, SearchError> { |
| 244 | match toks.get(*pos) { |
| 245 | Some(Token::Atom(a)) => { *pos += 1; Ok(a.clone()) }, |
| 246 | _ => Err(SearchError::Bad(fmt!("{} needs an argument", key))), |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | fn take_string(toks: &[Token], pos: &mut usize, key: &str) -> Result<String, SearchError> { |
| 251 | match toks.get(*pos) { |
| 252 | Some(Token::Atom(s)) | Some(Token::Str(s)) => { *pos += 1; Ok(s.clone()) }, |
| 253 | _ => Err(SearchError::Bad(fmt!("{} needs a string", key))), |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | fn take_number(toks: &[Token], pos: &mut usize, key: &str) -> Result<u64, SearchError> { |
| 258 | let a = ok!(take_atom(toks, pos, key)); |
| 259 | match a.parse::<u64>() { |
| 260 | Ok(n) => Ok(n), |
| 261 | Err(_) => Err(SearchError::Bad(fmt!("{} needs a number, not {:?}", key, a))), |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | fn take_date(toks: &[Token], pos: &mut usize, key: &str) -> Result<i64, SearchError> { |
| 266 | let s = ok!(take_string(toks, pos, key)); |
| 267 | match parse_search_date(&s) { |
| 268 | Some(d) => Ok(d), |
| 269 | None => Err(SearchError::Bad(fmt!("{} needs a date such as 1-Feb-1994, not {:?}", key, s))), |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | /// Is `s` a sequence set: `n`, `*`, `n:m`, joined by commas, with no zero? |
| 274 | fn valid_set(s: &str) -> bool { |
| 275 | !s.is_empty() && s.split(',').all(|piece| { |
| 276 | let mut ends = piece.splitn(2, ':'); |
| 277 | ends.all(|e| e == "*" || matches!(e.parse::<u32>(), Ok(n) if n > 0)) |
| 278 | && !piece.is_empty() |
| 279 | }) |
| 280 | } |
| 281 | |
| 282 | /// Does the set, with `*` read as `max`, hold `n`? |
| 283 | fn set_contains(set: &str, n: u32, max: u32) -> bool { |
| 284 | let num = |e: &str| if e == "*" { max } else { e.parse::<u32>().unwrap_or(0) }; |
| 285 | set.split(',').any(|piece| { |
| 286 | let (lo, hi) = match piece.split_once(':') { |
| 287 | Some((a, b)) => (num(a), num(b)), |
| 288 | None => (num(piece), num(piece)), |
| 289 | }; |
| 290 | let (lo, hi) = if lo > hi { (hi, lo) } else { (lo, hi) }; |
| 291 | n >= lo && n <= hi |
| 292 | }) |
| 293 | } |
| 294 | |
| 295 | // fixed: RFC 3501's date-month. |
| 296 | const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; |
| 297 | |
| 298 | fn month_number(m: &str) -> Option<u32> { |
| 299 | MONTHS.iter().position(|x| x.eq_ignore_ascii_case(m)).map(|i| i as u32 + 1) |
| 300 | } |
| 301 | |
| 302 | /// `d-Mon-yyyy`, the RFC 3501 `date`, as days since the epoch. |
| 303 | pub fn parse_search_date(s: &str) -> Option<i64> { |
| 304 | let mut it = s.split('-'); |
| 305 | let d: u32 = ok!(ok!(it.next()).parse().ok()); |
| 306 | let m = ok!(month_number(ok!(it.next()))); |
| 307 | let y: i32 = ok!(ok!(it.next()).parse().ok()); |
| 308 | if it.next().is_some() || d == 0 || d > 31 { return None; } |
| 309 | Some(days_from_civil(y, m, d)) |
| 310 | } |
| 311 | |
| 312 | /// The date of an RFC 5322 `Date:` field, `[Day,] d Mon yyyy hh:mm[:ss] zone`, as days since the |
| 313 | /// epoch. Time and zone are disregarded, as RFC 3501 asks of the SENT keys. |
| 314 | fn parse_header_date(s: &str) -> Option<i64> { |
| 315 | // The weekday is optional, and some clients omit its comma (`Tue 27 Oct 2026`). |
| 316 | let mut it = s.split(|c: char| c.is_whitespace() || c == ',').filter(|t| !t.is_empty()).peekable(); |
| 317 | if it.peek().map_or(false, |t| t.chars().all(|c| c.is_ascii_alphabetic())) { it.next(); } |
| 318 | let d: u32 = ok!(ok!(it.next()).parse().ok()); |
| 319 | let m = ok!(month_number(ok!(it.next()))); |
| 320 | let y_str = ok!(it.next()); |
| 321 | let mut y: i32 = ok!(y_str.parse().ok()); |
| 322 | // RFC 5322 §4.3: a two-digit year is 19xx from 50, 20xx below; three digits add 1900. |
| 323 | if y_str.len() == 2 { y += if y < 50 { 2000 } else { 1900 }; } |
| 324 | else if y_str.len() == 3 { y += 1900; } |
| 325 | if d == 0 || d > 31 { return None; } |
| 326 | Some(days_from_civil(y, m, d)) |
| 327 | } |
| 328 | |
| 329 | /// Howard Hinnant's algorithm, proleptic Gregorian. |
| 330 | pub fn days_from_civil(y: i32, m: u32, d: u32) -> i64 { |
| 331 | let y = if m <= 2 { y as i64 - 1 } else { y as i64 }; |
| 332 | let era = if y >= 0 { y } else { y - 399 } / 400; |
| 333 | let yoe = y - era * 400; |
| 334 | let mp = if m > 2 { m - 3 } else { m + 9 } as i64; |
| 335 | let doy = (153 * mp + 2) / 5 + d as i64 - 1; |
| 336 | let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; |
| 337 | era * 146_097 + doe - 719_468 |
| 338 | } |
| 339 | |
| 340 | /// The year, month and day of a count of days since the epoch, the inverse of `days_from_civil`. |
| 341 | pub fn civil_from_days(n: i64) -> (i32, u32, u32) { |
| 342 | let z = n.saturating_add(719_468); |
| 343 | let era = if z >= 0 { z } else { z - 146_096 } / 146_097; |
| 344 | let doe = z - era * 146_097; |
| 345 | let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; |
| 346 | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| 347 | let mp = (5 * doy + 2) / 153; |
| 348 | let m = if mp < 10 { mp + 3 } else { mp - 9 }; |
| 349 | ((yoe + era * 400 + (m <= 2) as i64) as i32, m as u32, (doy - (153 * mp + 2) / 5 + 1) as u32) |
| 350 | } |
| 351 | |
| 352 | /// What the content keys look at in one message, decoded and lower-cased once. |
| 353 | #[derive(Debug)] |
| 354 | pub struct Content { |
| 355 | fields: Vec<(String, String)>, // lower-case name, unfolded, decoded, lower-case value |
| 356 | head: String, // the decoded fields as `name: value` lines, for TEXT |
| 357 | body: String, // the decoded text parts, lower case |
| 358 | sent: Option<i64>, // the Date: field, days since the epoch |
| 359 | } |
| 360 | |
| 361 | impl Content { |
| 362 | pub fn new(bytes: &[u8]) -> Self { |
| 363 | // Decode before lower-casing: case is meaningful inside a base64 word. |
| 364 | let fields: Vec<(String, String)> = headers(bytes).into_iter() |
| 365 | .map(|(n, v)| (n, decode_words(&v).to_lowercase())) |
| 366 | .collect(); |
| 367 | let mut head = String::new(); |
| 368 | for (n, v) in &fields { |
| 369 | head.push_str(n); |
| 370 | head.push_str(": "); |
| 371 | head.push_str(v); |
| 372 | head.push('\n'); |
| 373 | } |
| 374 | let sent = fields.iter() |
| 375 | .find(|(n, _)| n == "date") |
| 376 | .and_then(|(_, v)| parse_header_date(v)); |
| 377 | let mut body = String::new(); |
| 378 | // A multipart left a leaf (no boundary) is text, as the mail matcher reads it. |
| 379 | for p in leaf_parts(bytes).iter().filter(|p| p.is_text() || p.media_type().starts_with("multipart/")) { |
| 380 | body.push_str(&p.text().to_lowercase()); |
| 381 | body.push('\n'); |
| 382 | } |
| 383 | Self { |
| 384 | fields, |
| 385 | head, |
| 386 | body, |
| 387 | sent, |
| 388 | } |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | impl SearchKey { |
| 393 | /// Does any part of the key read the message itself rather than its flags, size or date? |
| 394 | pub fn needs_content(&self) -> bool { |
| 395 | match self { |
| 396 | Self::Header(..) | Self::Body(_) | Self::Text(_) |
| 397 | | Self::SentBefore(_) | Self::SentOn(_) | Self::SentSince(_) => true, |
| 398 | Self::Not(k) => k.needs_content(), |
| 399 | Self::Or(a, b) => a.needs_content() || b.needs_content(), |
| 400 | Self::And(ks) => ks.iter().any(|k| k.needs_content()), |
| 401 | _ => false, |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | /// Does message `msgs[idx]` match? `content` is `None` only where `needs_content` is false. |
| 406 | pub fn matches(&self, idx: usize, msgs: &[MessageMeta], content: Option<&Content>) -> bool { |
| 407 | let m = match msgs.get(idx) { |
| 408 | Some(m) => m, |
| 409 | None => return false, |
| 410 | }; |
| 411 | let day = || match m.internal.duration_since(UNIX_EPOCH) { |
| 412 | Ok(d) => (d.as_secs() / 86_400) as i64, |
| 413 | Err(e) => -((e.duration().as_secs() / 86_400) as i64) - 1, |
| 414 | }; |
| 415 | let sent = || content.and_then(|c| c.sent); |
| 416 | match self { |
| 417 | Self::All => true, |
| 418 | Self::Flag(f, want) => { |
| 419 | let set = match f { |
| 420 | Flag::Answered => m.flags.answered, |
| 421 | Flag::Deleted => m.flags.deleted, |
| 422 | Flag::Draft => m.flags.draft, |
| 423 | Flag::Flagged => m.flags.flagged, |
| 424 | Flag::Recent => m.flags.recent, |
| 425 | Flag::Seen => m.flags.seen, |
| 426 | }; |
| 427 | set == *want |
| 428 | }, |
| 429 | Self::New => m.flags.recent && !m.flags.seen, |
| 430 | Self::Old => !m.flags.recent, |
| 431 | Self::Keyword(want) => !*want, |
| 432 | Self::Header(name, needle) => match content { |
| 433 | Some(c) => c.fields.iter().any(|(n, v)| n == name && v.contains(needle.as_str())), |
| 434 | None => false, |
| 435 | }, |
| 436 | Self::Body(needle) => content.is_some_and(|c| c.body.contains(needle.as_str())), |
| 437 | Self::Text(needle) => content.is_some_and(|c| { |
| 438 | c.head.contains(needle.as_str()) || c.body.contains(needle.as_str()) |
| 439 | }), |
| 440 | Self::Before(d) => day() < *d, |
| 441 | Self::On(d) => day() == *d, |
| 442 | Self::Since(d) => day() >= *d, |
| 443 | Self::SentBefore(d) => sent().is_some_and(|s| s < *d), |
| 444 | Self::SentOn(d) => sent().is_some_and(|s| s == *d), |
| 445 | Self::SentSince(d) => sent().is_some_and(|s| s >= *d), |
| 446 | Self::Larger(n) => m.size > *n, |
| 447 | Self::Smaller(n) => m.size < *n, |
| 448 | Self::Seq(set) => set_contains(set, idx as u32 + 1, msgs.len() as u32), |
| 449 | Self::Uid(set) => { |
| 450 | let max = msgs.last().map(|x| x.uid.0).unwrap_or(0); |
| 451 | set_contains(set, m.uid.0, max) |
| 452 | }, |
| 453 | Self::Not(k) => !k.matches(idx, msgs, content), |
| 454 | Self::Or(a, b) => a.matches(idx, msgs, content) || b.matches(idx, msgs, content), |
| 455 | Self::And(ks) => ks.iter().all(|k| k.matches(idx, msgs, content)), |
| 456 | Self::GmRaw(_) => false, // fixed: never parsed by this server |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | /// The arguments of `UID SEARCH` that `parse` reads back as this key, its strings in lower |
| 461 | /// case: a string quoted where it is 7-bit without CR, LF or NUL, else a literal, and |
| 462 | /// `CHARSET UTF-8` first where one is not ASCII. Written from a stack of its own. |
| 463 | pub fn wire(&self) -> Outcome<Vec<Segment>> { |
| 464 | enum W<'a> { K(&'a SearchKey, bool), S(&'static str) } // a key, and whether it is the whole |
| 465 | let (mut out, mut utf8, mut st) = (vec![Segment::Text(String::new())], false, vec![W::K(self, true)]); |
| 466 | while let Some(w) = st.pop() { |
| 467 | let (k, top) = match w { |
| 468 | W::S(s) => { text(&mut out, s); continue; } |
| 469 | W::K(k, t) => (k, t), |
| 470 | }; |
| 471 | let flag = |f: &Flag| FLAGS.iter().find(|(_, x)| x == f).map_or("", |(w, _)| *w); |
| 472 | let (name, strs): (String, Vec<&String>) = match k { |
| 473 | Self::All => ("ALL".into(), vec![]), |
| 474 | Self::Flag(Flag::Recent, false) => ("NOT RECENT".into(), vec![]), |
| 475 | Self::Flag(f, true) => (flag(f).into(), vec![]), |
| 476 | Self::Flag(f, false) => (fmt!("UN{}", flag(f)), vec![]), |
| 477 | Self::New => ("NEW".into(), vec![]), |
| 478 | Self::Old => ("OLD".into(), vec![]), |
| 479 | Self::Keyword(_) => return Err(err!("A KEYWORD key holds no keyword to send."; Invalid, Input)), |
| 480 | Self::Header(h, s) => match h.as_str() { |
| 481 | "from" | "to" | "cc" | "bcc" | "subject" => (h.to_ascii_uppercase(), vec![s]), |
| 482 | _ => ("HEADER".into(), vec![h, s]), |
| 483 | }, |
| 484 | Self::Body(s) => ("BODY".into(), vec![s]), |
| 485 | Self::Text(s) => ("TEXT".into(), vec![s]), |
| 486 | Self::GmRaw(s) => ("X-GM-RAW".into(), vec![s]), |
| 487 | Self::Before(d) => (fmt!("BEFORE {}", res!(date(*d))), vec![]), |
| 488 | Self::On(d) => (fmt!("ON {}", res!(date(*d))), vec![]), |
| 489 | Self::Since(d) => (fmt!("SINCE {}", res!(date(*d))), vec![]), |
| 490 | Self::SentBefore(d) => (fmt!("SENTBEFORE {}", res!(date(*d))), vec![]), |
| 491 | Self::SentOn(d) => (fmt!("SENTON {}", res!(date(*d))), vec![]), |
| 492 | Self::SentSince(d) => (fmt!("SENTSINCE {}", res!(date(*d))), vec![]), |
| 493 | Self::Larger(n) => (fmt!("LARGER {}", n), vec![]), |
| 494 | Self::Smaller(n) => (fmt!("SMALLER {}", n), vec![]), |
| 495 | Self::Seq(set) | Self::Uid(set) if !valid_set(set) => return Err(err!( |
| 496 | "{:?} is not a sequence set.", set; Invalid, Input)), |
| 497 | Self::Seq(set) => (set.clone(), vec![]), |
| 498 | Self::Uid(set) => (fmt!("UID {}", set), vec![]), |
| 499 | Self::Not(x) => { text(&mut out, "NOT "); st.push(W::K(x, false)); continue; } |
| 500 | Self::Or(a, b) => { |
| 501 | text(&mut out, "OR "); |
| 502 | st.extend([W::K(b, false), W::S(" "), W::K(a, false)]); |
| 503 | continue; |
| 504 | } |
| 505 | Self::And(v) if v.is_empty() => return Err(err!("An empty AND has no wire form; send ALL."; Invalid, Input)), |
| 506 | // Bare only as the whole of several keys, which `parse` reads as their AND. |
| 507 | Self::And(v) => { |
| 508 | let bare = top && v.len() > 1; |
| 509 | if !bare { text(&mut out, "("); st.push(W::S(")")); } |
| 510 | for (i, x) in v.iter().enumerate().rev() { |
| 511 | st.push(W::K(x, false)); |
| 512 | if i > 0 { st.push(W::S(" ")); } |
| 513 | } |
| 514 | continue; |
| 515 | } |
| 516 | }; |
| 517 | text(&mut out, &name); |
| 518 | for s in strs { |
| 519 | text(&mut out, " "); |
| 520 | if s.contains('\0') { |
| 521 | return Err(err!("A search string holds NUL, which IMAP cannot carry."; Invalid, Input)); |
| 522 | } |
| 523 | utf8 |= !s.is_ascii(); |
| 524 | match s.is_ascii() && !s.contains(['\r', '\n']) { |
| 525 | true => text(&mut out, &fmt!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))), |
| 526 | false => out.push(Segment::Literal(s.clone())), |
| 527 | } |
| 528 | } |
| 529 | } |
| 530 | if let (true, Some(Segment::Text(t))) = (utf8, out.first_mut()) { t.insert_str(0, "CHARSET UTF-8 "); } |
| 531 | Ok(out) |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | /// Appends command text, after a literal in a segment of its own. |
| 536 | fn text(out: &mut Vec<Segment>, s: &str) { |
| 537 | match out.last_mut() { |
| 538 | Some(Segment::Text(t)) => t.push_str(s), |
| 539 | _ => out.push(Segment::Text(s.to_string())), |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | /// `d-Mon-yyyy`, for a day within the four-digit years RFC 3501's `date-year` holds. |
| 544 | fn date(n: i64) -> Outcome<String> { |
| 545 | let (y, m, d) = civil_from_days(n); |
| 546 | match (days_from_civil(0, 1, 1)..=days_from_civil(9999, 12, 31)).contains(&n) { |
| 547 | true => Ok(fmt!("{}-{}-{:04}", d, MONTHS[(m as usize - 1) % 12], y)), |
| 548 | false => Err(err!("Day {} since the epoch has no four-digit year.", n; Invalid, Input)), |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | /// Where a line of SEARCH arguments ends in a literal marker `{n}` or `{n+}`: the text before |
| 553 | /// it, `n`, and whether the client waits for a continuation (`{n}`, synchronising). |
| 554 | pub fn trailing_literal(line: &str) -> Option<(String, usize, bool)> { |
| 555 | let inner = ok!(line.strip_suffix('}')); |
| 556 | let open = ok!(inner.rfind('{')); |
| 557 | let spec = &inner[open + 1..]; |
| 558 | let (digits, sync) = match spec.strip_suffix('+') { |
| 559 | Some(d) => (d, false), |
| 560 | None => (spec, true), |
| 561 | }; |
| 562 | if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { return None; } |
| 563 | let n: usize = ok!(digits.parse().ok()); |
| 564 | Some((line[..open].to_string(), n, sync)) |
| 565 | } |