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
243fn unchanged(body: &[u8], schedule_tag: Option<String>) -> Stored {
244 Stored {
245 data: body.to_vec(),
246 changed: false,
247 schedule_tag,
248 ops: Vec::new(),
249 }
250}
251
252/// The writes a DELETE of `old` causes. `reply` is false for
253/// `Schedule-Reply: F` (RFC 6638, 8.1). `Err` names a lacking privilege.
254pub(crate) async fn delete(
255 state: &AppState,
256 dir: &Directory,
257 w: &Writer<'_>,
258 old: &[u8],
259 reply: bool,
260) -> Result<Result<Vec<PimOp>, Element>, ApiError> {
261 let Ok(old) = ICalendar::parse(String::from_utf8_lossy(old).as_ref()) else {
262 return Ok(Ok(Vec::new()));
263 };
264 let role = itip::role(&old, &dir.is(w.owner.id)).ok();
265 removed(state, dir, w, &old, role, reply).await
266}
267
268/// An organizer object going away cancels; an attendee copy declines.
269async fn removed(
270 state: &AppState,
271 dir: &Directory,
272 w: &Writer<'_>,
273 old: &ICalendar,
274 role: Option<Role>,
275 reply: bool,
276) -> Result<Result<Vec<PimOp>, Element>, ApiError> {
277 let owner = w.owner;
278 let owns = dir.is(owner.id);
279 let now = Utc::now();
280 let mut old = old.clone();
281 itip::stamp_sender(&mut old, &owns, w.sent_by.as_deref());
282 let mut ops = Vec::new();
283 match role {
284 Some(Role::Organizer) => {
285 let (_, messages) = itip::organize(Some(&old), None, &owns, now);
286 if !messages.is_empty() && !w.may_schedule {
287 return Ok(Err(w.refused("schedule-send-invite")));
288 }
289 for m in &messages {
290 deliver(state, dir, owner, m, &mut ops).await?;
291 }
292 }
293 Some(Role::Attendee) if reply => {
294 if let Some(m) = itip::decline(&old, &owns, now) {
295 if !w.may_schedule {
296 return Ok(Err(w.refused("schedule-send-reply")));
297 }
298 reply_to(state, dir, owner, &m, &mut ops).await?;
299 }
300 }
301 _ => {}
302 }
303 Ok(Ok(ops))
304}
305
306/// The resource of the owner that already schedules this UID elsewhere:
307/// RFC 6638 allows one per UID (3.2.4.1).
308async fn elsewhere(
309 state: &AppState,
310 owner: &PimPrincipal,
311 cal: &ICalendar,
312 (collection_id, name): (i64, &str),
313) -> Result<Option<Element>, ApiError> {
314 let Some((uid, _)) = identity(cal) else {
315 return Ok(None);
316 };
317 let Some((holder_id, holder, _)) = state.db.pim_find_uid(owner.id, &uid).await? else {
318 return Ok(None);
319 };
320 if holder_id == collection_id && holder.name == name {
321 return Ok(None);
322 }
323 let slug = match state.db.pim_collection_by_id(holder_id).await? {
324 Some((_, _, c)) => c.slug,
325 None => return Ok(None),
326 };
327 let href = collection_href(&owner.name, PimKind::Calendar, &slug, None) + &seg(&holder.name);
328 Ok(Some(with_children(
329 el(CALDAV, "unique-scheduling-object-resource"),
330 hrefs([href.as_str()]),
331 )))
332}
333
334/// Rooms and resources answer their invitations at once: accepted where
335/// free, declined where their bookings overlap. The answers go into the
336/// organizer's `store` and inbox. Returns whether any room answered.
337async fn answer_rooms(
338 state: &AppState,
339 dir: &Directory,
340 organizer: &PimPrincipal,
341 store: &mut ICalendar,
342 messages: &[Message],
343 ops: &mut Vec<PimOp>,
344 now: DateTime<Utc>,
345) -> Result<bool, ApiError> {
346 let mut answered = false;
347 for m in messages
348 .iter()
349 .filter(|m| m.method == Method::Request && !m.quiet)
350 {
351 let Recipient::Local(room) = dir.resolve(&m.to) else {
352 continue;
353 };
354 let Some((uid, component)) = identity(&m.cal) else {
355 continue;
356 };
357 if room.kind == UserType::Individual {
358 continue;
359 }
360 let Some(calendar) = state.db.pim_calendar_for(room.id, &component).await? else {
361 continue;
362 };
363 let current = state
364 .db
365 .pim_find_uid(room.id, &uid)
366 .await?
367 .and_then(|(_, _, d)| ICalendar::parse(String::from_utf8_lossy(&d).as_ref()).ok());
368 let Some(received) = itip::receive(current.as_ref(), m) else {
369 continue;
370 };
371 let is_room = dir.is(room.id);
372 let window = now..now + itip::answer_horizon(&received);
373 let taken = busy_of(state, dir, room, &window, Some(&uid)).await?;
374 let floating = floating_of(calendar.timezone.as_deref());
375 let answer = itip::auto_answer(&received, &is_room, &taken, &window, &floating);
376 let Ok((_, Some(reply))) = itip::attend(&received, answer, &is_room, now) else {
377 continue;
378 };
379 answered |= itip::apply_reply(store, &reply.cal, &is_room);
380 ops.push(inbox(organizer, &reply, &component));
381 }
382 Ok(answered)
383}
384
385/// The busy time a principal shows to scheduling: its opaque calendars that
386/// take events, never the inbox. Objects with UID `skip` do not count.
387// ponytail: reads every object of those calendars per call. Keep busy
388// periods in a table if principals grow large calendars.
389pub(crate) async fn busy_of(
390 state: &AppState,
391 dir: &Directory,
392 p: &PimPrincipal,
393 range: &TimeRange,
394 skip: Option<&str>,
395) -> Result<Vec<Period>, ApiError> {
396 let me = dir.is(p.id);
397 let mut busy = Vec::new();
398 for c in state.db.pim_collections(p.id, PimKind::Calendar).await? {
399 if c.slug == INBOX || c.transparent || !c.components.split(',').any(|x| x == "VEVENT") {
400 continue;
401 }
402 let floating = floating_of(c.timezone.as_deref());
403 for (o, data) in state.db.pim_objects_with_data(c.id).await? {
404 if skip.is_some_and(|u| u == o.uid) {
405 continue;
406 }
407 if let Ok(cal) = ICalendar::parse(String::from_utf8_lossy(&data).as_ref()) {
408 busy.extend(freebusy::busy(&cal, range, &floating, Some(&me)));
409 }
410 }
411 }
412 Ok(freebusy::merge(busy))
413}
414
415fn floating_of(timezone: Option<&str>) -> Zone {
416 timezone.and_then(zone::from_vtimezone).unwrap_or(Zone::Utc)
417}
418
419/// The answers to a free-busy request to an outbox (RFC 6638, 5.2): per
420/// recipient its address, the REQUEST-STATUS and the VFREEBUSY reply.
421pub(crate) async fn free_busy(
422 state: &AppState,
423 dir: &Directory,
424 req: &freebusy::Request,
425) -> Result<Vec<(String, &'static str, Option<String>)>, ApiError> {
426 let now = Utc::now();
427 let mut out = Vec::new();
428 for to in &req.attendees {
429 let (status, data) = match dir.resolve(to) {
430 Recipient::Local(p) => {
431 let busy = busy_of(state, dir, p, &req.range, None).await?;
432 ("2.0;Success", Some(freebusy::reply(&busy, req, to, now)))
433 }
434 Recipient::Unknown => ("3.7;Invalid calendar user", None),
435 Recipient::External => ("5.2;Invalid calendar service", None),
436 };
437 out.push((to.clone(), status, data));
438 }
439 Ok(out)
440}
441
442/// A REQUEST or CANCEL from `sender` into the recipient's calendar and
443/// inbox. Returns the delivery status, `None` for the sender itself.
444async fn deliver(
445 state: &AppState,
446 dir: &Directory,
447 sender: &PimPrincipal,
448 m: &Message,
449 ops: &mut Vec<PimOp>,
450) -> Result<Option<&'static str>, ApiError> {
451 let p = match dir.resolve(&m.to) {
452 Recipient::Local(p) if p.id == sender.id => return Ok(None),
453 Recipient::Local(p) => p,
454 Recipient::Unknown => return Ok(Some(INVALID_USER)),
455 Recipient::External => return Ok(Some(NO_ROUTE)),
456 };
457 ensure(state, p).await?;
458 let Some((uid, component)) = identity(&m.cal) else {
459 return Ok(Some(REFUSED));
460 };
461 let copy = state.db.pim_find_uid(p.id, &uid).await?;
462 let current = copy
463 .as_ref()
464 .and_then(|(_, _, d)| ICalendar::parse(String::from_utf8_lossy(d).as_ref()).ok());
465 if let Some(next) = itip::receive(current.as_ref(), m) {
466 let data = next.to_string().into_bytes();
467 let etag = etag_of(&data);
468 let (collection_id, name, schedule_tag) = match copy {
469 // Only the others' answers changed: the attendee's pending edit
470 // may still go through (RFC 6638, 3.2.10).
471 Some((id, obj, _)) => (
472 id,
473 obj.name,
474 if m.quiet {
475 obj.schedule_tag
476 } else {
477 Some(etag.clone())
478 },
479 ),
480 None => match state.db.pim_calendar_for(p.id, &component).await? {
481 Some(c) => (
482 c.id,
483 format!("{}.ics", &crate::hex(&Sha256::digest(&uid))[..32]),
484 Some(etag.clone()),
485 ),
486 None => return Ok(Some(REFUSED)),
487 },
488 };
489 ops.push(PimOp::Put {
490 collection_id,
491 obj: PimObject {
492 name,
493 uid,
494 component: component.clone(),
495 etag,
496 schedule_tag,
497 ..Default::default()
498 },
499 data,
500 });
501 }
502 if !m.quiet {
503 ops.push(inbox(p, m, &component));
504 }
505 Ok(Some(DELIVERED))
506}
507
508/// An attendee's REPLY: applied to the organizer's object, passed on to the
509/// other attendees, and left in the organizer's inbox. Returns the delivery
510/// status for the attendee's copy.
511async fn reply_to(
512 state: &AppState,
513 dir: &Directory,
514 attendee: &PimPrincipal,
515 m: &Message,
516 ops: &mut Vec<PimOp>,
517) -> Result<&'static str, ApiError> {
518 let organizer = match dir.resolve(&m.to) {
519 Recipient::Local(p) => p,
520 Recipient::Unknown => return Ok(INVALID_USER),
521 Recipient::External => return Ok(NO_ROUTE),
522 };
523 let Some((uid, component)) = identity(&m.cal) else {
524 return Ok(REFUSED);
525 };
526 // RFC 6638, 4.2: a reply to an object the organizer no longer has is
527 // ignored.
528 let Some((collection_id, obj, data)) = state.db.pim_find_uid(organizer.id, &uid).await? else {
529 return Ok(NO_ROUTE);
530 };
531 let Ok(before) = ICalendar::parse(String::from_utf8_lossy(&data).as_ref()) else {
532 return Ok(NO_ROUTE);
533 };
534 let mut after = before.clone();
535 let replier = dir.is(attendee.id);
536 if itip::apply_reply(&mut after, &m.cal, &replier) {
537 let data = after.to_string().into_bytes();
538 ops.push(PimOp::Put {
539 collection_id,
540 obj: PimObject {
541 etag: etag_of(&data),
542 ..obj
543 },
544 data,
545 });
546 // The others learn the new answer without a new Schedule-Tag.
547 let organizes = dir.is(organizer.id);
548 for mut other in itip::messages(Some(&before), Some(&after), &organizes, &[], Utc::now()) {
549 if other.method == Method::Request && !replier(&other.to) {
550 other.quiet = true;
551 deliver(state, dir, organizer, &other, ops).await?;
552 }
553 }
554 }
555 ops.push(inbox(organizer, m, &component));
556 Ok(DELIVERED)
557}
558
559async fn ensure(state: &AppState, p: &PimPrincipal) -> Result<(), ApiError> {
560 match p.kind {
561 UserType::Individual => state.db.pim_ensure_defaults(p.id).await?,
562 _ => state.db.pim_ensure_inbox(p.id).await?,
563 }
564 Ok(())
565}
566
567fn inbox(p: &PimPrincipal, m: &Message, component: &str) -> PimOp {
568 let data = m.cal.to_string().into_bytes();
569 let stamp = Utc::now().timestamp_nanos_opt().unwrap_or_default();
570 let seed = format!(
571 "{}\n{}\n{stamp}\n{:?}",
572 m.to,
573 String::from_utf8_lossy(&data),
574 m.method
575 );
576 let name = format!("{}.ics", &crate::hex(&Sha256::digest(seed))[..32]);
577 PimOp::Inbox {
578 principal_id: p.id,
579 obj: PimObject {
580 // Inbox messages share UIDs, and the store keeps UIDs unique.
581 uid: name.clone(),
582 name,
583 component: component.to_string(),
584 etag: etag_of(&data),
585 ..Default::default()
586 },
587 data,
588 }
589}
590
591/// UID and component type of a scheduling message or object.
592fn identity(cal: &ICalendar) -> Option<(String, String)> {
593 let c = cal.components.iter().find(|c| {
594 matches!(
595 c.component_type,
596 ICalendarComponentType::VEvent
597 | ICalendarComponentType::VTodo
598 | ICalendarComponentType::VJournal
599 )
600 })?;
601 Some((c.uid()?.to_string(), c.component_type.as_str().to_string()))
602}
603