pim_schedule.rs
⎇
Raw
1//! Implicit scheduling (RFC 6638) between the principals of this server.
2//!
3//! `pimdav::itip` decides what a change sends to whom. This module finds the
4//! recipients and their objects, and turns every message into writes that
5//! commit together with the change itself. Nothing leaves the server: an
6//! address outside it gets a delivery failure in its SCHEDULE-STATUS.
7//!
8//! Rooms and resources answer at once, from their own bookings. The outbox
9//! answers free-busy requests from the recipients' calendars.
10
11use std::collections::hash_map::Entry;
12use std::collections::{HashMap, HashSet};
13use std::sync::Arc;
14
15use chrono::{DateTime, Utc};
16use percent_encoding::percent_decode_str;
17use pimdav::calcard::icalendar::{
18 ICalendar, ICalendarComponent, ICalendarComponentType, ICalendarProperty, ICalendarValue,
19};
20use pimdav::expand;
21use pimdav::filter::TimeRange;
22use pimdav::freebusy::{self, Period};
23use pimdav::itip::{self, Message, Method, Role};
24use pimdav::principal::UserType;
25use pimdav::render;
26use pimdav::xml::{CALDAV, el, hrefs, with_children};
27use pimdav::zone::{self, Zone};
28use sha2::{Digest, Sha256};
29use tokio::sync::Mutex;
30use xmltree::Element;
31
32use super::pim::{
33 INBOX, MAIL_DOMAIN, OUTBOX, collection_href, etag_of, local_part, need_privilege,
34 principal_name, principal_uuid, seg,
35};
36use crate::api::common::blocking;
37use crate::db::{PimKind, PimObject, PimOp, PimPrincipal};
38use crate::error::{ApiError, AppState};
39
40/// Held from reading a calendar object to committing the change, so that a
41/// change and the writes it causes see a consistent store.
42// ponytail: one lock for every object write. Per-UID locks if write
43// throughput ever matters.
44pub(crate) static LOCK: Mutex<()> = Mutex::const_new(());
45
46/// The delivery status codes of RFC 6638, 3.2.9.
47const DELIVERED: &str = "1.2";
48/// An address in this server's domains that names no one.
49const INVALID_USER: &str = "3.7";
50/// An address outside this server: there is no iMIP to reach it.
51const NO_ROUTE: &str = "5.2";
52/// A reply the organizer's object had no room for in full.
53const UNDELIVERED: &str = "5.1";
54/// The recipient has no calendar for the component.
55const REFUSED: &str = "5.3";
56/// The recipient holds an object with this UID that is not its copy of the
57/// sender's meeting (RFC 6638: no scheduling privileges).
58const NO_AUTHORITY: &str = "3.8";
59
60/// Recipients one free-busy request answers. Each costs an expansion of
61/// their calendars.
62const MAX_FREE_BUSY_ATTENDEES: usize = 100;
63
64/// Who writes into a calendar, as far as scheduling cares.
65pub(crate) struct Writer<'a> {
66 pub owner: &'a PimPrincipal,
67 /// May send messages as the owner (RFC 6638 `schedule-send`).
68 pub may_schedule: bool,
69 /// The writer's address when it is not the owner, for SENT-BY.
70 pub sent_by: Option<String>,
71 /// Stores the object without sending anything.
72 pub quiet: bool,
73}
74
75impl Writer<'_> {
76 /// The owner itself.
77 pub(crate) fn owner(owner: &PimPrincipal) -> Writer<'_> {
78 Writer {
79 owner,
80 may_schedule: true,
81 sent_by: None,
82 quiet: false,
83 }
84 }
85
86 /// 403 `need-privileges` on the owner's outbox.
87 fn refused(&self, privilege: &str) -> Element {
88 let outbox = collection_href(&self.owner.name, PimKind::Calendar, OUTBOX, None);
89 need_privilege(&outbox, CALDAV, privilege)
90 }
91}
92
93/// Every principal, for mapping calendar user addresses.
94#[derive(Clone)]
95pub(crate) struct Directory(Vec<PimPrincipal>);
96
97enum Recipient<'a> {
98 Local(&'a PimPrincipal),
99 Unknown,
100 External,
101}
102
103fn found(p: Option<&PimPrincipal>) -> Recipient<'_> {
104 match p {
105 Some(p) => Recipient::Local(p),
106 None => Recipient::Unknown,
107 }
108}
109
110impl Directory {
111 /// Disabled accounts included: they cannot log in, but their copies stay
112 /// current.
113 pub(crate) async fn load(state: &AppState) -> Result<Self, ApiError> {
114 Ok(Directory(state.db.pim_principals(false).await?))
115 }
116
117 pub(crate) fn get(&self, id: i64) -> Option<&PimPrincipal> {
118 self.0.iter().find(|p| p.id == id)
119 }
120
121 /// The forms `calendar-user-address-set` lists: the mailto address, the
122 /// principal URL and the `urn:uuid:`. Compared without case.
123 fn resolve(&self, addr: &str) -> Recipient<'_> {
124 let addr = addr.trim();
125 let lower = addr.to_ascii_lowercase();
126 if let Some(rest) = lower.strip_prefix("mailto:") {
127 let Some((local, domain)) = rest.rsplit_once('@') else {
128 return Recipient::External;
129 };
130 let kind = match domain.strip_suffix(MAIL_DOMAIN) {
131 Some("") => UserType::Individual,
132 Some("rooms.") => UserType::Room,
133 Some("resources.") => UserType::Resource,
134 // The tombstone of a deleted principal.
135 Some("deleted.") => return Recipient::Unknown,
136 _ => return Recipient::External,
137 };
138 let name = percent_decode_str(local).decode_utf8_lossy();
139 return found(
140 self.0
141 .iter()
142 .find(|p| p.kind == kind && p.name.eq_ignore_ascii_case(&name)),
143 );
144 }
145 if let Some(uuid) = lower.strip_prefix("urn:uuid:") {
146 return found(self.0.iter().find(|p| principal_uuid(p.id) == uuid));
147 }
148 match principal_name(addr) {
149 Some(name) => found(self.0.iter().find(|p| p.name.eq_ignore_ascii_case(&name))),
150 None if lower.starts_with('/') || lower.starts_with("http") => Recipient::Unknown,
151 None => Recipient::External,
152 }
153 }
154
155 /// Whether an address names principal `id`.
156 pub(crate) fn is(&self, id: i64) -> impl Fn(&str) -> bool + '_ {
157 move |a: &str| matches!(self.resolve(a), Recipient::Local(p) if p.id == id)
158 }
159}
160
161/// The writes that make other principals' objects forget `gone` before it
162/// is deleted, after `retracted`, the writes of [`retract`]. Its addresses
163/// become a tombstone in `deleted.` of the mail domain, which names no one,
164/// so a later principal of the same name gets nothing meant for the old one.
165/// Commit them together with the delete, holding [`LOCK`].
166pub(crate) async fn forget(
167 state: &AppState,
168 gone: &PimPrincipal,
169 mut retracted: Vec<PimOp>,
170) -> Result<Vec<PimOp>, ApiError> {
171 let dir = Directory(vec![gone.clone()]);
172 let is_gone = dir.is(gone.id);
173 let encoded = local_part(&gone.name);
174 let tombstone = format!("mailto:{encoded}-{}@deleted.{MAIL_DOMAIN}", gone.id);
175 let uuid = principal_uuid(gone.id);
176 let needles = [gone.name.as_str(), encoded.as_str(), uuid.as_str()];
177 let rewrite = |data: &[u8]| {
178 itip::forget(&String::from_utf8_lossy(data), &is_gone, &tombstone).map(String::into_bytes)
179 };
180 let retracted_puts: HashSet<(i64, &str)> = retracted
181 .iter()
182 .filter_map(|op| match op {
183 PimOp::Put {
184 collection_id, obj, ..
185 } => Some((*collection_id, obj.name.as_str())),
186 _ => None,
187 })
188 .collect();
189 let mut ops = Vec::new();
190 for (collection_id, obj, data) in state.db.pim_objects_mentioning(gone.id, &needles).await? {
191 if retracted_puts.contains(&(collection_id, obj.name.as_str())) {
192 continue;
193 }
194 let Some(data) = rewrite(&data) else {
195 continue;
196 };
197 ops.push(PimOp::Put {
198 collection_id,
199 obj: PimObject {
200 etag: etag_of(&data),
201 ..obj
202 },
203 data,
204 });
205 }
206 for op in &mut retracted {
207 if let PimOp::Put { obj, data, .. } | PimOp::Inbox { obj, data, .. } = op
208 && let Some(new) = rewrite(data)
209 {
210 obj.etag = etag_of(&new);
211 *data = new;
212 }
213 }
214 // Last, because inbox writes drop the oldest messages; a rewrite after
215 // them would bring a dropped one back.
216 ops.extend(retracted);
217 Ok(ops)
218}
219
220/// What a PUT of a calendar object stores, and what else it writes.
221pub(crate) struct Stored {
222 pub data: Vec<u8>,
223 /// Whether `data` differs from the request body.
224 pub changed: bool,
225 pub schedule_tag: Option<String>,
226 pub ops: Vec<PimOp>,
227}
228
229/// A PUT of `body` over `old` into collection `at.0` under the name `at.1`.
230/// `Err` names a failed scheduling precondition.
231pub(crate) async fn put(
232 state: &AppState,
233 dir: &Directory,
234 w: &Writer<'_>,
235 at: (i64, &str),
236 old: Option<&[u8]>,
237 body: &[u8],
238) -> Result<Result<Stored, Element>, ApiError> {
239 let parse = |b: &[u8]| render::parse(&String::from_utf8_lossy(b));
240 let Some(sent) = parse(body) else {
241 return Ok(Ok(unchanged(body, None)));
242 };
243 let owner = w.owner;
244 let owns = dir.is(owner.id);
245 let role = match itip::role(&sent, &owns) {
246 Ok(r) => r,
247 Err(refused) => return Ok(Err(refused.condition())),
248 };
249 if role != Role::None
250 && let Some(holder) = elsewhere(state, owner, &sent, at).await?
251 {
252 return Ok(Err(holder));
253 }
254 let old = old.and_then(parse);
255 let old_role = old.as_ref().and_then(|o| itip::role(o, &owns).ok());
256 let now = Utc::now();
257 let mut ops = Vec::new();
258
259 let stored = match (role, old_role) {
260 (Role::Organizer, _) => {
261 let old = old.as_ref().filter(|_| old_role == Some(Role::Organizer));
262 let (mut store, force) = itip::prepare(old, &sent, &owns);
263 let mut messages = match w.quiet {
264 true => Vec::new(),
265 false => itip::messages(old, Some(&store), &owns, &force, now),
266 };
267 if !messages.is_empty() && !w.may_schedule {
268 // A SEQUENCE bump alone is no invitation. The copies are not
269 // reached, so the stored object keeps their SEQUENCE.
270 let Some(same) = only_sequence(old, &store, &owns, &force, now) else {
271 return Ok(Err(w.refused("schedule-send-invite")));
272 };
273 store = same;
274 messages.clear();
275 }
276 if !messages.is_empty() {
277 itip::stamp_sender(&mut store, &owns, w.sent_by.as_deref());
278 messages = itip::messages(old, Some(&store), &owns, &force, now);
279 }
280 // Rooms answer first, so the others' copies carry their answers.
281 if answer_rooms(state, dir, owner, &mut store, &messages, &mut ops, now).await? {
282 messages = itip::messages(old, Some(&store), &owns, &force, now);
283 }
284 let mut sent = Sent::new();
285 for m in &messages {
286 if let Some(status) = deliver(state, dir, owner, m, &mut ops, &mut sent).await? {
287 itip::set_attendee_status(&mut store, &m.to, status);
288 }
289 }
290 store
291 }
292 (Role::Attendee, Some(Role::Attendee)) => {
293 let old = old.as_ref().expect("an attendee role needs the old object");
294 let (mut store, reply) = match itip::attend(old, sent.clone(), &owns, now) {
295 Ok(v) => v,
296 Err(refused) => return Ok(Err(refused.condition())),
297 };
298 if let Some(mut reply) = reply.filter(|_| !w.quiet) {
299 if !w.may_schedule {
300 return Ok(Err(w.refused("schedule-send-reply")));
301 }
302 itip::stamp_sender(&mut store, &owns, w.sent_by.as_deref());
303 itip::stamp_sender(Arc::make_mut(&mut reply.cal), &owns, w.sent_by.as_deref());
304 let status = reply_to(state, dir, owner, &reply, &mut ops).await?;
305 itip::set_organizer_status(&mut store, status);
306 }
307 store
308 }
309 // No longer a scheduling object, or a copy the attendee brings in
310 // itself (RFC 6638, 3.2.2.2): stored as sent.
311 (_, previous) => {
312 if let Some(old) = old.as_ref().filter(|_| !w.quiet) {
313 match removed(state, dir, w, old, previous, true).await? {
314 Ok(more) => ops.extend(more),
315 Err(refused) => return Ok(Err(refused)),
316 }
317 }
318 let tag = (role != Role::None).then(|| etag_of(body));
319 return Ok(Ok(Stored {
320 ops,
321 ..unchanged(body, tag)
322 }));
323 }
324 };
325 let changed = stored != sent;
326 let data = match changed {
327 true => render::write(&stored).into_bytes(),
328 false => body.to_vec(),
329 };
330 Ok(Ok(Stored {
331 schedule_tag: Some(etag_of(&data)),
332 data,
333 changed,
334 ops,
335 }))
336}
337
338/// `store` with the SEQUENCE values of `old`, if that leaves the attendees
339/// nothing to hear.
340fn only_sequence(
341 old: Option<&ICalendar>,
342 store: &ICalendar,
343 owns: itip::Is,
344 force: &[String],
345 now: DateTime<Utc>,
346) -> Option<ICalendar> {
347 let old = old?;
348 let key = |c: &ICalendarComponent| {
349 c.property(&ICalendarProperty::RecurrenceId)
350 .map(|e| format!("{:?}", e.values))
351 };
352 let sequences: HashMap<_, _> = old
353 .components
354 .iter()
355 .filter(|c| c.has_property(&ICalendarProperty::Uid))
356 .map(|c| (key(c), c.property(&ICalendarProperty::Sequence).cloned()))
357 .collect();
358 let mut same = store.clone();
359 for c in same
360 .components
361 .iter_mut()
362 .filter(|c| c.has_property(&ICalendarProperty::Uid))
363 {
364 let sequence = sequences.get(&key(c))?;
365 c.entries.retain(|e| e.name != ICalendarProperty::Sequence);
366 c.entries.extend(sequence.clone());
367 }
368 itip::messages(Some(old), Some(&same), owns, force, now)
369 .is_empty()
370 .then_some(same)
371}
372
373/// The resource name the server picks for an object it creates.
374pub(crate) fn object_name(uid: &str, kind: PimKind) -> String {
375 let ext = match kind {
376 PimKind::Calendar => "ics",
377 PimKind::AddressBook => "vcf",
378 };
379 format!("{}.{ext}", &crate::hex(&Sha256::digest(uid))[..32])
380}
381
382fn unchanged(body: &[u8], schedule_tag: Option<String>) -> Stored {
383 Stored {
384 data: body.to_vec(),
385 changed: false,
386 schedule_tag,
387 ops: Vec::new(),
388 }
389}
390
391/// The writes a DELETE of `old` causes. `reply` is false for
392/// `Schedule-Reply: F` (RFC 6638, 8.1). `Err` names a lacking privilege.
393pub(crate) async fn delete(
394 state: &AppState,
395 dir: &Directory,
396 w: &Writer<'_>,
397 old: &[u8],
398 reply: bool,
399) -> Result<Result<Vec<PimOp>, Element>, ApiError> {
400 let Some(old) = render::parse(&String::from_utf8_lossy(old)) else {
401 return Ok(Ok(Vec::new()));
402 };
403 let role = itip::role(&old, &dir.is(w.owner.id)).ok();
404 removed(state, dir, w, &old, role, reply).await
405}
406
407/// The writes that cancel or decline every object of the collections for
408/// their attendees, as deleting each object would. Hold [`LOCK`].
409pub(crate) async fn retract(
410 state: &AppState,
411 dir: &Directory,
412 owner: &PimPrincipal,
413 collection_ids: &[i64],
414) -> Result<Result<Vec<PimOp>, Element>, ApiError> {
415 let w = Writer::owner(owner);
416 let mut ops = Vec::new();
417 for &id in collection_ids {
418 for (_, data) in state.db.pim_objects_with_data(id).await? {
419 match delete(state, dir, &w, &data, true).await? {
420 Ok(more) => ops.extend(more),
421 Err(refused) => return Ok(Err(refused)),
422 }
423 }
424 }
425 Ok(Ok(ops))
426}
427
428/// An organizer object going away cancels; an attendee copy declines.
429async fn removed(
430 state: &AppState,
431 dir: &Directory,
432 w: &Writer<'_>,
433 old: &ICalendar,
434 role: Option<Role>,
435 reply: bool,
436) -> Result<Result<Vec<PimOp>, Element>, ApiError> {
437 let owner = w.owner;
438 let owns = dir.is(owner.id);
439 let now = Utc::now();
440 let mut old = old.clone();
441 itip::stamp_sender(&mut old, &owns, w.sent_by.as_deref());
442 let mut ops = Vec::new();
443 match role {
444 Some(Role::Organizer) => {
445 let (_, messages) = itip::organize(Some(&old), None, &owns, now);
446 if !messages.is_empty() && !w.may_schedule {
447 return Ok(Err(w.refused("schedule-send-invite")));
448 }
449 let mut sent = Sent::new();
450 for m in &messages {
451 deliver(state, dir, owner, m, &mut ops, &mut sent).await?;
452 }
453 }
454 Some(Role::Attendee) if reply => {
455 if let Some(m) = itip::decline(&old, &owns, now) {
456 if !w.may_schedule {
457 return Ok(Err(w.refused("schedule-send-reply")));
458 }
459 reply_to(state, dir, owner, &m, &mut ops).await?;
460 }
461 }
462 _ => {}
463 }
464 Ok(Ok(ops))
465}
466
467/// The resource of the owner that already schedules this UID elsewhere:
468/// RFC 6638 allows one per UID (3.2.4.1).
469async fn elsewhere(
470 state: &AppState,
471 owner: &PimPrincipal,
472 cal: &ICalendar,
473 (collection_id, name): (i64, &str),
474) -> Result<Option<Element>, ApiError> {
475 let Some((uid, _)) = identity(cal) else {
476 return Ok(None);
477 };
478 let Some((holder_id, holder, _)) = state.db.pim_find_uid(owner.id, &uid).await? else {
479 return Ok(None);
480 };
481 // A plain event with the same UID schedules nothing.
482 if holder.schedule_tag.is_none() || (holder_id == collection_id && holder.name == name) {
483 return Ok(None);
484 }
485 let slug = match state.db.pim_collection_by_id(holder_id).await? {
486 Some((_, _, c)) => c.slug,
487 None => return Ok(None),
488 };
489 let href = collection_href(&owner.name, PimKind::Calendar, &slug, None) + &seg(&holder.name);
490 Ok(Some(with_children(
491 el(CALDAV, "unique-scheduling-object-resource"),
492 hrefs([href.as_str()]),
493 )))
494}
495
496/// Rooms and resources answer their invitations at once: accepted where
497/// free, declined where their bookings overlap. The answers go into the
498/// organizer's `store` and inbox. Returns whether any room answered.
499async fn answer_rooms(
500 state: &AppState,
501 dir: &Directory,
502 organizer: &PimPrincipal,
503 store: &mut ICalendar,
504 messages: &[Message],
505 ops: &mut Vec<PimOp>,
506 now: DateTime<Utc>,
507) -> Result<bool, ApiError> {
508 let mut answered = false;
509 for m in messages
510 .iter()
511 .filter(|m| m.method == Method::Request && !m.quiet)
512 {
513 let Recipient::Local(room) = dir.resolve(&m.to) else {
514 continue;
515 };
516 let Some((uid, component)) = identity(&m.cal) else {
517 continue;
518 };
519 if room.kind == UserType::Individual {
520 continue;
521 }
522 let Some(calendar) = state.db.pim_calendar_for(room.id, &component).await? else {
523 continue;
524 };
525 let Ok(copy) = copy_of(state, dir, room, organizer, &uid).await? else {
526 continue;
527 };
528 let Some(received) = itip::receive(copy.as_ref().map(|(_, _, c)| c), m) else {
529 continue;
530 };
531 let is_room = dir.is(room.id);
532 let window = now..now + itip::answer_horizon(&received);
533 let taken = busy_of(state, dir, room, &window, Some(&uid)).await?;
534 let floating = floating_of(calendar.timezone.as_deref());
535 let answer = itip::auto_answer(&received, &is_room, &taken, &window, &floating);
536 let Ok((_, Some(reply))) = itip::attend(&received, answer, &is_room, now) else {
537 continue;
538 };
539 answered |= itip::apply_reply(store, &reply.cal, &is_room).changed;
540 ops.push(inbox(organizer, &reply, &component));
541 }
542 Ok(answered)
543}
544
545/// The busy time a principal shows to scheduling: its opaque calendars that
546/// take events, never the inbox. Objects with UID `skip` do not count.
547// ponytail: reads every object of those calendars per call. Keep busy
548// periods in a table if principals grow large calendars.
549pub(crate) async fn busy_of(
550 state: &AppState,
551 dir: &Directory,
552 p: &PimPrincipal,
553 range: &TimeRange,
554 skip: Option<&str>,
555) -> Result<Vec<Period>, ApiError> {
556 let mut calendars = Vec::new();
557 for c in state.db.pim_collections(p.id, PimKind::Calendar).await? {
558 if c.slug == INBOX || c.transparent || !c.components.split(',').any(|x| x == "VEVENT") {
559 continue;
560 }
561 let objects = state.db.pim_objects_with_data(c.id).await?;
562 calendars.push((floating_of(c.timezone.as_deref()), objects));
563 }
564 let (dir, id, range, skip) = (dir.clone(), p.id, range.clone(), skip.map(str::to_string));
565 blocking(move || -> Result<_, ApiError> {
566 let me = dir.is(id);
567 let mut busy = Vec::new();
568 for (floating, objects) in calendars {
569 for (o, data) in objects {
570 if skip.as_deref().is_some_and(|u| u == o.uid) {
571 continue;
572 }
573 if let Ok(cal) = ICalendar::parse(String::from_utf8_lossy(&data).as_ref()) {
574 busy.extend(freebusy::busy(&cal, &range, &floating, Some(&me)));
575 }
576 }
577 }
578 Ok(freebusy::merge(busy))
579 })
580 .await
581}
582
583fn floating_of(timezone: Option<&str>) -> Zone {
584 timezone.and_then(zone::from_vtimezone).unwrap_or(Zone::Utc)
585}
586
587/// Whether every instance of the calendar object `body` ended before `now`.
588/// A component without a start, or a rule without COUNT that runs until
589/// about now or later, never ends.
590pub(crate) fn ended(body: &[u8], timezone: Option<&str>, now: DateTime<Utc>) -> bool {
591 let Ok(cal) = ICalendar::parse(String::from_utf8_lossy(body).as_ref()) else {
592 return false;
593 };
594 // A day of slack covers an UNTIL in a zone or floating.
595 let soon = now.naive_utc() - chrono::TimeDelta::days(1);
596 let open = cal.components.iter().any(|c| {
597 let item = matches!(
598 c.component_type,
599 ICalendarComponentType::VEvent
600 | ICalendarComponentType::VTodo
601 | ICalendarComponentType::VJournal
602 );
603 let endless = c.properties(&ICalendarProperty::Rrule).any(|e| {
604 matches!(e.values.first(), Some(ICalendarValue::RecurrenceRule(r))
605 if r.count.is_none() && r.until.as_ref().and_then(|u| u.to_date_time())
606 .is_none_or(|u| u.date_time >= soon))
607 });
608 item && (endless || !c.has_property(&ICalendarProperty::Dtstart))
609 });
610 if open {
611 return false;
612 }
613 let x = expand::expand(&cal, now..DateTime::<Utc>::MAX_UTC, floating_of(timezone));
614 x.instances.is_empty() && !x.truncated
615}
616
617/// The answers to a free-busy request to an outbox (RFC 6638, 5.2): per
618/// recipient its address, the REQUEST-STATUS and the VFREEBUSY reply.
619pub(crate) async fn free_busy(
620 state: &AppState,
621 dir: &Directory,
622 req: &freebusy::Request,
623) -> Result<Vec<(String, &'static str, Option<String>)>, ApiError> {
624 let now = Utc::now();
625 let mut out = Vec::new();
626 let mut known: HashMap<i64, Vec<Period>> = HashMap::new();
627 for (i, to) in req.attendees.iter().enumerate() {
628 let (status, data) = match dir.resolve(to) {
629 _ if i >= MAX_FREE_BUSY_ATTENDEES => ("5.1;Service unavailable", None),
630 // A disabled account still gets messages, but shows no busy time.
631 Recipient::Local(p) if !p.active => ("3.7;Invalid calendar user", None),
632 Recipient::Local(p) => {
633 if let Entry::Vacant(e) = known.entry(p.id) {
634 e.insert(busy_of(state, dir, p, &req.range, None).await?);
635 }
636 (
637 "2.0;Success",
638 Some(freebusy::reply(&known[&p.id], req, to, now)),
639 )
640 }
641 Recipient::Unknown => ("3.7;Invalid calendar user", None),
642 Recipient::External => ("5.2;Invalid calendar service", None),
643 };
644 out.push((to.clone(), status, data));
645 }
646 Ok(out)
647}
648
649/// Statuses of the deliveries in one batch: principal, body, quiet.
650type Sent = Vec<(i64, Arc<ICalendar>, bool, Option<&'static str>)>;
651
652/// A REQUEST or CANCEL from `sender` into the recipient's calendar and
653/// inbox. Returns the delivery status, `None` for the sender itself. A
654/// principal named by two addresses that see the same message gets it once.
655async fn deliver(
656 state: &AppState,
657 dir: &Directory,
658 sender: &PimPrincipal,
659 m: &Message,
660 ops: &mut Vec<PimOp>,
661 sent: &mut Sent,
662) -> Result<Option<&'static str>, ApiError> {
663 let p = match dir.resolve(&m.to) {
664 Recipient::Local(p) if p.id == sender.id => return Ok(None),
665 Recipient::Local(p) => p,
666 Recipient::Unknown => return Ok(Some(INVALID_USER)),
667 Recipient::External => return Ok(Some(NO_ROUTE)),
668 };
669 // A forced send must not reuse a quiet one.
670 if let Some((.., status)) = sent
671 .iter()
672 .find(|(id, c, quiet, _)| *id == p.id && Arc::ptr_eq(c, &m.cal) && *quiet == m.quiet)
673 {
674 return Ok(*status);
675 }
676 let status = deliver_to(state, dir, sender, p, m, ops).await?;
677 sent.push((p.id, m.cal.clone(), m.quiet, status));
678 Ok(status)
679}
680
681async fn deliver_to(
682 state: &AppState,
683 dir: &Directory,
684 sender: &PimPrincipal,
685 p: &PimPrincipal,
686 m: &Message,
687 ops: &mut Vec<PimOp>,
688) -> Result<Option<&'static str>, ApiError> {
689 ensure(state, p).await?;
690 let Some((uid, component)) = identity(&m.cal) else {
691 return Ok(Some(REFUSED));
692 };
693 let Ok(copy) = copy_of(state, dir, p, sender, &uid).await? else {
694 return Ok(Some(NO_AUTHORITY));
695 };
696 if let Some(next) = itip::receive(copy.as_ref().map(|(_, _, c)| c), m) {
697 let data = render::write(&next).into_bytes();
698 let etag = etag_of(&data);
699 let (collection_id, name, schedule_tag) = match copy {
700 // Only the others' answers changed: the attendee's pending edit
701 // may still go through (RFC 6638, 3.2.10).
702 Some((id, obj, _)) => (
703 id,
704 obj.name,
705 if m.quiet {
706 obj.schedule_tag
707 } else {
708 Some(etag.clone())
709 },
710 ),
711 None => match state.db.pim_calendar_for(p.id, &component).await? {
712 Some(c) => (
713 c.id,
714 object_name(&uid, PimKind::Calendar),
715 Some(etag.clone()),
716 ),
717 None => return Ok(Some(REFUSED)),
718 },
719 };
720 ops.push(PimOp::Put {
721 collection_id,
722 obj: PimObject {
723 name,
724 uid,
725 component: component.clone(),
726 etag,
727 schedule_tag,
728 ..Default::default()
729 },
730 data,
731 });
732 }
733 if !m.quiet {
734 ops.push(inbox(p, m, &component));
735 }
736 Ok(Some(DELIVERED))
737}
738
739/// An attendee's REPLY: applied to the organizer's object, passed on to the
740/// other attendees, and left in the organizer's inbox. Returns the delivery
741/// status for the attendee's copy.
742async fn reply_to(
743 state: &AppState,
744 dir: &Directory,
745 attendee: &PimPrincipal,
746 m: &Message,
747 ops: &mut Vec<PimOp>,
748) -> Result<&'static str, ApiError> {
749 let organizer = match dir.resolve(&m.to) {
750 Recipient::Local(p) => p,
751 Recipient::Unknown => return Ok(INVALID_USER),
752 Recipient::External => return Ok(NO_ROUTE),
753 };
754 let Some((uid, component)) = identity(&m.cal) else {
755 return Ok(REFUSED);
756 };
757 // RFC 6638, 4.2: a reply to an object the organizer no longer has is
758 // ignored.
759 let Some((collection_id, obj, data)) = state.db.pim_find_uid(organizer.id, &uid).await? else {
760 return Ok(NO_ROUTE);
761 };
762 let Some(before) = render::parse(&String::from_utf8_lossy(&data)) else {
763 return Ok(NO_ROUTE);
764 };
765 // A UID alone proves nothing: only the organizer's own object takes it.
766 if !matches!(
767 itip::role(&before, &dir.is(organizer.id)),
768 Ok(Role::Organizer)
769 ) {
770 return Ok(NO_AUTHORITY);
771 }
772 let replier = dir.is(attendee.id);
773 if !matches!(itip::role(&before, &replier), Ok(Role::Attendee)) {
774 return Ok(NO_AUTHORITY);
775 }
776 let mut after = before.clone();
777 let applied = itip::apply_reply(&mut after, &m.cal, &replier);
778 if applied.changed {
779 let data = render::write(&after).into_bytes();
780 ops.push(PimOp::Put {
781 collection_id,
782 obj: PimObject {
783 etag: etag_of(&data),
784 ..obj
785 },
786 data,
787 });
788 // The others learn the new answer without a new Schedule-Tag.
789 let organizes = dir.is(organizer.id);
790 let mut sent = Sent::new();
791 for mut other in itip::messages(Some(&before), Some(&after), &organizes, &[], Utc::now()) {
792 if other.method == Method::Request && !replier(&other.to) {
793 other.quiet = true;
794 deliver(state, dir, organizer, &other, ops, &mut sent).await?;
795 }
796 }
797 }
798 ops.push(inbox(organizer, m, &component));
799 Ok(match applied.dropped {
800 0 => DELIVERED,
801 _ => UNDELIVERED,
802 })
803}
804
805/// Whether `copy` is `p`'s attendee copy of a meeting `organizer` runs. A
806/// message may change only that: anyone can pick any UID.
807fn attends(dir: &Directory, copy: &ICalendar, p: &PimPrincipal, organizer: &PimPrincipal) -> bool {
808 matches!(itip::role(copy, &dir.is(p.id)), Ok(Role::Attendee))
809 && itip::organizer(copy).is_some_and(dir.is(organizer.id))
810}
811
812/// `p`'s copy of the meeting with `uid` and where it is stored. `Err` if
813/// `p` holds that UID in an object the message may not touch.
814async fn copy_of(
815 state: &AppState,
816 dir: &Directory,
817 p: &PimPrincipal,
818 organizer: &PimPrincipal,
819 uid: &str,
820) -> Result<Result<Option<(i64, PimObject, ICalendar)>, ()>, ApiError> {
821 let Some((id, obj, data)) = state.db.pim_find_uid(p.id, uid).await? else {
822 return Ok(Ok(None));
823 };
824 Ok(match render::parse(&String::from_utf8_lossy(&data)) {
825 Some(c) if attends(dir, &c, p, organizer) => Ok(Some((id, obj, c))),
826 _ => Err(()),
827 })
828}
829
830async fn ensure(state: &AppState, p: &PimPrincipal) -> Result<(), ApiError> {
831 match p.kind {
832 UserType::Individual => state.db.pim_ensure_defaults(p.id).await?,
833 _ => state.db.pim_ensure_inbox(p.id).await?,
834 }
835 Ok(())
836}
837
838fn inbox(p: &PimPrincipal, m: &Message, component: &str) -> PimOp {
839 let data = render::write(&m.cal).into_bytes();
840 let stamp = Utc::now().timestamp_nanos_opt().unwrap_or_default();
841 let seed = format!(
842 "{}\n{}\n{stamp}\n{:?}",
843 m.to,
844 String::from_utf8_lossy(&data),
845 m.method
846 );
847 let name = format!("{}.ics", &crate::hex(&Sha256::digest(seed))[..32]);
848 PimOp::Inbox {
849 principal_id: p.id,
850 obj: PimObject {
851 // Inbox messages share UIDs, and the store keeps UIDs unique.
852 uid: name.clone(),
853 name,
854 component: component.to_string(),
855 etag: etag_of(&data),
856 ..Default::default()
857 },
858 data,
859 }
860}
861
862/// UID and component type of a scheduling message or object.
863fn identity(cal: &ICalendar) -> Option<(String, String)> {
864 let c = cal.components.iter().find(|c| {
865 matches!(
866 c.component_type,
867 ICalendarComponentType::VEvent
868 | ICalendarComponentType::VTodo
869 | ICalendarComponentType::VJournal
870 )
871 })?;
872 Some((c.uid()?.to_string(), c.component_type.as_str().to_string()))
873}
874
875#[cfg(test)]
876mod tests {
877 use super::*;
878
879 #[test]
880 fn a_rule_running_on_has_not_ended_and_costs_nothing() {
881 let body = |rule: &str| {
882 format!(
883 "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//t//EN\r\nBEGIN:VEVENT\r\nUID:x\r\n\
884 DTSTAMP:20200101T000000Z\r\nDTSTART:20200101T100000Z\r\n{rule}END:VEVENT\r\nEND:VCALENDAR\r\n"
885 )
886 };
887 let now = Utc::now();
888 let started = std::time::Instant::now();
889 let on = body("RRULE:FREQ=MINUTELY;UNTIL=99991231T000000Z\r\n");
890 assert!(!ended(on.as_bytes(), None, now));
891 assert!(started.elapsed() < std::time::Duration::from_millis(200));
892 let over = body("RRULE:FREQ=DAILY;UNTIL=20200110T000000Z\r\n");
893 assert!(ended(over.as_bytes(), None, now));
894 }
895}
896