oxedyne/fe2o3/fe2o3_mail/src/sync/act.rs
31.2 KiB, 256 runs
created by r1870400018:75201, 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 | //! Acting on the server for a journal entry, with every outcome definite. |
| 2 | //! |
| 3 | //! - A flag change is a `+FLAGS`/`-FLAGS` delta, never an absolute list. On a UID the folder no |
| 4 | //! longer holds it is [`ActOutcome::Gone`]: definite, not retried, and not an alarm. |
| 5 | //! - A move whose source UID is gone is `Done` when the target holds the message's `Message-ID`, |
| 6 | //! `Superseded` when any other folder does (another device filed it first), and `Lost` only |
| 7 | //! when none does. |
| 8 | //! - A `Message-ID` match is never trusted from `SEARCH` alone: each is confirmed by fetching |
| 9 | //! that header field ([`find_message_id`]). |
| 10 | //! - On a UIDVALIDITY that is no longer the entry's, the message is re-found by `Message-ID` and |
| 11 | //! size, and only a unique match is acted on; otherwise the entry is `Stuck`. |
| 12 | //! - Without `MOVE`, a move is `UID COPY`, `+FLAGS \Deleted` and `UID EXPUNGE`; without `UIDPLUS` |
| 13 | //! the action refuses, because a plain `EXPUNGE` would remove other `\Deleted` messages too. A |
| 14 | //! target that already holds the message's confirmed `Message-ID` is not copied to again, so a |
| 15 | //! retry after a cut between the copy and the expunge leaves one copy, not two. |
| 16 | //! - A copy is made once: a target that already holds the message by the one rule, byte for byte, |
| 17 | //! and not flagged `\Deleted`, is not copied to again, and a copy whose source UID is gone is |
| 18 | //! [`ActOutcome::Gone`]. |
| 19 | //! - A move or copy to the folder the message is already in does nothing and answers |
| 20 | //! [`ActOutcome::Already`], never `Done` (26 Oct 2026, QA mailA: a `Done` for Delete pressed in |
| 21 | //! Trash let the page forget a message the server kept). |
| 22 | |
| 23 | use crate::sync::{ |
| 24 | bare_message_id, |
| 25 | header_message_id, |
| 26 | Caps, |
| 27 | MailSession, |
| 28 | Roles, |
| 29 | SelectWith, |
| 30 | SpecialUse, |
| 31 | UidSet, |
| 32 | FetchWhat, |
| 33 | AppendUid, |
| 34 | }; |
| 35 | |
| 36 | use oxedyne_fe2o3_core::prelude::*; |
| 37 | use oxedyne_fe2o3_net::imap::types::parse_internal_date; |
| 38 | |
| 39 | |
| 40 | /// Where a move goes: a role, resolved by its attribute, or a path the user chose. |
| 41 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 42 | pub enum Target { |
| 43 | Inbox, |
| 44 | Role(SpecialUse), |
| 45 | Path(String), |
| 46 | } |
| 47 | |
| 48 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 49 | pub enum Action { |
| 50 | Flags { add: Vec<String>, remove: Vec<String> }, |
| 51 | Move { to: Target }, |
| 52 | Copy { to: Target }, // the message stays where it is |
| 53 | Archive, // by the provider's rule |
| 54 | Trash, |
| 55 | Junk, |
| 56 | NotJunk, // back to the inbox |
| 57 | Expunge, |
| 58 | } |
| 59 | |
| 60 | impl Action { |
| 61 | /// Does the action take the message out of its folder? |
| 62 | pub fn removes(&self) -> bool { |
| 63 | !matches!(self, Self::Flags { .. } | Self::Copy { .. }) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /// One journal entry, as the device recorded it at the press. |
| 68 | #[derive(Clone, Debug, Default, Eq, PartialEq)] |
| 69 | pub struct Entry { |
| 70 | pub id: u64, |
| 71 | pub mailbox: String, |
| 72 | pub uid_validity: u32, |
| 73 | pub uid: u32, |
| 74 | pub message_id: String, // empty where the message has none |
| 75 | pub size: u32, // RFC822.SIZE, which with the Message-ID re-finds it |
| 76 | pub internal_date: String, // INTERNALDATE: with the size, confirms a message with no Message-ID |
| 77 | pub year: Option<u16>, // of its Date, for a yearly archive |
| 78 | pub action: Action, |
| 79 | } |
| 80 | |
| 81 | impl Default for Action { |
| 82 | fn default() -> Self { |
| 83 | Self::Flags { add: Vec::new(), remove: Vec::new() } |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 88 | pub enum ActOutcome { |
| 89 | Done, |
| 90 | Already(String), // the message is in this folder already: nothing was done |
| 91 | Gone, // the UID is no longer in the folder: a flag change has nothing to do |
| 92 | Superseded(String), // another device filed it first, here |
| 93 | Lost, // found in no folder at all, to be shown, never dropped |
| 94 | Stuck(String), // cannot act without guessing; kept until the user decides |
| 95 | } |
| 96 | |
| 97 | /// The account's server, which fixes its archive and its Sent filing. |
| 98 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 99 | pub enum Provider { |
| 100 | Steel, |
| 101 | Gmail, |
| 102 | Office365, |
| 103 | Generic, |
| 104 | } |
| 105 | |
| 106 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 107 | pub enum ArchiveRule { |
| 108 | Yearly, // `<Archive>/<year>` of the message's Date, created when absent |
| 109 | AllFlat, // a move to the `\All` role, which drops Gmail's Inbox label |
| 110 | Role, // the `\Archive` role, flat |
| 111 | } |
| 112 | |
| 113 | /// Who puts a sent message's copy in Sent. |
| 114 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 115 | pub enum SentFiling { |
| 116 | Append, // the client, by `APPEND`, after a confirmed search finds no copy |
| 117 | // The server's SMTP does, asynchronously, so a search just after the send can miss a copy |
| 118 | // about to appear: never `APPEND`, which would double Sent. |
| 119 | ServerFiles, |
| 120 | } |
| 121 | |
| 122 | impl Provider { |
| 123 | /// The provider of an account on `host`: Gmail where the server says so (`X-GM-EXT-1`), else |
| 124 | /// the most specific row of `table`, the caller's, from config, whose host is `host` or a |
| 125 | /// domain above it, compared without case or a trailing dot; `Generic` where none is. An |
| 126 | /// address matches only itself, and no row makes an account Gmail: only the capability does. |
| 127 | pub fn of(caps: &Caps, host: &str, table: &[(String, Provider)]) -> Self { |
| 128 | if caps.gmail { |
| 129 | return Self::Gmail; |
| 130 | } |
| 131 | let norm = |h: &str| h.trim().trim_end_matches('.').to_ascii_lowercase(); |
| 132 | let host = norm(host); |
| 133 | let ip = host.parse::<std::net::IpAddr>().is_ok(); |
| 134 | table.iter() |
| 135 | .map(|(h, p)| (norm(h), *p)) |
| 136 | .filter(|(h, p)| !h.is_empty() && *p != Self::Gmail && (host == *h || (!ip |
| 137 | && host.strip_suffix(h.as_str()).map_or(false, |r| r.ends_with('.'))))) |
| 138 | .max_by_key(|(h, _)| h.len()) |
| 139 | .map_or(Self::Generic, |(_, p)| p) |
| 140 | } |
| 141 | |
| 142 | pub fn archive_rule(&self) -> ArchiveRule { |
| 143 | match self { |
| 144 | Self::Gmail => ArchiveRule::AllFlat, |
| 145 | Self::Office365 => ArchiveRule::Role, |
| 146 | Self::Steel | Self::Generic => ArchiveRule::Yearly, |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | pub fn sent_filing(&self) -> SentFiling { |
| 151 | match self { |
| 152 | Self::Gmail | Self::Office365 => SentFiling::ServerFiles, |
| 153 | Self::Steel | Self::Generic => SentFiling::Append, |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | /// What became of a draft saved over its earlier version. All but `Unchanged` and `Refused` |
| 159 | /// hold the new version's UID where the server gave one. |
| 160 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 161 | pub enum Saved { |
| 162 | Replaced(Option<AppendUid>), // saved, and the old version removed |
| 163 | OldGone(Option<AppendUid>), // saved; no old version was there to remove |
| 164 | OldLeft(Option<AppendUid>, String), // saved; the old version kept beside it, and why |
| 165 | Unchanged, // the old version is these bytes already: nothing done |
| 166 | Refused(String), // nothing saved, and why |
| 167 | } |
| 168 | |
| 169 | /// How a sent message's copy was filed. |
| 170 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 171 | pub enum Filed { |
| 172 | Server, // the server files it; confirmed later by a sync of Sent |
| 173 | Already, // a confirmed copy was there |
| 174 | Appended(Option<AppendUid>), |
| 175 | } |
| 176 | |
| 177 | |
| 178 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 179 | // │ ACTING │ |
| 180 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 181 | |
| 182 | /// Carries out one journal entry. An `Err` is a transport failure, which the journal may retry; |
| 183 | /// every outcome is definite. |
| 184 | pub async fn act<S: MailSession>( |
| 185 | s: &mut S, |
| 186 | caps: &Caps, |
| 187 | roles: &Roles, |
| 188 | provider: Provider, |
| 189 | e: &Entry, |
| 190 | ) |
| 191 | -> Outcome<ActOutcome> |
| 192 | { |
| 193 | // Where the message goes, resolved before anything is touched. |
| 194 | let dest = match &e.action { |
| 195 | Action::Flags { .. } | Action::Expunge => None, |
| 196 | other => match res!(destination(s, roles, provider, e, other).await) { |
| 197 | Ok(d) => Some(d), |
| 198 | Err(why) => return Ok(ActOutcome::Stuck(why)), |
| 199 | }, |
| 200 | }; |
| 201 | |
| 202 | if let Some(to) = &dest { |
| 203 | if *to == e.mailbox { |
| 204 | return Ok(ActOutcome::Already(to.clone())); |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | let st = res!(s.select(&e.mailbox, &SelectWith::Plain).await); |
| 209 | let uid = match res!(resolve(s, e, st.uid_validity, None).await) { |
| 210 | Ok(u) => u, |
| 211 | Err(why) => return Ok(ActOutcome::Stuck(why)), |
| 212 | }; |
| 213 | |
| 214 | match (&e.action, dest, uid) { |
| 215 | (Action::Flags { add, remove }, _, Some(u)) => { |
| 216 | let add: Vec<&str> = add.iter().map(|f| f.as_str()).collect(); |
| 217 | let remove: Vec<&str> = remove.iter().map(|f| f.as_str()).collect(); |
| 218 | res!(s.uid_store_flags(&UidSet::from([u]), &add, &remove).await); |
| 219 | Ok(ActOutcome::Done) |
| 220 | } |
| 221 | (Action::Flags { .. }, _, None) | (Action::Expunge, _, None) => Ok(ActOutcome::Gone), |
| 222 | (Action::Copy { .. }, Some(to), Some(u)) => { |
| 223 | // A replay after a cut between the COPY and its answer finds the copy made. |
| 224 | match res!(held_in(s, roles, &to, u, &e.mailbox).await) { |
| 225 | Ok(true) => {}, |
| 226 | Ok(false) => { res!(s.uid_copy(&UidSet::from([u]), &to).await); }, |
| 227 | Err(why) => return Ok(ActOutcome::Stuck(why)), |
| 228 | } |
| 229 | Ok(ActOutcome::Done) |
| 230 | } |
| 231 | (Action::Copy { .. }, _, None) => Ok(ActOutcome::Gone), |
| 232 | (Action::Expunge, _, Some(u)) => { |
| 233 | if !caps.uidplus { |
| 234 | return Ok(ActOutcome::Stuck(no_uid_expunge())); |
| 235 | } |
| 236 | res!(expunge_one(s, u).await); |
| 237 | Ok(ActOutcome::Done) |
| 238 | } |
| 239 | (_, Some(to), Some(u)) => { |
| 240 | let one = UidSet::from([u]); |
| 241 | if caps.mov { |
| 242 | res!(s.uid_move(&one, &to).await); |
| 243 | } else if caps.uidplus { |
| 244 | // A retry after a cut between the copy and the expunge finds the copy made. |
| 245 | match res!(held_in(s, roles, &to, u, &e.mailbox).await) { |
| 246 | Ok(true) => {}, |
| 247 | Ok(false) => { res!(s.uid_copy(&one, &to).await); }, |
| 248 | Err(why) => return Ok(ActOutcome::Stuck(why)), |
| 249 | } |
| 250 | res!(expunge_one(s, u).await); |
| 251 | } else { |
| 252 | return Ok(ActOutcome::Stuck(no_uid_expunge())); |
| 253 | } |
| 254 | Ok(ActOutcome::Done) |
| 255 | } |
| 256 | (_, Some(to), None) => locate(s, roles, e, &to).await, |
| 257 | (_, None, _) => Err(err!("Entry {}: a move with no destination.", e.id; Bug)), |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | /// The entry's UID in the folder selected, numbered `uv`, confirmed by the Message-ID and size |
| 262 | /// the entry gives, since a server may reuse a UID; `None` only where the UID holds no message. |
| 263 | /// `ours`, a version just saved, is never taken for it. The inner `Err` says why it cannot be |
| 264 | /// found without a guess, or what disagrees in a message there that is not confirmed as it. |
| 265 | async fn resolve<S: MailSession>(s: &mut S, e: &Entry, uv: u32, ours: Option<&Ours<'_>>) |
| 266 | -> Outcome<std::result::Result<Option<u32>, String>> |
| 267 | { |
| 268 | if e.size == 0 || (bare_message_id(&e.message_id).is_empty() && e.internal_date.is_empty()) { |
| 269 | return Ok(Err(fmt!("The entry gives no size, or neither a Message-ID nor a date, to confirm \ |
| 270 | UID {} in {} by.", e.uid, e.mailbox))); |
| 271 | } |
| 272 | if uv == e.uid_validity { |
| 273 | let want = Ident::of(e); |
| 274 | let m = match res!(idents(s, &[e.uid], want.dated()).await).into_iter().next() { |
| 275 | Some((_, m)) => m, |
| 276 | None => return Ok(Ok(None)), |
| 277 | }; |
| 278 | if let Err(what) = want.agrees(&m) { |
| 279 | return Ok(Err(fmt!("UID {} in {} holds a message not confirmed as the one \ |
| 280 | chosen ({}); it was left as it is.", e.uid, e.mailbox, what))); |
| 281 | } |
| 282 | if res!(mine(s, ours, uv, e.uid, m.size).await) { |
| 283 | return Ok(Err(fmt!("The earlier version in {} cannot be told from the one just \ |
| 284 | saved.", e.mailbox))); |
| 285 | } |
| 286 | return Ok(Ok(Some(e.uid))); |
| 287 | } |
| 288 | // The UIDs the entry was made under are void: re-find the message, only uniquely. |
| 289 | if e.message_id.is_empty() { |
| 290 | return Ok(Err(fmt!("Cannot identify the message: {} was renumbered and it has no \ |
| 291 | Message-ID.", e.mailbox))); |
| 292 | } |
| 293 | let mut found = Vec::new(); |
| 294 | match res!(find_same(s, &Ident::of(e)).await) { |
| 295 | Ok(f) => for (u, size) in f { |
| 296 | if !res!(mine(s, ours, uv, u, size).await) { |
| 297 | found.push(u); |
| 298 | } |
| 299 | }, |
| 300 | Err(why) => return Ok(Err(why)), |
| 301 | } |
| 302 | match found.len() { |
| 303 | 1 => Ok(Ok(Some(found[0]))), |
| 304 | n => Ok(Err(fmt!("Cannot identify the message: {} was renumbered and {} of its messages \ |
| 305 | are this one by its Message-ID, size and date.", e.mailbox, n))), |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | /// What a message is known by: its bare Message-ID (empty for none), size and INTERNALDATE. |
| 310 | #[derive(Debug, Default)] |
| 311 | struct Ident { |
| 312 | mid: String, |
| 313 | size: u32, |
| 314 | date: String, |
| 315 | } |
| 316 | |
| 317 | impl Ident { |
| 318 | fn of(e: &Entry) -> Self { |
| 319 | Self { mid: bare_message_id(&e.message_id).to_string(), size: e.size, date: e.internal_date.clone() } |
| 320 | } |
| 321 | |
| 322 | /// Is the date to be compared? Always without a Message-ID; with one, where it is held. |
| 323 | fn dated(&self) -> bool { |
| 324 | self.mid.is_empty() || !self.date.is_empty() |
| 325 | } |
| 326 | |
| 327 | /// The one rule by which a message on the server is taken for this one or its copy: the |
| 328 | /// Message-ID and the size, and the INTERNALDATE (as an instant) where it is held; with no |
| 329 | /// Message-ID, none there either, and the date always. `Err` says what disagrees. |
| 330 | fn agrees(&self, there: &Ident) -> std::result::Result<(), &'static str> { |
| 331 | if there.mid != self.mid { |
| 332 | return Err("its Message-ID differs"); |
| 333 | } |
| 334 | if there.size != self.size { |
| 335 | return Err("its size differs"); |
| 336 | } |
| 337 | if !self.dated() { |
| 338 | return Ok(()); |
| 339 | } |
| 340 | match (parse_internal_date(&there.date), parse_internal_date(&self.date)) { |
| 341 | (Some(a), Some(b)) if a == b => Ok(()), |
| 342 | (Some(_), Some(_)) => Err("its date differs"), |
| 343 | _ => Err("a date cannot be read"), |
| 344 | } |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | /// What the server holds at each of `uids` it answers for, its date fetched where `dated`. |
| 349 | async fn idents<S: MailSession>(s: &mut S, uids: &[u32], dated: bool) -> Outcome<Vec<(u32, Ident)>> { |
| 350 | if uids.is_empty() { |
| 351 | return Ok(Vec::new()); |
| 352 | } |
| 353 | let set = UidSet::from(&uids.to_vec()); |
| 354 | let mut out: Vec<(u32, Ident)> = res!(s.uid_fetch(&set, FetchWhat::MessageId).await).into_iter() |
| 355 | .filter(|m| set.contains(m.uid)) |
| 356 | .map(|m| (m.uid, Ident { mid: header_message_id(&m.body).unwrap_or_default(), size: m.size, |
| 357 | date: String::new() })) |
| 358 | .collect(); |
| 359 | if dated && !out.is_empty() { |
| 360 | let meta = res!(s.uid_fetch(&set, FetchWhat::Meta).await); |
| 361 | for (u, m) in out.iter_mut() { |
| 362 | if let Some(d) = meta.iter().find(|d| d.uid == *u) { |
| 363 | m.date = d.internal_date.clone(); |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | Ok(out) |
| 368 | } |
| 369 | |
| 370 | /// The messages in the folder selected that are `want` by the one rule, found by its Message-ID, |
| 371 | /// with their sizes; the inner `Err` where the Message-ID cannot be searched for. |
| 372 | async fn find_same<S: MailSession>(s: &mut S, want: &Ident) |
| 373 | -> Outcome<std::result::Result<Vec<(u32, u32)>, String>> |
| 374 | { |
| 375 | let uids: Vec<u32> = match res!(search_mid(s, &want.mid).await) { |
| 376 | Ok(f) => f.into_iter().map(|(u, _)| u).collect(), |
| 377 | Err(why) => return Ok(Err(why)), |
| 378 | }; |
| 379 | Ok(Ok(res!(idents(s, &uids, want.dated()).await).into_iter() |
| 380 | .filter(|(_, m)| want.agrees(m).is_ok()) |
| 381 | .map(|(u, m)| (u, m.size)) |
| 382 | .collect())) |
| 383 | } |
| 384 | |
| 385 | /// A version just saved, which a removal never takes for the one it removes. |
| 386 | struct Ours<'a> { |
| 387 | new: Option<AppendUid>, // as the server gave it |
| 388 | raw: &'a [u8], |
| 389 | } |
| 390 | |
| 391 | /// Is the message at `u`, numbered `uv`, of `size` bytes, the version just saved? By its |
| 392 | /// APPENDUID while that numbering stands, else by its bytes. |
| 393 | async fn mine<S: MailSession>(s: &mut S, ours: Option<&Ours<'_>>, uv: u32, u: u32, size: u32) |
| 394 | -> Outcome<bool> |
| 395 | { |
| 396 | match ours { |
| 397 | None => Ok(false), |
| 398 | Some(Ours { new: Some(n), .. }) if n.uid_validity == uv => Ok(n.uid == u), |
| 399 | Some(o) => same(s, u, size, o.raw).await, |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | /// Is the message at `u`, of `size` bytes, `raw` byte for byte? |
| 404 | async fn same<S: MailSession>(s: &mut S, u: u32, size: u32, raw: &[u8]) -> Outcome<bool> { |
| 405 | if size as usize != raw.len() { |
| 406 | return Ok(false); |
| 407 | } |
| 408 | Ok(res!(s.uid_fetch_section(u, "", size).await).map_or(false, |m| m.body == raw)) |
| 409 | } |
| 410 | |
| 411 | /// `+FLAGS \Deleted` and `UID EXPUNGE` of the one UID, so no other `\Deleted` message goes. |
| 412 | async fn expunge_one<S: MailSession>(s: &mut S, u: u32) -> Outcome<()> { |
| 413 | let one = UidSet::from([u]); |
| 414 | res!(s.uid_store_flags(&one, &["\\Deleted"], &[]).await); |
| 415 | s.uid_expunge(&one).await |
| 416 | } |
| 417 | |
| 418 | /// The source no longer holds the message: did the move happen, did another device file it, or |
| 419 | /// is it gone from everywhere? |
| 420 | async fn locate<S: MailSession>(s: &mut S, roles: &Roles, e: &Entry, to: &str) |
| 421 | -> Outcome<ActOutcome> |
| 422 | { |
| 423 | if e.message_id.is_empty() || e.size == 0 { |
| 424 | return Ok(ActOutcome::Stuck(fmt!("The message has left {} and has no Message-ID and size to \ |
| 425 | find it by.", e.mailbox))); |
| 426 | } |
| 427 | let want = Ident::of(e); |
| 428 | if roles.exists(to) { |
| 429 | res!(s.select(to, &SelectWith::Plain).await); |
| 430 | match res!(find_same(s, &want).await) { |
| 431 | Ok(f) if f.is_empty() => {}, |
| 432 | Ok(_) => return Ok(ActOutcome::Done), |
| 433 | Err(why) => return Ok(ActOutcome::Stuck(why)), |
| 434 | } |
| 435 | } |
| 436 | let others: Vec<String> = roles.selectable() |
| 437 | .filter(|m| *m != to && *m != e.mailbox) |
| 438 | .map(|m| m.to_string()) |
| 439 | .collect(); |
| 440 | for mb in others { |
| 441 | res!(s.select(&mb, &SelectWith::Plain).await); |
| 442 | match res!(find_same(s, &want).await) { |
| 443 | Ok(f) if f.is_empty() => {}, |
| 444 | Ok(_) => return Ok(ActOutcome::Superseded(mb)), |
| 445 | Err(why) => return Ok(ActOutcome::Stuck(why)), |
| 446 | } |
| 447 | } |
| 448 | Ok(ActOutcome::Lost) |
| 449 | } |
| 450 | |
| 451 | /// Does `to` hold a copy of the message at `u` in `back`: one that is it by the one rule, byte for |
| 452 | /// byte, and not flagged `\Deleted` (it waits only for an expunge)? Leaves `back` selected again. |
| 453 | /// Anything less is no copy, so a COPY is made: a double at worst, never a loss. A message with no |
| 454 | /// Message-ID is never looked for. |
| 455 | async fn held_in<S: MailSession>(s: &mut S, roles: &Roles, to: &str, u: u32, back: &str) |
| 456 | -> Outcome<std::result::Result<bool, String>> |
| 457 | { |
| 458 | if !roles.exists(to) { |
| 459 | return Ok(Ok(false)); |
| 460 | } |
| 461 | let src = match res!(idents(s, &[u], true).await).into_iter().next() { |
| 462 | Some((_, m)) if !m.mid.is_empty() => m, |
| 463 | _ => return Ok(Ok(false)), |
| 464 | }; |
| 465 | res!(s.select(to, &SelectWith::Plain).await); |
| 466 | let found = match res!(find_same(s, &src).await) { |
| 467 | Ok(f) if !f.is_empty() => Ok(res!(undeleted(s, f).await)), |
| 468 | other => other, |
| 469 | }; |
| 470 | res!(s.select(back, &SelectWith::Plain).await); |
| 471 | let f = match found { |
| 472 | Ok(f) if !f.is_empty() => f, |
| 473 | other => return Ok(other.map(|_| false)), |
| 474 | }; |
| 475 | // The source's bytes, fetched only now a candidate is there. |
| 476 | let raw = match res!(s.uid_fetch_section(u, "", src.size).await) { |
| 477 | Some(m) if m.body.len() == src.size as usize => m.body, |
| 478 | _ => return Ok(Ok(false)), |
| 479 | }; |
| 480 | res!(s.select(to, &SelectWith::Plain).await); |
| 481 | let mut held = false; |
| 482 | for (c, size) in f { |
| 483 | if res!(same(s, c, size, &raw).await) { |
| 484 | held = true; |
| 485 | break; |
| 486 | } |
| 487 | } |
| 488 | res!(s.select(back, &SelectWith::Plain).await); |
| 489 | Ok(Ok(held)) |
| 490 | } |
| 491 | |
| 492 | /// Those of `f` (UID, size) in the folder selected that the server answers for without `\Deleted`; |
| 493 | /// no flags answer is no answer. |
| 494 | async fn undeleted<S: MailSession>(s: &mut S, f: Vec<(u32, u32)>) -> Outcome<Vec<(u32, u32)>> { |
| 495 | let set = UidSet::from(&f.iter().map(|(u, _)| *u).collect::<Vec<u32>>()); |
| 496 | let flags = res!(s.uid_fetch(&set, FetchWhat::Flags).await); |
| 497 | Ok(f.into_iter() |
| 498 | .filter(|(u, _)| flags.iter().any(|m| m.uid == *u |
| 499 | && !m.flags.iter().any(|x| x.eq_ignore_ascii_case("\\Deleted")))) |
| 500 | .collect()) |
| 501 | } |
| 502 | |
| 503 | /// The mailbox an action moves to, created where the provider's rule needs one that is absent; |
| 504 | /// the inner `Err` says why it cannot be resolved without a guess. |
| 505 | async fn destination<S: MailSession>( |
| 506 | s: &mut S, |
| 507 | roles: &Roles, |
| 508 | provider: Provider, |
| 509 | e: &Entry, |
| 510 | action: &Action, |
| 511 | ) |
| 512 | -> Outcome<std::result::Result<String, String>> |
| 513 | { |
| 514 | let role = |r: SpecialUse| roles.role(r).map(|n| n.to_string()) |
| 515 | .ok_or_else(|| fmt!("The account has no {:?} folder.", r)); |
| 516 | let archive = || roles.role(SpecialUse::Archive).or(roles.archive.as_deref()) |
| 517 | .map(|n| n.to_string()) |
| 518 | .ok_or_else(|| fmt!("The account has no \\Archive folder, and no archive is configured.")); |
| 519 | let to = match action { |
| 520 | Action::Move { to: Target::Inbox } |
| 521 | | Action::Copy { to: Target::Inbox } |
| 522 | | Action::NotJunk => Ok(roles.inbox.clone()), |
| 523 | Action::Move { to: Target::Role(r) } |
| 524 | | Action::Copy { to: Target::Role(r) } => role(*r), |
| 525 | Action::Move { to: Target::Path(p) } |
| 526 | | Action::Copy { to: Target::Path(p) } => Ok(p.clone()), |
| 527 | Action::Trash => role(SpecialUse::Trash), |
| 528 | Action::Junk => role(SpecialUse::Junk), |
| 529 | Action::Archive => match provider.archive_rule() { |
| 530 | ArchiveRule::AllFlat => role(SpecialUse::All), |
| 531 | ArchiveRule::Role => archive(), |
| 532 | ArchiveRule::Yearly => { |
| 533 | let year = match e.year { |
| 534 | Some(y) => y, |
| 535 | None => return Ok(Err(fmt!("The message has no Date to archive it by."))), |
| 536 | }; |
| 537 | let base = match archive() { |
| 538 | Ok(b) => b, |
| 539 | Err(why) => return Ok(Err(why)), |
| 540 | }; |
| 541 | let delim = roles.mailboxes.iter() |
| 542 | .find(|m| m.name == base) |
| 543 | .and_then(|m| m.delimiter) |
| 544 | .or(roles.delimiter) |
| 545 | .unwrap_or('/'); |
| 546 | Ok(fmt!("{}{}{}", base, delim, year)) |
| 547 | } |
| 548 | }, |
| 549 | Action::Flags { .. } | Action::Expunge => Err(fmt!("Not a move.")), |
| 550 | }; |
| 551 | if let Ok(name) = &to { |
| 552 | if !roles.exists(name) { |
| 553 | if let Action::Archive = action { |
| 554 | // The roles were listed at the batch's start, so an earlier entry of this batch, |
| 555 | // or another device, may have made it since: a refusal is checked, not trusted. |
| 556 | if let Err(x) = s.create(name).await { |
| 557 | let made = res!(s.list().await).iter().any(|m| m.name == *name); |
| 558 | if !made { |
| 559 | return Err(x); |
| 560 | } |
| 561 | } |
| 562 | } |
| 563 | } |
| 564 | } |
| 565 | Ok(to) |
| 566 | } |
| 567 | |
| 568 | /// The year of an RFC 5322 `Date` as written (`[day-of-week ","] day month year ...`), a two- or |
| 569 | /// three-digit year read as RFC 5322 4.3 says, and taken only from 1970 to the year after `now`, |
| 570 | /// the caller's current year (a browser's clock is the caller's); `None` for anything else, so a |
| 571 | /// yearly archive is never made on a guess or on a spammer's `Date`. |
| 572 | pub fn date_year(date: &str, now: u16) -> Option<u16> { |
| 573 | const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", |
| 574 | "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; // fixed: RFC 5322 month |
| 575 | let d = match date.split_once(',') { |
| 576 | Some((dow, rest)) if dow.trim().chars().all(|c| c.is_ascii_alphabetic()) => rest, |
| 577 | _ => date, |
| 578 | }; |
| 579 | let digits = |x: &str| !x.is_empty() && x.bytes().all(|b| b.is_ascii_digit()); |
| 580 | match d.split_whitespace().take(3).collect::<Vec<_>>()[..] { |
| 581 | [day, mon, y] if digits(day) && digits(y) && MONTHS.iter().any(|m| m.eq_ignore_ascii_case(mon)) => { |
| 582 | let n = match y.parse::<u16>() { |
| 583 | Ok(n) => n, |
| 584 | Err(_) => return None, |
| 585 | }; |
| 586 | let y = match y.len() { |
| 587 | 2 if n < 50 => 2000 + n, |
| 588 | 2 | 3 => 1900 + n, |
| 589 | 4 => n, |
| 590 | _ => return None, |
| 591 | }; |
| 592 | // fixed: no mail predates the Unix epoch's clocks |
| 593 | (1970..=now.saturating_add(1)).contains(&y).then_some(y) |
| 594 | } |
| 595 | _ => None, |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | fn no_uid_expunge() -> String { |
| 600 | fmt!("The server offers neither MOVE nor UIDPLUS, and a plain EXPUNGE would remove other \ |
| 601 | deleted messages too.") |
| 602 | } |
| 603 | |
| 604 | /// The UIDs and sizes of the messages in the selected folder whose `Message-ID` is `mid`. The |
| 605 | /// server's `SEARCH` gives candidates only, since a server may match a substring or anything at |
| 606 | /// all; each is confirmed by fetching its `Message-ID` field, a few bytes. |
| 607 | pub async fn find_message_id<S: MailSession>(s: &mut S, mid: &str) -> Outcome<Vec<(u32, u32)>> { |
| 608 | match res!(search_mid(s, mid).await) { |
| 609 | Ok(found) => Ok(found), |
| 610 | Err(why) => Err(err!("{}", why; Invalid, Input)), |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | /// As [`find_message_id`], an id that cannot be searched for answered in words: a definite |
| 615 | /// outcome for the caller, never an error a journal retries. |
| 616 | async fn search_mid<S: MailSession>(s: &mut S, mid: &str) |
| 617 | -> Outcome<std::result::Result<Vec<(u32, u32)>, String>> |
| 618 | { |
| 619 | let bare = bare_message_id(mid); |
| 620 | if bare.is_empty() || bare.chars().any(|c| c.is_control() || c == '"' || c == '\\') { |
| 621 | return Ok(Err(fmt!("The Message-ID {:?} cannot be searched for: empty, or with a control \ |
| 622 | character, quote or backslash.", mid))); |
| 623 | } |
| 624 | let uids = res!(s.uid_search(&fmt!("HEADER Message-ID \"{}\"", bare)).await); |
| 625 | if uids.is_empty() { |
| 626 | return Ok(Ok(Vec::new())); |
| 627 | } |
| 628 | let asked = UidSet::from(&uids); |
| 629 | Ok(Ok(res!(s.uid_fetch(&asked, FetchWhat::MessageId).await).into_iter() |
| 630 | .filter(|m| asked.contains(m.uid) && header_message_id(&m.body).as_deref() == Some(bare)) |
| 631 | .map(|m| (m.uid, m.size)) |
| 632 | .collect())) |
| 633 | } |
| 634 | |
| 635 | /// Files a sent message's copy in Sent by the provider's rule. Only an `Append` account is |
| 636 | /// searched, and only a confirmed absence is appended to. The search is by the Message-ID read |
| 637 | /// from `raw`: one that `mid` does not name, or none, is refused (`Input`), as a retry could not |
| 638 | /// find the copy it made. |
| 639 | pub async fn file_sent<S: MailSession>( |
| 640 | s: &mut S, |
| 641 | roles: &Roles, |
| 642 | provider: Provider, |
| 643 | mid: &str, |
| 644 | raw: &[u8], |
| 645 | ) |
| 646 | -> Outcome<Filed> |
| 647 | { |
| 648 | let own = res!(header_message_id(raw).ok_or_else(|| err!( |
| 649 | "The sent message has no Message-ID to find its copy by."; Invalid, Input, Missing))); |
| 650 | if bare_message_id(mid) != own { |
| 651 | return Err(err!("The Message-ID given, {:?}, is not the sent message's own, <{}>.", mid, own; |
| 652 | Invalid, Input, Mismatch)); |
| 653 | } |
| 654 | if provider.sent_filing() == SentFiling::ServerFiles { |
| 655 | return Ok(Filed::Server); |
| 656 | } |
| 657 | let sent = res!(roles.role(SpecialUse::Sent) |
| 658 | .ok_or_else(|| err!("The account has no folder with the \\Sent role."; Missing))); |
| 659 | let sent = sent.to_string(); |
| 660 | res!(s.select(&sent, &SelectWith::Plain).await); |
| 661 | let want = Ident { mid: own.clone(), size: raw.len() as u32, ..Default::default() }; |
| 662 | match res!(find_same(s, &want).await) { |
| 663 | Ok(f) => for (u, size) in f { |
| 664 | if res!(same(s, u, size, raw).await) { |
| 665 | return Ok(Filed::Already); |
| 666 | } |
| 667 | }, |
| 668 | Err(why) => return Err(err!("{}", why; Invalid, Input)), |
| 669 | } |
| 670 | Ok(Filed::Appended(res!(s.append(&sent, &["\\Seen"], raw).await))) |
| 671 | } |
| 672 | |
| 673 | /// Saves `raw` to the `\Drafts` role with `\Draft \Seen`, and only once the server holds it |
| 674 | /// removes `old`, the earlier version (its `action` is not read), as `act` removes: confirmed, by |
| 675 | /// `UID EXPUNGE` alone. A cut between the two leaves two versions, never none. A retry after a cut |
| 676 | /// finds a stored copy by its Message-ID and bytes and does not append again, so a draft whose |
| 677 | /// Message-ID is missing or cannot be searched for is refused. |
| 678 | pub async fn save_draft<S: MailSession>( |
| 679 | s: &mut S, |
| 680 | caps: &Caps, |
| 681 | roles: &Roles, |
| 682 | raw: &[u8], |
| 683 | old: Option<&Entry>, |
| 684 | ) |
| 685 | -> Outcome<Saved> |
| 686 | { |
| 687 | let mid = match header_message_id(raw) { |
| 688 | Some(m) => m, |
| 689 | None => return Ok(Saved::Refused(fmt!("The draft has no Message-ID, so a retry could \ |
| 690 | not tell whether it was saved."))), |
| 691 | }; |
| 692 | let drafts = match roles.role(SpecialUse::Drafts) { |
| 693 | Some(d) => d.to_string(), |
| 694 | None => return Ok(Saved::Refused(fmt!("The account has no folder with the \\Drafts role."))), |
| 695 | }; |
| 696 | let st = res!(s.select(&drafts, &SelectWith::Plain).await); |
| 697 | let found = match res!(search_mid(s, &mid).await) { |
| 698 | Ok(f) => f, |
| 699 | Err(why) => return Ok(Saved::Refused(why)), |
| 700 | }; |
| 701 | // These bytes stored already, as the old version itself or before a cut: not appended again. |
| 702 | let in_place = old.filter(|o| o.mailbox == drafts && o.uid_validity == st.uid_validity); |
| 703 | let mut stored = None; |
| 704 | for (u, size) in found { |
| 705 | // Kept only on a flags answer without \Deleted; none, or a garbled one, is not kept. |
| 706 | if res!(same(s, u, size, raw).await) && res!(s.uid_fetch(&UidSet::from([u]), FetchWhat::Flags) |
| 707 | .await).iter().any(|m| m.uid == u && !m.flags.iter().any(|f| f.eq_ignore_ascii_case("\\Deleted"))) |
| 708 | { |
| 709 | if let Some(o) = in_place.filter(|o| o.uid == u) { |
| 710 | let want = Ident::of(o); |
| 711 | if res!(idents(s, &[u], want.dated()).await).iter().any(|(_, m)| want.agrees(m).is_ok()) { |
| 712 | return Ok(Saved::Unchanged); |
| 713 | } |
| 714 | } |
| 715 | stored = Some(AppendUid { uid_validity: st.uid_validity, uid: u }); |
| 716 | break; |
| 717 | } |
| 718 | } |
| 719 | let new = match stored { |
| 720 | Some(n) => Some(n), |
| 721 | None => res!(s.append(&drafts, &["\\Draft", "\\Seen"], raw).await), |
| 722 | }; |
| 723 | |
| 724 | let o = match old { |
| 725 | Some(o) => o, |
| 726 | None => return Ok(Saved::OldGone(new)), |
| 727 | }; |
| 728 | let in_drafts = roles.mailboxes.iter() |
| 729 | .any(|m| m.name == o.mailbox && m.special_use() == Some(SpecialUse::Drafts)); |
| 730 | if !in_drafts { |
| 731 | return Ok(Saved::OldLeft(new, fmt!("The earlier version is in {}, not a drafts folder.", |
| 732 | o.mailbox))); |
| 733 | } |
| 734 | if !caps.uidplus { |
| 735 | return Ok(Saved::OldLeft(new, no_uid_expunge())); |
| 736 | } |
| 737 | let st = res!(s.select(&o.mailbox, &SelectWith::Plain).await); |
| 738 | let ours = Ours { new, raw }; |
| 739 | match res!(resolve(s, o, st.uid_validity, Some(&ours)).await) { |
| 740 | Ok(Some(u)) => { |
| 741 | res!(expunge_one(s, u).await); |
| 742 | Ok(Saved::Replaced(new)) |
| 743 | } |
| 744 | Ok(None) => Ok(Saved::OldGone(new)), |
| 745 | Err(why) => Ok(Saved::OldLeft(new, why)), |
| 746 | } |
| 747 | } |