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 chrono::{DateTime, Utc};
12use percent_encoding::percent_decode_str;
13use pimdav::calcard::icalendar::{ICalendar, ICalendarComponentType};
14use pimdav::filter::TimeRange;
15use pimdav::freebusy::{self, Period};
16use pimdav::itip::{self, Message, Method, Role};
17use pimdav::principal::UserType;
18use pimdav::xml::{CALDAV, el, hrefs, with_children};
19use pimdav::zone::{self, Zone};
20use sha2::{Digest, Sha256};
21use tokio::sync::Mutex;
22use xmltree::Element;
23
24use super::pim::{
25 INBOX, MAIL_DOMAIN, OUTBOX, collection_href, etag_of, need_privilege, principal_name,
26 principal_uuid, seg,
27};
28use crate::db::{PimKind, PimObject, PimOp, PimPrincipal};
29use crate::error::{ApiError, AppState};
30
31/// Held from reading a calendar object to committing the change, so that a
32/// change and the writes it causes see a consistent store.
33// ponytail: one lock for every object write. Per-UID locks if write
34// throughput ever matters.
35pub(crate) static LOCK: Mutex<()> = Mutex::const_new(());
36
37/// The delivery status codes of RFC 6638, 3.2.9.
38const DELIVERED: &str = "1.2";
39/// An address in this server's domains that names no one.
40const INVALID_USER: &str = "3.7";
41/// An address outside this server: there is no iMIP to reach it.
42const NO_ROUTE: &str = "5.2";
43/// The recipient has no calendar for the component.
44const REFUSED: &str = "5.3";
45
46/// Who writes into a calendar, as far as scheduling cares.
47pub(crate) struct Writer<'a> {
48 pub owner: &'a PimPrincipal,
49 /// May send messages as the owner (RFC 6638 `schedule-send`).
50 pub may_schedule: bool,
51 /// The writer's address when it is not the owner, for SENT-BY.
52 pub sent_by: Option<String>,
53}
54
55impl Writer<'_> {
56 /// The owner itself.
57 pub(crate) fn owner(owner: &PimPrincipal) -> Writer<'_> {
58 Writer {
59 owner,
60 may_schedule: true,
61 sent_by: None,
62 }
63 }
64
65 /// 403 `need-privileges` on the owner's outbox.
66 fn refused(&self, privilege: &str) -> Element {
67 let outbox = collection_href(&self.owner.name, PimKind::Calendar, OUTBOX, None);
68 need_privilege(&outbox, CALDAV, privilege)
69 }
70}
71
72/// Every principal, for mapping calendar user addresses.
73pub(crate) struct Directory(Vec<PimPrincipal>);
74
75enum Recipient<'a> {
76 Local(&'a PimPrincipal),
77 Unknown,
78 External,
79}
80
81fn found(p: Option<&PimPrincipal>) -> Recipient<'_> {
82 match p {
83 Some(p) => Recipient::Local(p),
84 None => Recipient::Unknown,
85 }
86}
87
88impl Directory {
89 pub(crate) async fn load(state: &AppState) -> Result<Self, ApiError> {
90 Ok(Directory(state.db.pim_principals().await?))
91 }
92
93 pub(crate) fn get(&self, id: i64) -> Option<&PimPrincipal> {
94 self.0.iter().find(|p| p.id == id)
95 }
96
97 /// The forms `calendar-user-address-set` lists: the mailto address, the
98 /// principal URL and the `urn:uuid:`. Compared without case.
99 fn resolve(&self, addr: &str) -> Recipient<'_> {
100 let addr = addr.trim();
101 let lower = addr.to_ascii_lowercase();
102 if let Some(rest) = lower.strip_prefix("mailto:") {
103 let Some((local, domain)) = rest.rsplit_once('@') else {
104 return Recipient::External;
105 };
106 let kind = match domain.strip_suffix(MAIL_DOMAIN) {
107 Some("") => UserType::Individual,
108 Some("rooms.") => UserType::Room,
109 Some("resources.") => UserType::Resource,
110 _ => return Recipient::External,
111 };
112 let name = percent_decode_str(local).decode_utf8_lossy();
113 return found(
114 self.0
115 .iter()
116 .find(|p| p.kind == kind && p.name.eq_ignore_ascii_case(&name)),
117 );
118 }
119 if let Some(uuid) = lower.strip_prefix("urn:uuid:") {
120 return found(self.0.iter().find(|p| principal_uuid(p.id) == uuid));
121 }
122 match principal_name(addr) {
123 Some(name) => found(self.0.iter().find(|p| p.name.eq_ignore_ascii_case(&name))),
124 None if lower.starts_with('/') || lower.starts_with("http") => Recipient::Unknown,
125 None => Recipient::External,
126 }
127 }
128
129 /// Whether an address names principal `id`.
130 pub(crate) fn is(&self, id: i64) -> impl Fn(&str) -> bool + '_ {
131 move |a: &str| matches!(self.resolve(a), Recipient::Local(p) if p.id == id)
132 }
133}
134
135/// What a PUT of a calendar object stores, and what else it writes.
136pub(crate) struct Stored {
137 pub data: Vec<u8>,
138 /// Whether `data` differs from the request body.
139 pub changed: bool,
140 pub schedule_tag: Option<String>,
141 pub ops: Vec<PimOp>,
142}
143
144/// A PUT of `body` over `old` into collection `at.0` under the name `at.1`.
145/// `Err` names a failed scheduling precondition.
146pub(crate) async fn put(
147 state: &AppState,
148 dir: &Directory,
149 w: &Writer<'_>,
150 at: (i64, &str),
151 old: Option<&[u8]>,
152 body: &[u8],
153) -> Result<Result<Stored, Element>, ApiError> {
154 let parse = |b: &[u8]| ICalendar::parse(String::from_utf8_lossy(b).as_ref()).ok();
155 let Some(sent) = parse(body) else {
156 return Ok(Ok(unchanged(body, None)));
157 };
158 let owner = w.owner;
159 let owns = dir.is(owner.id);
160 let role = match itip::role(&sent, &owns) {
161 Ok(r) => r,
162 Err(refused) => return Ok(Err(refused.condition())),
163 };
164 if role != Role::None
165 && let Some(holder) = elsewhere(state, owner, &sent, at).await?
166 {
167 return Ok(Err(holder));
168 }
169 let old = old.and_then(parse);
170 let old_role = old.as_ref().and_then(|o| itip::role(o, &owns).ok());
171 let now = Utc::now();
172 let mut ops = Vec::new();
173
174 let stored = match (role, old_role) {
175 (Role::Organizer, _) => {
176 let old = old.as_ref().filter(|_| old_role == Some(Role::Organizer));
177 let (mut store, force) = itip::prepare(old, &sent, &owns);
178 let mut messages = itip::messages(old, Some(&store), &owns, &force, now);
179 if !messages.is_empty() {
180 if !w.may_schedule {
181 return Ok(Err(w.refused("schedule-send-invite")));
182 }
183 itip::stamp_sender(&mut store, &owns, w.sent_by.as_deref());
184 messages = itip::messages(old, Some(&store), &owns, &force, now);
185 }
186 // Rooms answer first, so the others' copies carry their answers.
187 if answer_rooms(state, dir, owner, &mut store, &messages, &mut ops, now).await? {
188 messages = itip::messages(old, Some(&store), &owns, &force, now);
189 }
190 for m in &messages {
191 if let Some(status) = deliver(state, dir, owner, m, &mut ops).await? {
192 itip::set_attendee_status(&mut store, &m.to, status);
193 }
194 }
195 store
196 }
197 (Role::Attendee, Some(Role::Attendee)) => {
198 let old = old.as_ref().expect("an attendee role needs the old object");
199 let (mut store, reply) = match itip::attend(old, sent.clone(), &owns, now) {
200 Ok(v) => v,
201 Err(refused) => return Ok(Err(refused.condition())),
202 };
203 if let Some(mut reply) = reply {
204 if !w.may_schedule {
205 return Ok(Err(w.refused("schedule-send-reply")));
206 }
207 itip::stamp_sender(&mut store, &owns, w.sent_by.as_deref());
208 itip::stamp_sender(&mut reply.cal, &owns, w.sent_by.as_deref());
209 let status = reply_to(state, dir, owner, &reply, &mut ops).await?;
210 itip::set_organizer_status(&mut store, status);
211 }
212 store
213 }
214 // No longer a scheduling object, or a copy the attendee brings in
215 // itself (RFC 6638, 3.2.2.2): stored as sent.
216 (_, previous) => {
217 if let Some(old) = &old {
218 match removed(state, dir, w, old, previous, true).await? {
219 Ok(more) => ops.extend(more),
220 Err(refused) => return Ok(Err(refused)),
221 }
222 }
223 let tag = (role != Role::None).then(|| etag_of(body));
224 return Ok(Ok(Stored {
225 ops,
226 ..unchanged(body, tag)
227 }));
228 }
229 };
230 let changed = stored != sent;
231 let data = match changed {
232 true => stored.to_string().into_bytes(),
233 false => body.to_vec(),
234 };
235 Ok(Ok(Stored {
236 schedule_tag: Some(etag_of(&data)),
237 data,
238 changed,
239 ops,
240 }))
241}
242
243/// The Schedule-Tag an import stores with `body`, `None` for an object that
244/// schedules nothing. An import sends no messages: the object is stored as
245/// sent. `Err` names the precondition that refuses it.
246pub(crate) async fn import_tag(
247 state: &AppState,
248 dir: &Directory,
249 owner: &PimPrincipal,
250 at: (i64, &str),
251 body: &[u8],
252) -> Result<Result<Option<String>, Element>, ApiError> {
253 let Ok(cal) = ICalendar::parse(String::from_utf8_lossy(body).as_ref()) else {
254 return Ok(Ok(None));
255 };
256 match itip::role(&cal, &dir.is(owner.id)) {
257 Err(refused) => Ok(Err(refused.condition())),
258 Ok(Role::None) => Ok(Ok(None)),
259 Ok(_) => Ok(match elsewhere(state, owner, &cal, at).await? {
260 Some(holder) => Err(holder),
261 None => Ok(Some(etag_of(body))),
262 }),
263 }
264}
265
266/// The resource name the server picks for an object it creates.
267pub(crate) fn object_name(uid: &str, kind: PimKind) -> String {
268 let ext = match kind {
269 PimKind::Calendar => "ics",
270 PimKind::AddressBook => "vcf",
271 };
272 format!("{}.{ext}", &crate::hex(&Sha256::digest(uid))[..32])
273}
274
275fn unchanged(body: &[u8], schedule_tag: Option<String>) -> Stored {
276 Stored {
277 data: body.to_vec(),
278 changed: false,
279 schedule_tag,
280 ops: Vec::new(),
281 }
282}
283
284/// The writes a DELETE of `old` causes. `reply` is false for
285/// `Schedule-Reply: F` (RFC 6638, 8.1). `Err` names a lacking privilege.
286pub(crate) async fn delete(
287 state: &AppState,
288 dir: &Directory,
289 w: &Writer<'_>,
290 old: &[u8],
291 reply: bool,
292) -> Result<Result<Vec<PimOp>, Element>, ApiError> {
293 let Ok(old) = ICalendar::parse(String::from_utf8_lossy(old).as_ref()) else {
294 return Ok(Ok(Vec::new()));
295 };
296 let role = itip::role(&old, &dir.is(w.owner.id)).ok();
297 removed(state, dir, w, &old, role, reply).await
298}
299
300/// An organizer object going away cancels; an attendee copy declines.
301async fn removed(
302 state: &AppState,
303 dir: &Directory,
304 w: &Writer<'_>,
305 old: &ICalendar,
306 role: Option<Role>,
307 reply: bool,
308) -> Result<Result<Vec<PimOp>, Element>, ApiError> {
309 let owner = w.owner;
310 let owns = dir.is(owner.id);
311 let now = Utc::now();
312 let mut old = old.clone();
313 itip::stamp_sender(&mut old, &owns, w.sent_by.as_deref());
314 let mut ops = Vec::new();
315 match role {
316 Some(Role::Organizer) => {
317 let (_, messages) = itip::organize(Some(&old), None, &owns, now);
318 if !messages.is_empty() && !w.may_schedule {
319 return Ok(Err(w.refused("schedule-send-invite")));
320 }
321 for m in &messages {
322 deliver(state, dir, owner, m, &mut ops).await?;
323 }
324 }
325 Some(Role::Attendee) if reply => {
326 if let Some(m) = itip::decline(&old, &owns, now) {
327 if !w.may_schedule {
328 return Ok(Err(w.refused("schedule-send-reply")));
329 }
330 reply_to(state, dir, owner, &m, &mut ops).await?;
331 }
332 }
333 _ => {}
334 }
335 Ok(Ok(ops))
336}
337
338/// The resource of the owner that already schedules this UID elsewhere:
339/// RFC 6638 allows one per UID (3.2.4.1).
340async fn elsewhere(
341 state: &AppState,
342 owner: &PimPrincipal,
343 cal: &ICalendar,
344 (collection_id, name): (i64, &str),
345) -> Result<Option<Element>, ApiError> {
346 let Some((uid, _)) = identity(cal) else {
347 return Ok(None);
348 };
349 let Some((holder_id, holder, _)) = state.db.pim_find_uid(owner.id, &uid).await? else {
350 return Ok(None);
351 };
352 if holder_id == collection_id && holder.name == name {
353 return Ok(None);
354 }
355 let slug = match state.db.pim_collection_by_id(holder_id).await? {
356 Some((_, _, c)) => c.slug,
357 None => return Ok(None),
358 };
359 let href = collection_href(&owner.name, PimKind::Calendar, &slug, None) + &seg(&holder.name);
360 Ok(Some(with_children(
361 el(CALDAV, "unique-scheduling-object-resource"),
362 hrefs([href.as_str()]),
363 )))
364}
365
366/// Rooms and resources answer their invitations at once: accepted where
367/// free, declined where their bookings overlap. The answers go into the
368/// organizer's `store` and inbox. Returns whether any room answered.
369async fn answer_rooms(
370 state: &AppState,
371 dir: &Directory,
372 organizer: &PimPrincipal,
373 store: &mut ICalendar,
374 messages: &[Message],
375 ops: &mut Vec<PimOp>,
376 now: DateTime<Utc>,
377) -> Result<bool, ApiError> {
378 let mut answered = false;
379 for m in messages
380 .iter()
381 .filter(|m| m.method == Method::Request && !m.quiet)
382 {
383 let Recipient::Local(room) = dir.resolve(&m.to) else {
384 continue;
385 };
386 let Some((uid, component)) = identity(&m.cal) else {
387 continue;
388 };
389 if room.kind == UserType::Individual {
390 continue;
391 }
392 let Some(calendar) = state.db.pim_calendar_for(room.id, &component).await? else {
393 continue;
394 };
395 let current = state
396 .db
397 .pim_find_uid(room.id, &uid)
398 .await?
399 .and_then(|(_, _, d)| ICalendar::parse(String::from_utf8_lossy(&d).as_ref()).ok());
400 let Some(received) = itip::receive(current.as_ref(), m) else {
401 continue;
402 };
403 let is_room = dir.is(room.id);
404 let window = now..now + itip::answer_horizon(&received);
405 let taken = busy_of(state, dir, room, &window, Some(&uid)).await?;
406 let floating = floating_of(calendar.timezone.as_deref());
407 let answer = itip::auto_answer(&received, &is_room, &taken, &window, &floating);
408 let Ok((_, Some(reply))) = itip::attend(&received, answer, &is_room, now) else {
409 continue;
410 };
411 answered |= itip::apply_reply(store, &reply.cal, &is_room);
412 ops.push(inbox(organizer, &reply, &component));
413 }
414 Ok(answered)
415}
416
417/// The busy time a principal shows to scheduling: its opaque calendars that
418/// take events, never the inbox. Objects with UID `skip` do not count.
419// ponytail: reads every object of those calendars per call. Keep busy
420// periods in a table if principals grow large calendars.
421pub(crate) async fn busy_of(
422 state: &AppState,
423 dir: &Directory,
424 p: &PimPrincipal,
425 range: &TimeRange,
426 skip: Option<&str>,
427) -> Result<Vec<Period>, ApiError> {
428 let me = dir.is(p.id);
429 let mut busy = Vec::new();
430 for c in state.db.pim_collections(p.id, PimKind::Calendar).await? {
431 if c.slug == INBOX || c.transparent || !c.components.split(',').any(|x| x == "VEVENT") {
432 continue;
433 }
434 let floating = floating_of(c.timezone.as_deref());
435 for (o, data) in state.db.pim_objects_with_data(c.id).await? {
436 if skip.is_some_and(|u| u == o.uid) {
437 continue;
438 }
439 if let Ok(cal) = ICalendar::parse(String::from_utf8_lossy(&data).as_ref()) {
440 busy.extend(freebusy::busy(&cal, range, &floating, Some(&me)));
441 }
442 }
443 }
444 Ok(freebusy::merge(busy))
445}
446
447fn floating_of(timezone: Option<&str>) -> Zone {
448 timezone.and_then(zone::from_vtimezone).unwrap_or(Zone::Utc)
449}
450
451/// The answers to a free-busy request to an outbox (RFC 6638, 5.2): per
452/// recipient its address, the REQUEST-STATUS and the VFREEBUSY reply.
453pub(crate) async fn free_busy(
454 state: &AppState,
455 dir: &Directory,
456 req: &freebusy::Request,
457) -> Result<Vec<(String, &'static str, Option<String>)>, ApiError> {
458 let now = Utc::now();
459 let mut out = Vec::new();
460 for to in &req.attendees {
461 let (status, data) = match dir.resolve(to) {
462 Recipient::Local(p) => {
463 let busy = busy_of(state, dir, p, &req.range, None).await?;
464 ("2.0;Success", Some(freebusy::reply(&busy, req, to, now)))
465 }
466 Recipient::Unknown => ("3.7;Invalid calendar user", None),
467 Recipient::External => ("5.2;Invalid calendar service", None),
468 };
469 out.push((to.clone(), status, data));
470 }
471 Ok(out)
472}
473
474/// A REQUEST or CANCEL from `sender` into the recipient's calendar and
475/// inbox. Returns the delivery status, `None` for the sender itself.
476async fn deliver(
477 state: &AppState,
478 dir: &Directory,
479 sender: &PimPrincipal,
480 m: &Message,
481 ops: &mut Vec<PimOp>,
482) -> Result<Option<&'static str>, ApiError> {
483 let p = match dir.resolve(&m.to) {
484 Recipient::Local(p) if p.id == sender.id => return Ok(None),
485 Recipient::Local(p) => p,
486 Recipient::Unknown => return Ok(Some(INVALID_USER)),
487 Recipient::External => return Ok(Some(NO_ROUTE)),
488 };
489 ensure(state, p).await?;
490 let Some((uid, component)) = identity(&m.cal) else {
491 return Ok(Some(REFUSED));
492 };
493 let copy = state.db.pim_find_uid(p.id, &uid).await?;
494 let current = copy
495 .as_ref()
496 .and_then(|(_, _, d)| ICalendar::parse(String::from_utf8_lossy(d).as_ref()).ok());
497 if let Some(next) = itip::receive(current.as_ref(), m) {
498 let data = next.to_string().into_bytes();
499 let etag = etag_of(&data);
500 let (collection_id, name, schedule_tag) = match copy {
501 // Only the others' answers changed: the attendee's pending edit
502 // may still go through (RFC 6638, 3.2.10).
503 Some((id, obj, _)) => (
504 id,
505 obj.name,
506 if m.quiet {
507 obj.schedule_tag
508 } else {
509 Some(etag.clone())
510 },
511 ),
512 None => match state.db.pim_calendar_for(p.id, &component).await? {
513 Some(c) => (
514 c.id,
515 object_name(&uid, PimKind::Calendar),
516 Some(etag.clone()),
517 ),
518 None => return Ok(Some(REFUSED)),
519 },
520 };
521 ops.push(PimOp::Put {
522 collection_id,
523 obj: PimObject {
524 name,
525 uid,
526 component: component.clone(),
527 etag,
528 schedule_tag,
529 ..Default::default()
530 },
531 data,
532 });
533 }
534 if !m.quiet {
535 ops.push(inbox(p, m, &component));
536 }
537 Ok(Some(DELIVERED))
538}
539
540/// An attendee's REPLY: applied to the organizer's object, passed on to the
541/// other attendees, and left in the organizer's inbox. Returns the delivery
542/// status for the attendee's copy.
543async fn reply_to(
544 state: &AppState,
545 dir: &Directory,
546 attendee: &PimPrincipal,
547 m: &Message,
548 ops: &mut Vec<PimOp>,
549) -> Result<&'static str, ApiError> {
550 let organizer = match dir.resolve(&m.to) {
551 Recipient::Local(p) => p,
552 Recipient::Unknown => return Ok(INVALID_USER),
553 Recipient::External => return Ok(NO_ROUTE),
554 };
555 let Some((uid, component)) = identity(&m.cal) else {
556 return Ok(REFUSED);
557 };
558 // RFC 6638, 4.2: a reply to an object the organizer no longer has is
559 // ignored.
560 let Some((collection_id, obj, data)) = state.db.pim_find_uid(organizer.id, &uid).await? else {
561 return Ok(NO_ROUTE);
562 };
563 let Ok(before) = ICalendar::parse(String::from_utf8_lossy(&data).as_ref()) else {
564 return Ok(NO_ROUTE);
565 };
566 let mut after = before.clone();
567 let replier = dir.is(attendee.id);
568 if itip::apply_reply(&mut after, &m.cal, &replier) {
569 let data = after.to_string().into_bytes();
570 ops.push(PimOp::Put {
571 collection_id,
572 obj: PimObject {
573 etag: etag_of(&data),
574 ..obj
575 },
576 data,
577 });
578 // The others learn the new answer without a new Schedule-Tag.
579 let organizes = dir.is(organizer.id);
580 for mut other in itip::messages(Some(&before), Some(&after), &organizes, &[], Utc::now()) {
581 if other.method == Method::Request && !replier(&other.to) {
582 other.quiet = true;
583 deliver(state, dir, organizer, &other, ops).await?;
584 }
585 }
586 }
587 ops.push(inbox(organizer, m, &component));
588 Ok(DELIVERED)
589}
590
591async fn ensure(state: &AppState, p: &PimPrincipal) -> Result<(), ApiError> {
592 match p.kind {
593 UserType::Individual => state.db.pim_ensure_defaults(p.id).await?,
594 _ => state.db.pim_ensure_inbox(p.id).await?,
595 }
596 Ok(())
597}
598
599fn inbox(p: &PimPrincipal, m: &Message, component: &str) -> PimOp {
600 let data = m.cal.to_string().into_bytes();
601 let stamp = Utc::now().timestamp_nanos_opt().unwrap_or_default();
602 let seed = format!(
603 "{}\n{}\n{stamp}\n{:?}",
604 m.to,
605 String::from_utf8_lossy(&data),
606 m.method
607 );
608 let name = format!("{}.ics", &crate::hex(&Sha256::digest(seed))[..32]);
609 PimOp::Inbox {
610 principal_id: p.id,
611 obj: PimObject {
612 // Inbox messages share UIDs, and the store keeps UIDs unique.
613 uid: name.clone(),
614 name,
615 component: component.to_string(),
616 etag: etag_of(&data),
617 ..Default::default()
618 },
619 data,
620 }
621}
622
623/// UID and component type of a scheduling message or object.
624fn identity(cal: &ICalendar) -> Option<(String, String)> {
625 let c = cal.components.iter().find(|c| {
626 matches!(
627 c.component_type,
628 ICalendarComponentType::VEvent
629 | ICalendarComponentType::VTodo
630 | ICalendarComponentType::VJournal
631 )
632 })?;
633 Some((c.uid()?.to_string(), c.component_type.as_str().to_string()))
634}
635