pim.rs
⎇
Raw
1//! CalDAV and CardDAV.
2//!
3//! URL layout under [`PIM`]:
4//!
5//! * `/principals/` and `/principals/{name}/`: accounts, rooms and resources
6//! * `/calendars/{name}/` and `/addressbooks/{name}/`, the homes
7//! * `/calendars/{name}/{collection}/` and `.../{collection}/{object}`, the
8//! same for address books
9//!
10//! A home also shows the collections lent to its account, as
11//! `shared-{collection id}`, and the address book home shows the generated
12//! system address book as `system`. The calendar home holds the scheduling
13//! `inbox` and `outbox`, and the generated `birthdays` calendar. A room's home
14//! holds its bookings.
15//!
16//! The protocol logic is `pimdav`'s. This module authenticates, maps URLs onto
17//! the store and assembles the responses.
18
19use std::collections::HashSet;
20use std::sync::Arc;
21
22use api_types::PIM;
23use axum::body::Body;
24use axum::extract::State;
25use axum::http::header::{ALLOW, CONTENT_TYPE, ETAG, LOCATION};
26use axum::http::{HeaderMap, Method, Request, Response, StatusCode};
27use axum::response::IntoResponse;
28use percent_encoding::{
29 AsciiSet, CONTROLS, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode,
30};
31use pimdav::calcard::icalendar::ICalendar;
32use pimdav::calcard::vcard::VCard;
33use pimdav::principal::{self, Principal, Search, UserType};
34use pimdav::render::{self, TooManyInstances};
35use pimdav::report::{self, Props, Refused, Report};
36use pimdav::xml::{
37 self, APPLE, CALDAV, CALSERVER, CARDDAV, DAV, Name, Propfind, Update, el, hrefs, with_attr,
38 with_children, with_text,
39};
40use pimdav::zone::{self, Zone};
41use pimdav::{contact, filter, freebusy, object};
42
43use super::common::blocking;
44use super::pim_schedule::{self, Directory, Stored, Writer};
45use sha2::{Digest, Sha256};
46use xmltree::Element;
47
48use crate::db::{
49 DeadProp, PimCollection, PimKind, PimObject, PimOp, PimPrincipal, PimShareMode, PimWrite,
50 Precondition, PropPlace, User,
51};
52use crate::error::{ApiError, AppState};
53
54/// Largest object a PUT may store. Contacts carry photos inline.
55pub(super) const MAX_RESOURCE_SIZE: usize = 10 * 1024 * 1024;
56
57const MAX_SLUG: usize = 255;
58pub(super) const MAX_COLLECTIONS: usize = 100;
59pub(super) const MAX_DISPLAYNAME: usize = 256;
60pub(super) const MAX_DESCRIPTION: usize = 1024;
61
62/// A trimmed name (`lines` false) or description within `max` characters.
63pub(super) fn valid_text(v: &str, max: usize, lines: bool) -> bool {
64 let v = v.trim();
65 v.chars().count() <= max
66 && !v
67 .chars()
68 .any(|c| c.is_control() && !(lines && matches!(c, '\n' | '\r' | '\t')))
69}
70
71/// Largest XML request body.
72const MAX_XML_SIZE: usize = 1024 * 1024;
73
74/// Largest client property the server stores without interpreting it, and
75/// the most one resource may hold.
76const MAX_DEAD_SIZE: usize = 64 * 1024;
77const MAX_DEAD_PROPS: usize = 100;
78
79/// The domain of the addresses users schedule with. `.invalid` is reserved
80/// (RFC 2606), so nothing sent there can reach anyone.
81pub(super) const MAIL_DOMAIN: &str = "dovenest.invalid";
82
83/// The ids of the generated collections, which no stored one has.
84pub(super) const DIRECTORY: i64 = 0;
85pub(super) const BIRTHDAYS: i64 = -1;
86pub(super) const DIRECTORY_SLUG: &str = "system";
87pub(super) const BIRTHDAYS_SLUG: &str = "birthdays";
88/// The slug prefix of a collection lent to the account.
89pub(super) const SHARED_PREFIX: &str = "shared-";
90/// The scheduling inbox is a stored calendar collection under this slug.
91pub(crate) const INBOX: &str = "inbox";
92/// The scheduling outbox holds nothing and is not stored.
93pub(crate) const OUTBOX: &str = "outbox";
94
95/// Characters escaped in an href segment.
96const SEGMENT: &AsciiSet = &CONTROLS
97 .add(b' ')
98 .add(b'"')
99 .add(b'#')
100 .add(b'%')
101 .add(b'/')
102 .add(b'<')
103 .add(b'>')
104 .add(b'?')
105 .add(b'[')
106 .add(b']')
107 .add(b'`')
108 .add(b'{')
109 .add(b'}');
110
111/// Characters a principal name keeps in the local part of its address. The
112/// rest is percent-encoded: `%` is valid there, `@` and spaces are not
113/// (RFC 5322, 3.2.3).
114const LOCAL: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'_').remove(b'.');
115/// The same without the dot, for names where a dot would lead, trail or
116/// repeat.
117const LOCAL_NO_DOT: &AsciiSet = &LOCAL.add(b'.');
118
119type Reply = Result<Response<Body>, ApiError>;
120
121/// Up to this many responses a PROPFIND answer is built in place. Larger ones
122/// go to the blocking pool, so they do not stall the async workers.
123const INLINE_RESPONSES: usize = 64;
124
125/// `{WELL_KNOWN_CALDAV}` and `{WELL_KNOWN_CARDDAV}`.
126///
127/// 307, not 301: HTTP clients drop the body on a 301, and python-caldav sends
128/// its principal search to the URL it was configured with.
129pub async fn well_known() -> Response<Body> {
130 (
131 StatusCode::TEMPORARY_REDIRECT,
132 [(LOCATION, format!("{PIM}/"))],
133 )
134 .into_response()
135}
136
137/// The `DAV` header of every response here. Apple Calendar looks for it on
138/// PROPFIND responses too, not only on OPTIONS.
139pub(super) const COMPLIANCE: &str =
140 "1, 3, access-control, calendar-access, calendar-auto-schedule, addressbook, extended-mkcol";
141
142/// `{PIM}` and everything under it.
143pub async fn handle(State(state): State<Arc<AppState>>, req: Request<Body>) -> Response<Body> {
144 let mut r = match super::dav::authenticate(&state, req.headers()).await {
145 Some((user_id, _)) => serve(&state, user_id, req)
146 .await
147 .unwrap_or_else(IntoResponse::into_response),
148 None => super::dav::challenge(),
149 };
150 r.headers_mut()
151 .insert("dav", axum::http::HeaderValue::from_static(COMPLIANCE));
152 r
153}
154
155/// The signed-in account.
156#[derive(Clone)]
157struct Me {
158 id: i64,
159 /// The account's principal, which owns its collections.
160 pid: i64,
161 admin: bool,
162 /// The scheduling address, for SENT-BY when acting for someone else.
163 address: String,
164 /// The own principal href. Spelled as the request spelled the name when
165 /// it named this account: a client that asked for `/ALICE/` must get
166 /// hrefs it recognises.
167 principal: String,
168}
169
170/// The principal whose URLs a request addresses: the signed-in account, or
171/// a room or resource. Another account's principal is readable too.
172#[derive(Clone)]
173struct Space {
174 id: i64,
175 /// The URL segment, as the request spelled it.
176 path: String,
177 display: String,
178 kind: UserType,
179 mine: bool,
180}
181
182impl Space {
183 fn principal(&self) -> String {
184 principal_href(&self.path)
185 }
186
187 fn home(&self, kind: PimKind) -> String {
188 format!("{PIM}/{}/{}/", kind_segment(kind), seg(&self.path))
189 }
190
191 fn collection(&self, kind: PimKind, slug: &str) -> String {
192 format!("{}{}/", self.home(kind), seg(slug))
193 }
194
195 fn object(&self, kind: PimKind, slug: &str, name: &str) -> String {
196 format!("{}{}", self.collection(kind, slug), seg(name))
197 }
198}
199
200/// The URL of a principal.
201pub(crate) fn principal_href(name: &str) -> String {
202 format!("{PIM}/principals/{}/", seg(name))
203}
204
205/// The principal name of a principal URL, given as a path or a full URL.
206pub(super) fn principal_name(href: &str) -> Option<String> {
207 let path = match href.starts_with('/') {
208 true => href.to_string(),
209 false => href.parse::<axum::http::Uri>().ok()?.path().to_string(),
210 };
211 match parse_target(path.strip_prefix(PIM)?)? {
212 Target::Principal(name) => Some(name),
213 _ => None,
214 }
215}
216
217/// The URL of a collection in the home of `user`, whether it owns it or
218/// has it lent (`lent_id`).
219pub(crate) fn collection_href(
220 user: &str,
221 kind: PimKind,
222 slug: &str,
223 lent_id: Option<i64>,
224) -> String {
225 let slug = match lent_id {
226 Some(id) => format!("{SHARED_PREFIX}{id}"),
227 None => slug.to_string(),
228 };
229 format!("{PIM}/{}/{}/{}/", kind_segment(kind), seg(user), seg(&slug))
230}
231
232/// What the signed-in account may do with a collection.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
234enum Access {
235 Read,
236 /// Change members, not the collection's own properties.
237 Write,
238 /// Also send scheduling messages as the owner.
239 Schedule,
240 Own,
241}
242
243/// A collection as the signed-in account sees it.
244struct Col {
245 /// `slug` and `displayname` as this account sees them.
246 c: PimCollection,
247 access: Access,
248 /// The principal href of the owner.
249 owner: String,
250}
251
252async fn serve(state: &AppState, user_id: i64, req: Request<Body>) -> Reply {
253 let Some(user) = state.db.find_user_by_id(user_id).await? else {
254 return Ok(super::dav::challenge());
255 };
256 let path = req.uri().path().strip_prefix(PIM).unwrap_or_default();
257 let Some(target) = parse_target(path) else {
258 return Ok(status(StatusCode::NOT_FOUND));
259 };
260 let (me, space) = match resolve_space(state, &user, &target).await? {
261 Ok(v) => v,
262 Err(code) => return Ok(status(code)),
263 };
264 state.db.pim_ensure_defaults(me.pid).await?;
265
266 let method = req.method().clone();
267 let (parts, body) = req.into_parts();
268 let cx = Cx {
269 state,
270 me: &me,
271 space: space.as_ref(),
272 };
273 match method.as_str() {
274 "OPTIONS" => Ok(options(&target)),
275 "POST" => cx.post(&target, body).await,
276 "PROPFIND" => cx.propfind(&target, &parts.headers, body).await,
277 "PROPPATCH" => cx.proppatch(&target, body).await,
278 "MKCALENDAR" | "MKCOL" => cx.mkcol(&target, method.as_str(), body).await,
279 "GET" | "HEAD" => {
280 cx.get(&target, &parts.headers, method == Method::HEAD)
281 .await
282 }
283 "PUT" => cx.put(&target, &parts.headers, body).await,
284 "DELETE" => cx.delete(&target, &parts.headers).await,
285 "REPORT" => cx.report(&target, body).await,
286 "MOVE" => cx.move_object(&target, &parts.headers).await,
287 _ => Ok(status(StatusCode::METHOD_NOT_ALLOWED)),
288 }
289}
290
291/// Who asks, and in whose URL space. Another account's space is off limits
292/// except for its principal.
293async fn resolve_space(
294 state: &AppState,
295 user: &User,
296 target: &Target,
297) -> Result<Result<(Me, Option<Space>), StatusCode>, ApiError> {
298 let mut me = Me {
299 id: user.id,
300 pid: state.db.principal_of(user.id).await?,
301 admin: user.is_admin,
302 address: format!("mailto:{}", mailto(&user.name, UserType::Individual)),
303 principal: principal_href(&user.name),
304 };
305 let Some(segment) = target.owner() else {
306 return Ok(Ok((me, None)));
307 };
308 if segment.eq_ignore_ascii_case(&user.name) {
309 me.principal = principal_href(segment);
310 let space = Space {
311 id: me.pid,
312 path: segment.to_string(),
313 display: user.name.clone(),
314 kind: UserType::Individual,
315 mine: true,
316 };
317 return Ok(Ok((me, Some(space))));
318 }
319 let Some(p) = state.db.pim_principal(segment).await? else {
320 return Ok(Err(StatusCode::NOT_FOUND));
321 };
322 if p.kind == UserType::Individual && !matches!(target, Target::Principal(_)) {
323 return Ok(Err(StatusCode::FORBIDDEN));
324 }
325 let space = Space {
326 id: p.id,
327 path: segment.to_string(),
328 display: p.display().to_string(),
329 kind: p.kind,
330 mine: false,
331 };
332 Ok(Ok((me, Some(space))))
333}
334
335#[derive(Debug)]
336enum Target {
337 Root,
338 Principals,
339 Principal(String),
340 Home(PimKind, String),
341 Collection(PimKind, String, String),
342 Object(PimKind, String, String, String),
343}
344
345impl Target {
346 fn owner(&self) -> Option<&str> {
347 match self {
348 Target::Root | Target::Principals => None,
349 Target::Principal(u)
350 | Target::Home(_, u)
351 | Target::Collection(_, u, _)
352 | Target::Object(_, u, _, _) => Some(u),
353 }
354 }
355}
356
357fn parse_target(path: &str) -> Option<Target> {
358 let segs = path
359 .split('/')
360 .filter(|s| !s.is_empty())
361 .map(|s| {
362 let s = percent_decode_str(s).decode_utf8().ok()?;
363 (s != "." && s != "..").then(|| s.into_owned())
364 })
365 .collect::<Option<Vec<_>>>()?;
366 let kind = |s: &str| match s {
367 "calendars" => Some(PimKind::Calendar),
368 "addressbooks" => Some(PimKind::AddressBook),
369 _ => None,
370 };
371 let mut it = segs.into_iter();
372 let Some(first) = it.next() else {
373 return Some(Target::Root);
374 };
375 let rest: Vec<String> = it.collect();
376 if first == "principals" {
377 let mut rest = rest.into_iter();
378 return match (rest.next(), rest.next()) {
379 (None, _) => Some(Target::Principals),
380 (Some(user), None) => Some(Target::Principal(user)),
381 _ => None,
382 };
383 }
384 let kind = kind(&first)?;
385 let mut rest = rest.into_iter();
386 Some(match (rest.next(), rest.next(), rest.next(), rest.next()) {
387 (Some(u), None, None, None) => Target::Home(kind, u),
388 (Some(u), Some(c), None, None) => Target::Collection(kind, u, c),
389 (Some(u), Some(c), Some(o), None) => Target::Object(kind, u, c, o),
390 _ => return None,
391 })
392}
393
394fn kind_segment(kind: PimKind) -> &'static str {
395 match kind {
396 PimKind::Calendar => "calendars",
397 PimKind::AddressBook => "addressbooks",
398 }
399}
400
401fn kind_ns(kind: PimKind) -> &'static str {
402 match kind {
403 PimKind::Calendar => CALDAV,
404 PimKind::AddressBook => CARDDAV,
405 }
406}
407
408pub(super) fn seg(s: &str) -> String {
409 utf8_percent_encode(s, SEGMENT).to_string()
410}
411
412fn status(code: StatusCode) -> Response<Body> {
413 code.into_response()
414}
415
416fn xml_response(code: StatusCode, body: String) -> Response<Body> {
417 (
418 code,
419 [(CONTENT_TYPE, "application/xml; charset=utf-8")],
420 body,
421 )
422 .into_response()
423}
424
425/// A failed precondition, named in a `<d:error>` body.
426fn error(code: StatusCode, condition: Element) -> Response<Body> {
427 xml_response(code, xml::error(condition))
428}
429
430/// The condition for a lacking privilege on `href` (RFC 3744, 7.1.1).
431pub(super) fn need_privilege(href: &str, ns: &str, privilege: &str) -> Element {
432 with_children(
433 el(DAV, "need-privileges"),
434 [with_children(
435 el(DAV, "resource"),
436 [
437 with_text(el(DAV, "href"), href),
438 with_children(el(DAV, "privilege"), [el(ns, privilege)]),
439 ],
440 )],
441 )
442}
443
444fn denied(href: &str, privilege: &str) -> Response<Body> {
445 error(StatusCode::FORBIDDEN, need_privilege(href, DAV, privilege))
446}
447
448fn options(target: &Target) -> Response<Body> {
449 let outbox = matches!(target, Target::Collection(PimKind::Calendar, _, s) if s == OUTBOX);
450 let allow = match outbox {
451 true => "OPTIONS, PROPFIND, POST",
452 false => {
453 "OPTIONS, GET, HEAD, PUT, DELETE, MOVE, PROPFIND, PROPPATCH, MKCALENDAR, MKCOL, REPORT"
454 }
455 };
456 (StatusCode::OK, [(ALLOW.as_str(), allow)]).into_response()
457}
458
459async fn read_body(body: Body, limit: usize) -> Option<axum::body::Bytes> {
460 axum::body::to_bytes(body, limit).await.ok()
461}
462
463pub(super) fn etag_of(data: &[u8]) -> String {
464 format!("\"{}\"", crate::hex(&Sha256::digest(data)[..16]))
465}
466
467/// A stable UUID per principal, for the `urn:uuid:` calendar user address.
468pub(super) fn principal_uuid(id: i64) -> String {
469 let h = crate::hex(&Sha256::digest(format!("dovenest principal {id}"))[..16]);
470 format!(
471 "{}-{}-{}-{}-{}",
472 &h[..8],
473 &h[8..12],
474 &h[12..16],
475 &h[16..20],
476 &h[20..]
477 )
478}
479
480/// The scheduling address of a principal. Rooms and resources use their own
481/// subdomains, so no account name can take their address.
482pub(super) fn mailto(name: &str, kind: UserType) -> String {
483 let domain = match kind {
484 UserType::Individual => MAIL_DOMAIN.to_string(),
485 UserType::Room => format!("rooms.{MAIL_DOMAIN}"),
486 UserType::Resource => format!("resources.{MAIL_DOMAIN}"),
487 };
488 format!("{}@{domain}", local_part(name))
489}
490
491/// A principal name as the local part of an address. Decoding the percent
492/// escapes gives the name back.
493pub(super) fn local_part(name: &str) -> String {
494 let set = match name.starts_with('.') || name.ends_with('.') || name.contains("..") {
495 true => LOCAL_NO_DOT,
496 false => LOCAL,
497 };
498 utf8_percent_encode(name, set).to_string()
499}
500
501/// A principal as PROPFIND and the searches describe it.
502struct PrincipalView {
503 id: i64,
504 /// The URL segment.
505 path: String,
506 display: String,
507 kind: UserType,
508 /// The signed-in account itself.
509 me: bool,
510}
511
512impl PrincipalView {
513 fn of(p: &PimPrincipal, me: &Me) -> Self {
514 PrincipalView {
515 id: p.id,
516 path: p.name.clone(),
517 display: p.display().to_string(),
518 kind: p.kind,
519 me: p.id == me.pid,
520 }
521 }
522
523 /// Only the mailto address: Apple takes the first href in order unless
524 /// one is `preferred`, and an attendee matched by its principal URL gets
525 /// no reply buttons. Scheduling still accepts the principal URL and the
526 /// `urn:uuid:` form.
527 fn addresses(&self) -> Vec<String> {
528 vec![format!("mailto:{}", mailto(&self.path, self.kind))]
529 }
530}
531
532// ---------------------------------------------------------------------------
533// Collections and members
534// ---------------------------------------------------------------------------
535
536/// Whether a collection is generated rather than stored.
537pub(super) fn generated(id: i64) -> bool {
538 id <= DIRECTORY
539}
540
541/// A generated collection. Its CTag and sync token come from `source`, what
542/// its members are built from, so they are known without building them.
543/// Only the current token is valid, so a client resyncs after each change.
544fn generated_collection(
545 id: i64,
546 slug: &str,
547 name: &str,
548 components: &str,
549 source: &str,
550) -> PimCollection {
551 // Bump when the members built from the same source change.
552 const FORMAT: &str = "1";
553 let digest = Sha256::digest(format!("{FORMAT}\n{source}"));
554 PimCollection {
555 id,
556 slug: slug.to_string(),
557 displayname: Some(name.to_string()),
558 components: components.to_string(),
559 seq: i64::from_be_bytes(digest[..8].try_into().expect("8 bytes")) & i64::MAX,
560 ..Default::default()
561 }
562}
563
564pub(super) type Members = Vec<(PimObject, Vec<u8>)>;
565type MemberMap = std::collections::HashMap<String, (PimObject, Vec<u8>)>;
566
567/// The generated system address book.
568pub(super) async fn directory_collection(state: &AppState) -> Result<PimCollection, ApiError> {
569 let source: String = state
570 .db
571 .pim_principals(true)
572 .await?
573 .iter()
574 .map(|p| format!("{}\t{}\t{}\t{:?}\n", p.id, p.name, p.display(), p.kind))
575 .collect();
576 Ok(generated_collection(
577 DIRECTORY,
578 DIRECTORY_SLUG,
579 "Directory",
580 "",
581 &source,
582 ))
583}
584
585/// The members of the system address book: one card per visible principal.
586pub(super) async fn directory(state: &AppState) -> Result<Members, ApiError> {
587 let mut members = Vec::new();
588 for p in state.db.pim_principals(true).await? {
589 let uuid = principal_uuid(p.id);
590 let uid = format!("urn:uuid:{uuid}");
591 let addresses: [String; 0] = [];
592 let view = Principal {
593 name: &p.name,
594 display: p.display(),
595 addresses: &addresses,
596 kind: p.kind,
597 };
598 let data = principal::card(&uid, &view, &mailto(&p.name, p.kind)).into_bytes();
599 members.push((
600 generated_object(format!("{uuid}.vcf"), uid, "VCARD", &data),
601 data,
602 ));
603 }
604 Ok(members)
605}
606
607/// The generated birthday calendar of a principal. It changes whenever one
608/// of the principal's own address books does.
609pub(super) async fn birthdays_collection(
610 state: &AppState,
611 principal: i64,
612) -> Result<PimCollection, ApiError> {
613 let source: String = state
614 .db
615 .pim_collections(principal, PimKind::AddressBook)
616 .await?
617 .iter()
618 .map(|b| format!("{}:{}\n", b.id, b.seq))
619 .collect();
620 let mut col = generated_collection(BIRTHDAYS, BIRTHDAYS_SLUG, "Birthdays", "VEVENT", &source);
621 col.transparent = true;
622 Ok(col)
623}
624
625/// The members of the birthday calendar: the birthdays and anniversaries in
626/// the principal's own address books, not lent ones.
627// ponytail: rebuilt from every contact on each request. Store the events if
628// large address books make it slow.
629pub(super) async fn birthdays(state: &AppState, principal: i64) -> Result<Members, ApiError> {
630 let mut books = Vec::new();
631 for book in state
632 .db
633 .pim_collections(principal, PimKind::AddressBook)
634 .await?
635 {
636 books.push((book.id, state.db.pim_objects_with_data(book.id).await?));
637 }
638 blocking(move || -> Result<Members, ApiError> {
639 let mut members = Vec::new();
640 for (book, objects) in books {
641 for (o, data) in objects {
642 let key = format!("{book}/{}", o.name);
643 for (uid, ics) in contact::dates(&String::from_utf8_lossy(&data), &key) {
644 let data = ics.into_bytes();
645 members.push((
646 generated_object(format!("{uid}.ics"), uid, "VEVENT", &data),
647 data,
648 ));
649 }
650 }
651 }
652 Ok(members)
653 })
654 .await
655}
656
657/// The members of collection `id`, stored or generated. `principal` owns
658/// a generated birthday calendar.
659pub(super) async fn members_of(
660 state: &AppState,
661 principal: i64,
662 id: i64,
663) -> Result<Members, ApiError> {
664 match id {
665 DIRECTORY => directory(state).await,
666 BIRTHDAYS => birthdays(state, principal).await,
667 id => Ok(state.db.pim_objects_with_data(id).await?),
668 }
669}
670
671fn generated_object(name: String, uid: String, component: &str, data: &[u8]) -> PimObject {
672 PimObject {
673 name,
674 uid,
675 component: component.to_string(),
676 etag: etag_of(data),
677 size: data.len() as i64,
678 ..Default::default()
679 }
680}
681
682/// The request context: who asks, and in whose URL space.
683struct Cx<'a> {
684 state: &'a AppState,
685 me: &'a Me,
686 space: Option<&'a Space>,
687}
688
689impl Cx<'_> {
690 fn space(&self) -> &Space {
691 self.space.expect("targets with an owner resolve a space")
692 }
693
694 /// A collection of the space by slug, with the access of the signed-in
695 /// account.
696 async fn collection(&self, kind: PimKind, slug: &str) -> Result<Option<Col>, ApiError> {
697 let space = self.space();
698 let db = &self.state.db;
699 if !space.mine {
700 if slug == INBOX {
701 return Ok(None);
702 }
703 // A room: everyone reads its bookings, admins may change and
704 // answer them.
705 let access = if self.me.admin {
706 Access::Schedule
707 } else {
708 Access::Read
709 };
710 return Ok(db.pim_collection(space.id, kind, slug).await?.map(|c| Col {
711 c,
712 access,
713 owner: space.principal(),
714 }));
715 }
716 if let Some(c) = db.pim_collection(space.id, kind, slug).await? {
717 return Ok(Some(Col {
718 c,
719 access: Access::Own,
720 owner: space.principal(),
721 }));
722 }
723 let generated = match (kind, slug) {
724 (PimKind::AddressBook, DIRECTORY_SLUG) => Some(directory_collection(self.state).await?),
725 (PimKind::Calendar, BIRTHDAYS_SLUG) => {
726 Some(birthdays_collection(self.state, space.id).await?)
727 }
728 _ => None,
729 };
730 if let Some(c) = generated {
731 return Ok(Some(Col {
732 c,
733 access: Access::Read,
734 owner: space.principal(),
735 }));
736 }
737 let Some(id) = slug
738 .strip_prefix(SHARED_PREFIX)
739 .and_then(|id| id.parse().ok())
740 else {
741 return Ok(None);
742 };
743 Ok(db
744 .pim_shared_collection(self.me.id, kind, id)
745 .await?
746 .map(|(c, owner, mode)| lent(c, &owner, mode)))
747 }
748
749 /// Every collection of `kind` in the space's home.
750 async fn collections(&self, kind: PimKind) -> Result<Vec<Col>, ApiError> {
751 let space = self.space();
752 let db = &self.state.db;
753 let own = if space.mine {
754 Access::Own
755 } else if self.me.admin {
756 Access::Schedule
757 } else {
758 Access::Read
759 };
760 let mut out: Vec<Col> = db
761 .pim_collections(space.id, kind)
762 .await?
763 .into_iter()
764 .filter(|c| space.mine || c.slug != INBOX)
765 .map(|c| Col {
766 c,
767 access: own,
768 owner: space.principal(),
769 })
770 .collect();
771 if space.mine {
772 let generated = match kind {
773 PimKind::AddressBook => directory_collection(self.state).await?,
774 PimKind::Calendar => birthdays_collection(self.state, space.id).await?,
775 };
776 out.push(Col {
777 c: generated,
778 access: Access::Read,
779 owner: space.principal(),
780 });
781 for (c, owner, mode) in db.pim_shared_collections(self.me.id, kind).await? {
782 out.push(lent(c, &owner, mode));
783 }
784 }
785 Ok(out)
786 }
787
788 async fn members(&self, c: &PimCollection) -> Result<Members, ApiError> {
789 members_of(self.state, self.space().id, c.id).await
790 }
791
792 async fn member_map(&self, c: &PimCollection) -> Result<MemberMap, ApiError> {
793 Ok(self
794 .members(c)
795 .await?
796 .into_iter()
797 .map(|m| (m.0.name.clone(), m))
798 .collect())
799 }
800
801 /// A generated collection is built as a whole, so a REPORT that looks up
802 /// many of its members builds it once.
803 async fn generated_members(&self, c: &PimCollection) -> Result<Option<MemberMap>, ApiError> {
804 match generated(c.id) {
805 true => Ok(Some(self.member_map(c).await?)),
806 false => Ok(None),
807 }
808 }
809
810 async fn member(
811 &self,
812 c: &PimCollection,
813 name: &str,
814 ) -> Result<Option<(PimObject, Vec<u8>)>, ApiError> {
815 if generated(c.id) {
816 let all = self.members(c).await?;
817 return Ok(all.into_iter().find(|(o, _)| o.name == name));
818 }
819 Ok(self.state.db.pim_object(c.id, name).await?)
820 }
821}
822
823/// Deletes a collection of principal `owner`. A calendar's scheduling
824/// objects are cancelled for their attendees first. `Err` names the
825/// precondition that refuses it: the calendar that receives invitations
826/// stays. Takes [`pim_schedule::LOCK`].
827pub(super) async fn delete_own(
828 state: &AppState,
829 owner: i64,
830 kind: PimKind,
831 col: &PimCollection,
832) -> Result<Result<(), Element>, ApiError> {
833 let db = &state.db;
834 // A PUT checks under the lock that its collection still exists.
835 let _lock = pim_schedule::LOCK.lock().await;
836 if kind == PimKind::Calendar && col.slug != INBOX {
837 if db
838 .pim_calendar_for(owner, "VEVENT")
839 .await?
840 .is_some_and(|d| d.id == col.id)
841 {
842 return Ok(Err(el(CALDAV, "default-calendar-needed")));
843 }
844 let dir = Directory::load(state).await?;
845 let owner = dir
846 .get(owner)
847 .cloned()
848 .ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, "collection not found"))?;
849 let mut ops = match pim_schedule::retract(state, &dir, &owner, &[col.id]).await? {
850 Ok(ops) => ops,
851 Err(refused) => return Ok(Err(refused)),
852 };
853 // The cancellations commit with the delete, so no event goes without
854 // its attendees hearing of it.
855 ops.push(PimOp::DeleteCollection(col.id));
856 db.pim_apply(&ops).await?;
857 return Ok(Ok(()));
858 }
859 db.pim_delete_collection(col.id).await?;
860 Ok(Ok(()))
861}
862
863/// A collection lent to the signed-in account, as it appears in their home.
864fn lent(mut c: PimCollection, owner: &str, mode: PimShareMode) -> Col {
865 let name = c.displayname.take().unwrap_or_else(|| c.slug.clone());
866 c.displayname = Some(format!("{name} ({owner})"));
867 c.slug = format!("{SHARED_PREFIX}{}", c.id);
868 Col {
869 c,
870 access: match mode {
871 PimShareMode::Ro => Access::Read,
872 PimShareMode::Rw => Access::Write,
873 PimShareMode::RwSchedule => Access::Schedule,
874 },
875 owner: principal_href(owner),
876 }
877}
878
879// ---------------------------------------------------------------------------
880// PROPFIND
881// ---------------------------------------------------------------------------
882
883/// A resource PROPFIND can describe.
884enum Res {
885 Root,
886 Principals,
887 Principal(PrincipalView),
888 /// With its owner's principal href, whether the account may add to it,
889 /// and where its client properties live.
890 Home(String, Access, PropPlace),
891 Collection(PimKind, Col),
892 /// With the href of the calendar that receives new invitations.
893 Inbox(Col, Option<String>),
894 /// With its owner's principal href.
895 Outbox(String),
896 Object(PimKind, PimObject),
897}
898
899impl Cx<'_> {
900 async fn propfind(&self, target: &Target, headers: &HeaderMap, body: Body) -> Reply {
901 // Missing means infinity to RFC 4918, but clients that omit it mean 0.
902 let deep = match headers.get("depth").and_then(|v| v.to_str().ok()) {
903 None | Some("0") => false,
904 Some("1") => true,
905 Some(_) => {
906 return Ok(error(
907 StatusCode::FORBIDDEN,
908 el(DAV, "propfind-finite-depth"),
909 ));
910 }
911 };
912 let Some(body) = read_body(body, MAX_XML_SIZE).await else {
913 return Ok(status(StatusCode::PAYLOAD_TOO_LARGE));
914 };
915 let Ok(request) = xml::propfind(&body) else {
916 return Ok(status(StatusCode::BAD_REQUEST));
917 };
918
919 let mut list: Vec<(String, Res)> = Vec::new();
920 match target {
921 Target::Root => list.push((format!("{PIM}/"), Res::Root)),
922 Target::Principals => {
923 list.push((format!("{PIM}/principals/"), Res::Principals));
924 if deep {
925 for p in self.state.db.pim_principals(true).await? {
926 list.push((
927 principal_href(&p.name),
928 Res::Principal(PrincipalView::of(&p, self.me)),
929 ));
930 }
931 }
932 }
933 Target::Principal(_) => {
934 let s = self.space();
935 list.push((
936 s.principal(),
937 Res::Principal(PrincipalView {
938 id: s.id,
939 path: s.path.clone(),
940 display: s.display.clone(),
941 kind: s.kind,
942 me: s.mine,
943 }),
944 ));
945 }
946 Target::Home(kind, _) => {
947 let s = self.space();
948 let access = if s.mine { Access::Own } else { Access::Read };
949 let place = PropPlace::Home(s.id, *kind);
950 list.push((s.home(*kind), Res::Home(s.principal(), access, place)));
951 if deep {
952 for col in self.collections(*kind).await? {
953 let href = s.collection(*kind, &col.c.slug);
954 list.push((href, self.res(*kind, col).await?));
955 }
956 if *kind == PimKind::Calendar && s.mine {
957 list.push((s.collection(*kind, OUTBOX), Res::Outbox(s.principal())));
958 }
959 }
960 }
961 Target::Collection(PimKind::Calendar, _, slug)
962 if slug == OUTBOX && self.space().mine =>
963 {
964 let s = self.space();
965 list.push((
966 s.collection(PimKind::Calendar, OUTBOX),
967 Res::Outbox(s.principal()),
968 ));
969 }
970 Target::Collection(kind, _, slug) => {
971 let Some(col) = self.collection(*kind, slug).await? else {
972 return Ok(status(StatusCode::NOT_FOUND));
973 };
974 let objects = match (deep, col.c.id) {
975 (false, _) => Vec::new(),
976 (true, id) if generated(id) => self
977 .members(&col.c)
978 .await?
979 .into_iter()
980 .map(|(o, _)| o)
981 .collect(),
982 (true, id) => self.state.db.pim_objects(id).await?,
983 };
984 let s = self.space();
985 let slug = col.c.slug.clone();
986 list.push((s.collection(*kind, &slug), self.res(*kind, col).await?));
987 for o in objects {
988 list.push((s.object(*kind, &slug, &o.name), Res::Object(*kind, o)));
989 }
990 }
991 Target::Object(kind, _, slug, name) => {
992 let found = match self.collection(*kind, slug).await? {
993 Some(col) => self.member(&col.c, name).await?,
994 None => None,
995 };
996 let Some((o, _)) = found else {
997 return Ok(status(StatusCode::NOT_FOUND));
998 };
999 list.push((
1000 self.space().object(*kind, slug, name),
1001 Res::Object(*kind, o),
1002 ));
1003 }
1004 }
1005
1006 let described_len = list.len();
1007 let mut described = Vec::with_capacity(described_len);
1008 for (href, res) in list {
1009 let dead = self.dead_props(&res).await?;
1010 described.push((href, res, dead));
1011 }
1012 let answer = move |me: &Me, space: Option<&Space>| {
1013 let responses: Vec<_> = described
1014 .into_iter()
1015 .map(|(href, res, dead)| {
1016 let mut all = live_props(me, space, &res);
1017 all.extend(dead);
1018 select(href, &request, all)
1019 })
1020 .collect();
1021 multistatus(&responses, None)
1022 };
1023 // A handoff to the blocking pool costs more than a small answer.
1024 if described_len <= INLINE_RESPONSES {
1025 return Ok(answer(self.me, self.space));
1026 }
1027 let (me, space) = (self.me.clone(), self.space.cloned());
1028 blocking(move || -> Reply { Ok(answer(&me, space.as_ref())) }).await
1029 }
1030
1031 /// The client properties stored for a resource. Those of a principal or
1032 /// home only reach the accounts that may write them: they hold another
1033 /// account's client settings.
1034 async fn dead_props(&self, res: &Res) -> Result<Vec<Element>, ApiError> {
1035 let place = match res {
1036 Res::Principal(p) if p.me || (self.me.admin && p.kind != UserType::Individual) => {
1037 PropPlace::Principal(p.id)
1038 }
1039 Res::Home(_, _, place) if self.may_edit(self.space()) => *place,
1040 Res::Collection(_, col) | Res::Inbox(col, _) if !generated(col.c.id) => {
1041 PropPlace::Collection(col.c.id)
1042 }
1043 _ => return Ok(Vec::new()),
1044 };
1045 Ok(self
1046 .state
1047 .db
1048 .pim_props(place)
1049 .await?
1050 .iter()
1051 .filter_map(|p| Element::parse(p.xml.as_bytes()).ok())
1052 .collect())
1053 }
1054
1055 fn props(&self, res: &Res) -> Vec<Element> {
1056 live_props(self.me, self.space, res)
1057 }
1058}
1059
1060/// Every live property of a resource, with its value.
1061fn live_props(me: &Me, space: Option<&Space>, res: &Res) -> Vec<Element> {
1062 let text = |ns: &str, local: &str, v: &str| with_text(el(ns, local), v);
1063 let href_prop = |ns: &str, local: &str, h: &str| with_children(el(ns, local), hrefs([h]));
1064 let resourcetype = |types: &[(&str, &str)]| {
1065 with_children(
1066 el(DAV, "resourcetype"),
1067 types.iter().map(|(ns, l)| el(ns, l)),
1068 )
1069 };
1070 let principals = format!("{PIM}/principals/");
1071 let mut out = vec![
1072 href_prop(DAV, "current-user-principal", &me.principal),
1073 href_prop(DAV, "principal-collection-set", &principals),
1074 ];
1075 match res {
1076 Res::Root => out.push(resourcetype(&[(DAV, "collection")])),
1077 Res::Principals => out.extend([
1078 resourcetype(&[(DAV, "collection")]),
1079 privileges(Access::Read),
1080 principal_reports(),
1081 ]),
1082 Res::Principal(p) => {
1083 // The own principal in the spelling of the request.
1084 let href = match p.me {
1085 true => me.principal.clone(),
1086 false => principal_href(&p.path),
1087 };
1088 let addresses = p.addresses();
1089 out.extend([
1090 resourcetype(&[(DAV, "collection"), (DAV, "principal")]),
1091 text(DAV, "displayname", &p.display),
1092 href_prop(DAV, "principal-URL", &href),
1093 with_children(
1094 el(CALDAV, "calendar-user-address-set"),
1095 hrefs(addresses.iter().map(String::as_str))
1096 .into_iter()
1097 .map(|h| with_attr(h, "preferred", "1")),
1098 ),
1099 with_children(
1100 el(CALSERVER, "email-address-set"),
1101 [with_text(
1102 el(CALSERVER, "email-address"),
1103 mailto(&p.path, p.kind),
1104 )],
1105 ),
1106 text(CALDAV, "calendar-user-type", p.kind.as_str()),
1107 privileges(if p.me { Access::Own } else { Access::Read }),
1108 principal_reports(),
1109 ]);
1110 let home = |kind: PimKind| {
1111 let name = match p.me {
1112 true => space.map_or(p.path.clone(), |s| s.path.clone()),
1113 false => p.path.clone(),
1114 };
1115 format!("{PIM}/{}/{}/", kind_segment(kind), seg(&name))
1116 };
1117 // Also for other accounts: python-caldav drops a search hit
1118 // without one. Their homes still answer 403.
1119 out.push(href_prop(
1120 CALDAV,
1121 "calendar-home-set",
1122 &home(PimKind::Calendar),
1123 ));
1124 if p.me {
1125 let cal = home(PimKind::Calendar);
1126 out.push(href_prop(
1127 CALDAV,
1128 "schedule-inbox-URL",
1129 &format!("{cal}{INBOX}/"),
1130 ));
1131 out.push(href_prop(
1132 CALDAV,
1133 "schedule-outbox-URL",
1134 &format!("{cal}{OUTBOX}/"),
1135 ));
1136 let book = home(PimKind::AddressBook);
1137 out.push(href_prop(CARDDAV, "addressbook-home-set", &book));
1138 out.push(href_prop(
1139 CARDDAV,
1140 "directory-gateway",
1141 &format!("{book}{DIRECTORY_SLUG}/"),
1142 ));
1143 }
1144 }
1145 Res::Home(owner, access, _) => out.extend([
1146 resourcetype(&[(DAV, "collection")]),
1147 href_prop(DAV, "owner", owner),
1148 privileges(*access),
1149 ]),
1150 Res::Collection(kind, col) => {
1151 let c = &col.c;
1152 let (types, desc) = match kind {
1153 PimKind::Calendar => ((CALDAV, "calendar"), (CALDAV, "calendar-description")),
1154 PimKind::AddressBook => (
1155 (CARDDAV, "addressbook"),
1156 (CARDDAV, "addressbook-description"),
1157 ),
1158 };
1159 out.extend([
1160 resourcetype(&[(DAV, "collection"), types]),
1161 href_prop(DAV, "owner", &col.owner),
1162 privileges(col.access),
1163 supported_reports(*kind),
1164 text(CALSERVER, "getctag", &format!("{}-{}", c.id, c.seq)),
1165 text(DAV, "sync-token", &sync_token(c.id, c.seq, None)),
1166 text(
1167 kind_ns(*kind),
1168 "max-resource-size",
1169 &MAX_RESOURCE_SIZE.to_string(),
1170 ),
1171 ]);
1172 if let Some(v) = &c.displayname {
1173 out.push(text(DAV, "displayname", v));
1174 }
1175 if let Some(v) = &c.description {
1176 out.push(text(desc.0, desc.1, v));
1177 }
1178 match kind {
1179 PimKind::Calendar => {
1180 out.push(with_children(
1181 el(CALDAV, "supported-calendar-component-set"),
1182 c.components
1183 .split(',')
1184 .map(|comp| with_attr(el(CALDAV, "comp"), "name", comp)),
1185 ));
1186 out.push(with_children(
1187 el(CALDAV, "supported-calendar-data"),
1188 [with_attr(
1189 with_attr(el(CALDAV, "calendar-data"), "content-type", "text/calendar"),
1190 "version",
1191 "2.0",
1192 )],
1193 ));
1194 if let Some(v) = &c.color {
1195 out.push(text(APPLE, "calendar-color", v));
1196 }
1197 if let Some(v) = &c.sort_order {
1198 out.push(text(APPLE, "calendar-order", v));
1199 }
1200 if let Some(v) = &c.timezone {
1201 out.push(text(CALDAV, "calendar-timezone", v));
1202 }
1203 out.push(with_children(
1204 el(CALDAV, "schedule-calendar-transp"),
1205 [el(
1206 CALDAV,
1207 if c.transparent {
1208 "transparent"
1209 } else {
1210 "opaque"
1211 },
1212 )],
1213 ));
1214 }
1215 // 3.0 only: a client told of 4.0 writes 4.0 groups, which
1216 // Apple Contacts on the same account cannot read. A 4.0
1217 // PUT is still stored, and served as 4.0 on request.
1218 PimKind::AddressBook => out.push(with_children(
1219 el(CARDDAV, "supported-address-data"),
1220 [with_attr(
1221 with_attr(
1222 el(CARDDAV, "address-data-type"),
1223 "content-type",
1224 "text/vcard",
1225 ),
1226 "version",
1227 "3.0",
1228 )],
1229 )),
1230 }
1231 }
1232 Res::Inbox(col, default) => {
1233 let c = &col.c;
1234 out.extend([
1235 resourcetype(&[(DAV, "collection"), (CALDAV, "schedule-inbox")]),
1236 href_prop(DAV, "owner", &col.owner),
1237 privilege_set(INBOX_PRIVILEGES),
1238 report_set(&[
1239 (CALDAV, "calendar-multiget"),
1240 (CALDAV, "calendar-query"),
1241 (DAV, "sync-collection"),
1242 ]),
1243 text(CALSERVER, "getctag", &format!("{}-{}", c.id, c.seq)),
1244 text(DAV, "sync-token", &sync_token(c.id, c.seq, None)),
1245 ]);
1246 if let Some(v) = &c.displayname {
1247 out.push(text(DAV, "displayname", v));
1248 }
1249 if let Some(h) = default {
1250 out.push(href_prop(CALDAV, "schedule-default-calendar-URL", h));
1251 }
1252 }
1253 Res::Outbox(owner) => out.extend([
1254 resourcetype(&[(DAV, "collection"), (CALDAV, "schedule-outbox")]),
1255 href_prop(DAV, "owner", owner),
1256 privilege_set(OUTBOX_PRIVILEGES),
1257 ]),
1258 Res::Object(kind, o) => {
1259 if let Some(tag) = &o.schedule_tag {
1260 out.push(text(CALDAV, "schedule-tag", tag));
1261 }
1262 out.extend([
1263 resourcetype(&[]),
1264 text(DAV, "getetag", &o.etag),
1265 text(DAV, "getcontenttype", &content_type(*kind, &o.component)),
1266 text(DAV, "getcontentlength", &o.size.to_string()),
1267 ]);
1268 if let Ok(t) = chrono::DateTime::parse_from_rfc3339(&o.modified_at) {
1269 let http_date = t.to_utc().format("%a, %d %b %Y %H:%M:%S GMT").to_string();
1270 out.push(text(DAV, "getlastmodified", &http_date));
1271 }
1272 }
1273 }
1274 out
1275}
1276
1277impl Cx<'_> {
1278 /// How PROPFIND describes a collection. The inbox names the calendar
1279 /// that receives new invitations.
1280 async fn res(&self, kind: PimKind, col: Col) -> Result<Res, ApiError> {
1281 if kind != PimKind::Calendar || col.c.slug != INBOX {
1282 return Ok(Res::Collection(kind, col));
1283 }
1284 let space = self.space();
1285 let default = self
1286 .state
1287 .db
1288 .pim_calendar_for(space.id, "VEVENT")
1289 .await?
1290 .map(|c| space.collection(PimKind::Calendar, &c.slug));
1291 Ok(Res::Inbox(col, default))
1292 }
1293}
1294
1295/// The response for one resource: the requested ones of `all`, and 404 for
1296/// those it lacks.
1297fn select(href: String, request: &Propfind, all: Vec<Element>) -> xml::Response {
1298 let mut r = xml::Response::new(href);
1299 match request {
1300 Propfind::AllProp(_) => all.into_iter().for_each(|p| r.push(200, p)),
1301 Propfind::PropName => all.iter().for_each(|p| r.push(200, Name::of(p).element())),
1302 Propfind::Prop(names) => {
1303 for n in names {
1304 match all.iter().find(|p| Name::of(p) == *n) {
1305 Some(p) => r.push(200, p.clone()),
1306 None => r.push(404, n.element()),
1307 }
1308 }
1309 }
1310 }
1311 if r.propstats.is_empty() {
1312 r.status = Some(200);
1313 }
1314 r
1315}
1316
1317fn multistatus(responses: &[xml::Response], tail: Option<Element>) -> Response<Body> {
1318 xml_response(
1319 StatusCode::MULTI_STATUS,
1320 xml::multistatus_with(&Name::new(DAV, "multistatus"), responses, tail),
1321 )
1322}
1323
1324fn report_set(reports: &[(&str, &str)]) -> Element {
1325 with_children(
1326 el(DAV, "supported-report-set"),
1327 reports.iter().map(|(ns, local)| {
1328 with_children(
1329 el(DAV, "supported-report"),
1330 [with_children(el(DAV, "report"), [el(ns, local)])],
1331 )
1332 }),
1333 )
1334}
1335
1336fn supported_reports(kind: PimKind) -> Element {
1337 report_set(match kind {
1338 PimKind::Calendar => &[
1339 (CALDAV, "calendar-multiget"),
1340 (CALDAV, "calendar-query"),
1341 (CALDAV, "free-busy-query"),
1342 (DAV, "sync-collection"),
1343 ],
1344 PimKind::AddressBook => &[
1345 (CARDDAV, "addressbook-multiget"),
1346 (CARDDAV, "addressbook-query"),
1347 (DAV, "sync-collection"),
1348 ],
1349 })
1350}
1351
1352fn principal_reports() -> Element {
1353 report_set(&[
1354 (DAV, "principal-property-search"),
1355 (DAV, "principal-search-property-set"),
1356 (CALSERVER, "calendarserver-principal-search"),
1357 ])
1358}
1359
1360fn privileges(access: Access) -> Element {
1361 const WRITE: [(&str, &str); 5] = [
1362 (DAV, "read"),
1363 (DAV, "write-content"),
1364 (DAV, "bind"),
1365 (DAV, "unbind"),
1366 (DAV, "read-current-user-privilege-set"),
1367 ];
1368 let names: Vec<(&str, &str)> = match access {
1369 Access::Own => [
1370 "all",
1371 "read",
1372 "write",
1373 "write-properties",
1374 "write-content",
1375 "bind",
1376 "unbind",
1377 "read-current-user-privilege-set",
1378 ]
1379 .map(|n| (DAV, n))
1380 .to_vec(),
1381 // RFC 6638 grants these on the outbox, which a sharee cannot see.
1382 Access::Schedule => [
1383 (CALDAV, "schedule-send"),
1384 (CALDAV, "schedule-send-invite"),
1385 (CALDAV, "schedule-send-reply"),
1386 ]
1387 .into_iter()
1388 .chain(WRITE)
1389 .collect(),
1390 Access::Write => WRITE.to_vec(),
1391 Access::Read => vec![(DAV, "read"), (DAV, "read-current-user-privilege-set")],
1392 };
1393 privilege_set(names)
1394}
1395
1396/// The owner reads and empties the inbox; only the server delivers into it.
1397const INBOX_PRIVILEGES: [(&str, &str); 7] = [
1398 (DAV, "read"),
1399 (DAV, "unbind"),
1400 (DAV, "read-current-user-privilege-set"),
1401 (CALDAV, "schedule-deliver"),
1402 (CALDAV, "schedule-deliver-invite"),
1403 (CALDAV, "schedule-deliver-reply"),
1404 (CALDAV, "schedule-query-freebusy"),
1405];
1406
1407const OUTBOX_PRIVILEGES: [(&str, &str); 6] = [
1408 (DAV, "read"),
1409 (DAV, "read-current-user-privilege-set"),
1410 (CALDAV, "schedule-send"),
1411 (CALDAV, "schedule-send-invite"),
1412 (CALDAV, "schedule-send-reply"),
1413 (CALDAV, "schedule-send-freebusy"),
1414];
1415
1416fn privilege_set<'a>(names: impl IntoIterator<Item = (&'a str, &'a str)>) -> Element {
1417 with_children(
1418 el(DAV, "current-user-privilege-set"),
1419 names
1420 .into_iter()
1421 .map(|(ns, n)| with_children(el(DAV, "privilege"), [el(ns, n)])),
1422 )
1423}
1424
1425/// Carries the collection id, so a token handed out for a deleted
1426/// collection never matches the one that later takes its URL. A cut initial
1427/// sync also carries `issued`, the collection seq it began at.
1428fn sync_token(id: i64, seq: i64, issued: Option<i64>) -> String {
1429 match issued {
1430 Some(i) => format!("urn:dovenest:sync:{id}-{seq}.{i}"),
1431 None => format!("urn:dovenest:sync:{id}-{seq}"),
1432 }
1433}
1434
1435fn content_type(kind: PimKind, component: &str) -> String {
1436 match kind {
1437 PimKind::Calendar => format!("text/calendar; charset=utf-8; component={component}"),
1438 PimKind::AddressBook => "text/vcard; charset=utf-8".to_string(),
1439 }
1440}
1441
1442// ---------------------------------------------------------------------------
1443// PROPPATCH, MKCALENDAR, MKCOL
1444// ---------------------------------------------------------------------------
1445
1446impl Cx<'_> {
1447 async fn proppatch(&self, target: &Target, body: Body) -> Reply {
1448 let Some(body) = read_body(body, MAX_XML_SIZE).await else {
1449 return Ok(status(StatusCode::PAYLOAD_TOO_LARGE));
1450 };
1451 let Ok(mut update) = xml::update(&body) else {
1452 return Ok(status(StatusCode::BAD_REQUEST));
1453 };
1454 // Read before the lock, so a slow client cannot hold it.
1455 let _lock = pim_schedule::LOCK.lock().await;
1456 let (href, place, res, mut col) = match target {
1457 Target::Collection(kind, _, slug) => {
1458 let Some(col) = self.collection(*kind, slug).await? else {
1459 return Ok(status(StatusCode::NOT_FOUND));
1460 };
1461 let href = self.space().collection(*kind, slug);
1462 if col.access != Access::Own {
1463 return Ok(denied(&href, "write-properties"));
1464 }
1465 let place = PropPlace::Collection(col.c.id);
1466 let stored = (*kind, col.c.clone());
1467 (href, place, self.res(*kind, col).await?, Some(stored))
1468 }
1469 Target::Home(kind, _) => {
1470 let s = self.space();
1471 if !self.may_edit(s) {
1472 return Ok(denied(&s.home(*kind), "write-properties"));
1473 }
1474 let place = PropPlace::Home(s.id, *kind);
1475 let res = Res::Home(s.principal(), Access::Own, place);
1476 (s.home(*kind), place, res, None)
1477 }
1478 Target::Principal(_) => {
1479 let s = self.space();
1480 if !self.may_edit(s) {
1481 return Ok(denied(&s.principal(), "write-properties"));
1482 }
1483 let view = PrincipalView {
1484 id: s.id,
1485 path: s.path.clone(),
1486 display: s.display.clone(),
1487 kind: s.kind,
1488 me: s.mine,
1489 };
1490 let place = PropPlace::Principal(s.id);
1491 (s.principal(), place, Res::Principal(view), None)
1492 }
1493 _ => return Ok(status(StatusCode::FORBIDDEN)),
1494 };
1495 let before = col.as_ref().map(|(_, c)| c.clone());
1496 // The inbox names the calendar that receives invitations (RFC 6638,
1497 // 9.2). `Some(Err(()))`: it names none of the owner's calendars.
1498 let default_url = Name::new(CALDAV, "schedule-default-calendar-URL");
1499 let mut default = None;
1500 if matches!(res, Res::Inbox(..)) {
1501 if let Some(i) = update.set.iter().position(|p| Name::of(p) == default_url) {
1502 let p = update.set.remove(i);
1503 let href = xml::child(&p, DAV, "href").map(xml::text);
1504 default = Some(match href {
1505 Some(h) => self.receiving_calendar(&h).await?.map(Some).ok_or(()),
1506 None => Err(()),
1507 });
1508 } else if let Some(i) = update.remove.iter().position(|n| *n == default_url) {
1509 update.remove.remove(i);
1510 default = Some(Ok(None));
1511 }
1512 }
1513 let live: Vec<Name> = self.props(&res).iter().map(Name::of).collect();
1514 let stored = self.state.db.pim_props(place).await?;
1515 let mut patch = apply(
1516 col.as_mut().map(|(k, c)| (*k, c)),
1517 &update,
1518 false,
1519 &live,
1520 &stored,
1521 );
1522 let default_ok = !matches!(default, Some(Err(())));
1523 if !default_ok {
1524 for (code, _) in &mut patch.results {
1525 if *code == 200 {
1526 *code = 424;
1527 }
1528 }
1529 }
1530 let all_ok = patch.ok() && default_ok;
1531 if all_ok {
1532 let db = &self.state.db;
1533 db.pim_patch(
1534 place,
1535 before.as_ref().zip(col.as_ref().map(|(_, c)| c)),
1536 &patch.set,
1537 &patch.remove,
1538 )
1539 .await?;
1540 if let Some(Ok(id)) = default {
1541 db.pim_set_default_calendar(self.space().id, id).await?;
1542 }
1543 }
1544 let mut r = xml::Response::new(href);
1545 r.error = match (default_ok, patch.protected) {
1546 (false, _) => Some(el(CALDAV, "valid-schedule-default-calendar-URL")),
1547 (true, true) => Some(el(DAV, "cannot-modify-protected-property")),
1548 (true, false) => None,
1549 };
1550 for (code, prop) in patch.results {
1551 r.push(code, prop);
1552 }
1553 if let Some(d) = default {
1554 let code = match (d, all_ok) {
1555 (Err(()), _) => 403,
1556 (Ok(_), true) => 200,
1557 (Ok(_), false) => 424,
1558 };
1559 r.push(code, default_url.element());
1560 }
1561 Ok(multistatus(&[r], None))
1562 }
1563
1564 /// The id of the own calendar at `href` that can receive invitations:
1565 /// stored, not the inbox, taking events.
1566 async fn receiving_calendar(&self, href: &str) -> Result<Option<i64>, ApiError> {
1567 let path = match href.starts_with('/') {
1568 true => href.to_string(),
1569 false => match href.parse::<axum::http::Uri>() {
1570 Ok(u) => u.path().to_string(),
1571 Err(_) => return Ok(None),
1572 },
1573 };
1574 let space = self.space();
1575 let slug = match path.strip_prefix(PIM).and_then(parse_target) {
1576 Some(Target::Collection(PimKind::Calendar, owner, slug))
1577 if owner.eq_ignore_ascii_case(&space.path) =>
1578 {
1579 slug
1580 }
1581 _ => return Ok(None),
1582 };
1583 Ok(self
1584 .collection(PimKind::Calendar, &slug)
1585 .await?
1586 .filter(|c| {
1587 c.access == Access::Own
1588 && !generated(c.c.id)
1589 && c.c.slug != INBOX
1590 && c.c.components.split(',').any(|x| x == "VEVENT")
1591 })
1592 .map(|c| c.c.id))
1593 }
1594
1595 /// The owner changes the properties of its principal and homes, admins
1596 /// those of rooms and resources.
1597 fn may_edit(&self, s: &Space) -> bool {
1598 s.mine || (self.me.admin && s.kind != UserType::Individual)
1599 }
1600
1601 async fn mkcol(&self, target: &Target, method: &str, body: Body) -> Reply {
1602 let Target::Collection(kind, _, slug) = target else {
1603 return Ok(status(StatusCode::METHOD_NOT_ALLOWED));
1604 };
1605 let space = self.space();
1606 if !space.mine {
1607 return Ok(denied(&space.home(*kind), "bind"));
1608 }
1609 let calendar = method == "MKCALENDAR";
1610 if calendar && *kind != PimKind::Calendar {
1611 return Ok(status(StatusCode::FORBIDDEN));
1612 }
1613 if self.collection(*kind, slug).await?.is_some() {
1614 return Ok(status(StatusCode::METHOD_NOT_ALLOWED));
1615 }
1616 // Names the home shows for lent and generated collections.
1617 if slug.starts_with(SHARED_PREFIX)
1618 || [DIRECTORY_SLUG, BIRTHDAYS_SLUG, INBOX, OUTBOX].contains(&slug.as_str())
1619 || slug.len() > MAX_SLUG
1620 {
1621 return Ok(status(StatusCode::FORBIDDEN));
1622 }
1623 if self
1624 .state
1625 .db
1626 .pim_collections(self.me.pid, *kind)
1627 .await?
1628 .len()
1629 >= MAX_COLLECTIONS
1630 {
1631 return Ok(status(StatusCode::FORBIDDEN));
1632 }
1633 let Some(body) = read_body(body, MAX_XML_SIZE).await else {
1634 return Ok(status(StatusCode::PAYLOAD_TOO_LARGE));
1635 };
1636 let Ok(update) = xml::update(&body) else {
1637 return Ok(status(StatusCode::BAD_REQUEST));
1638 };
1639 // A plain MKCOL makes a plain collection, which a calendar home cannot
1640 // hold. An address book home takes it as an address book.
1641 let typed = update
1642 .set
1643 .iter()
1644 .any(|p| Name::of(p).is(DAV, "resourcetype"));
1645 if !calendar && *kind == PimKind::Calendar && !typed {
1646 return Ok(status(StatusCode::FORBIDDEN));
1647 }
1648 let mut col = PimCollection {
1649 slug: slug.clone(),
1650 components: match kind {
1651 PimKind::Calendar => "VEVENT,VTODO,VJOURNAL".to_string(),
1652 PimKind::AddressBook => String::new(),
1653 },
1654 ..Default::default()
1655 };
1656 let res = Res::Collection(
1657 *kind,
1658 Col {
1659 c: col.clone(),
1660 access: Access::Own,
1661 owner: space.principal(),
1662 },
1663 );
1664 let live: Vec<Name> = self.props(&res).iter().map(Name::of).collect();
1665 let patch = apply(Some((*kind, &mut col)), &update, true, &live, &[]);
1666 if !patch.ok() {
1667 let root = match calendar {
1668 true => Name::new(CALDAV, "mkcalendar-response"),
1669 false => Name::new(DAV, "mkcol-response"),
1670 };
1671 let propstats = group(patch.results);
1672 return Ok(xml_response(
1673 StatusCode::FORBIDDEN,
1674 xml::propstat_document(&root, &propstats),
1675 ));
1676 }
1677 if !self
1678 .state
1679 .db
1680 .pim_create_collection(self.me.pid, *kind, &col, &patch.set)
1681 .await?
1682 {
1683 return Ok(status(StatusCode::METHOD_NOT_ALLOWED));
1684 }
1685 Ok(status(StatusCode::CREATED))
1686 }
1687}
1688
1689fn group(results: Vec<(u16, Element)>) -> Vec<(u16, Vec<Element>)> {
1690 let mut r = xml::Response::default();
1691 for (code, prop) in results {
1692 r.push(code, prop);
1693 }
1694 r.propstats
1695}
1696
1697/// A property update: each property with its status, and the client
1698/// properties to store and remove.
1699struct Patch {
1700 results: Vec<(u16, Element)>,
1701 set: Vec<DeadProp>,
1702 remove: Vec<(String, String)>,
1703 /// A property the server computes was named.
1704 protected: bool,
1705}
1706
1707impl Patch {
1708 fn ok(&self) -> bool {
1709 self.results.iter().all(|(code, _)| *code == 200)
1710 }
1711}
1712
1713/// DAV properties the server computes on some resource, beyond the ones
1714/// `live` names for the resource at hand.
1715const PROTECTED: [&str; 20] = [
1716 "acl",
1717 "alternate-URI-set",
1718 "creationdate",
1719 "current-user-principal",
1720 "current-user-privilege-set",
1721 "getcontentlength",
1722 "getcontenttype",
1723 "getetag",
1724 "getlastmodified",
1725 "group",
1726 "group-member-set",
1727 "group-membership",
1728 "lockdiscovery",
1729 "owner",
1730 "principal-URL",
1731 "principal-collection-set",
1732 "resourcetype",
1733 "supported-report-set",
1734 "supportedlock",
1735 "sync-token",
1736];
1737
1738/// Applies a PROPPATCH, MKCALENDAR or extended MKCOL body. A collection's
1739/// own properties go into `col`. What the server computes (`live`, or a
1740/// [`PROTECTED`] DAV property) is refused; anything else is stored as the
1741/// client sent it, as clients expect of properties such as Apple's
1742/// `default-alarm-vevent-date`. Nothing may be stored unless all of it is
1743/// allowed: RFC 4918 makes PROPPATCH atomic.
1744fn apply(
1745 mut col: Option<(PimKind, &mut PimCollection)>,
1746 update: &Update,
1747 creating: bool,
1748 live: &[Name],
1749 stored: &[DeadProp],
1750) -> Patch {
1751 let mut patch = Patch {
1752 results: Vec::new(),
1753 set: Vec::new(),
1754 remove: Vec::new(),
1755 protected: false,
1756 };
1757 let is_protected =
1758 |n: &Name| live.contains(n) || (n.ns == DAV && PROTECTED.contains(&n.local.as_str()));
1759 for p in &update.set {
1760 let name = Name::of(p);
1761 let own = col
1762 .as_mut()
1763 .and_then(|(kind, c)| set_own(*kind, c, p, &name, creating));
1764 let code = match own {
1765 Some(true) => 200,
1766 Some(false) => 403,
1767 None if is_protected(&name) => {
1768 patch.protected = true;
1769 403
1770 }
1771 None => {
1772 let xml = xml::document(p);
1773 if xml.len() > MAX_DEAD_SIZE {
1774 507
1775 } else {
1776 patch.set.push(DeadProp {
1777 ns: name.ns.clone(),
1778 name: name.local.clone(),
1779 xml,
1780 });
1781 200
1782 }
1783 }
1784 };
1785 patch.results.push((code, name.element()));
1786 }
1787 for name in &update.remove {
1788 let own = col
1789 .as_mut()
1790 .and_then(|(kind, c)| remove_own(*kind, c, name));
1791 let code = match own {
1792 Some(()) => 200,
1793 None if is_protected(name) => {
1794 patch.protected = true;
1795 403
1796 }
1797 None => {
1798 patch.remove.push((name.ns.clone(), name.local.clone()));
1799 200
1800 }
1801 };
1802 patch.results.push((code, name.element()));
1803 }
1804 let mut names: Vec<(&str, &str)> = stored
1805 .iter()
1806 .map(|p| (p.ns.as_str(), p.name.as_str()))
1807 .chain(patch.set.iter().map(|p| (p.ns.as_str(), p.name.as_str())))
1808 .filter(|n| {
1809 !patch
1810 .remove
1811 .iter()
1812 .any(|(ns, l)| (ns.as_str(), l.as_str()) == *n)
1813 })
1814 .collect();
1815 names.sort_unstable();
1816 names.dedup();
1817 if names.len() > MAX_DEAD_PROPS {
1818 for (code, prop) in &mut patch.results {
1819 let n = Name::of(prop);
1820 if patch.set.iter().any(|p| p.ns == n.ns && p.name == n.local) {
1821 *code = 507;
1822 }
1823 }
1824 }
1825 if !patch.ok() {
1826 for (code, _) in &mut patch.results {
1827 if *code == 200 {
1828 *code = 424;
1829 }
1830 }
1831 }
1832 patch
1833}
1834
1835fn is_color(v: &str) -> bool {
1836 matches!(v.len(), 7 | 9) && v.starts_with('#') && v[1..].bytes().all(|b| b.is_ascii_hexdigit())
1837}
1838
1839/// Sets one of a collection's own properties. `None` if it is none of them,
1840/// `Some(valid)` otherwise.
1841fn set_own(
1842 kind: PimKind,
1843 col: &mut PimCollection,
1844 p: &Element,
1845 name: &Name,
1846 creating: bool,
1847) -> Option<bool> {
1848 let cal = kind == PimKind::Calendar;
1849 let value = || Some(xml::text(p)).filter(|v| !v.is_empty());
1850 let short = |v: &Option<String>, max: usize, lines: bool| {
1851 v.as_ref().is_none_or(|v| valid_text(v, max, lines))
1852 };
1853 Some(match (name.ns.as_str(), name.local.as_str()) {
1854 (DAV, "displayname") => {
1855 let v = value();
1856 let valid = short(&v, MAX_DISPLAYNAME, false);
1857 if valid {
1858 col.displayname = v;
1859 }
1860 valid
1861 }
1862 (CALDAV, "calendar-description") if cal => {
1863 let v = value();
1864 let valid = short(&v, MAX_DESCRIPTION, true);
1865 if valid {
1866 col.description = v;
1867 }
1868 valid
1869 }
1870 (CARDDAV, "addressbook-description") if !cal => {
1871 let v = value();
1872 let valid = short(&v, MAX_DESCRIPTION, true);
1873 if valid {
1874 col.description = v;
1875 }
1876 valid
1877 }
1878 (APPLE, "calendar-color") if cal => {
1879 let v = value();
1880 let valid = v.as_deref().is_none_or(is_color);
1881 if valid {
1882 col.color = v;
1883 }
1884 valid
1885 }
1886 (APPLE, "calendar-order") if cal => {
1887 let v = value();
1888 let valid = v.as_deref().is_none_or(|v| v.parse::<i64>().is_ok());
1889 if valid {
1890 col.sort_order = v;
1891 }
1892 valid
1893 }
1894 (CALDAV, "calendar-timezone") if cal => {
1895 let tz = value();
1896 let valid = tz.as_deref().is_none_or(is_timezone);
1897 if valid {
1898 col.timezone = tz;
1899 }
1900 valid
1901 }
1902 (CALDAV, "schedule-calendar-transp") if cal => {
1903 let transparent = xml::child(p, CALDAV, "transparent").is_some();
1904 let valid = transparent || xml::child(p, CALDAV, "opaque").is_some();
1905 if valid {
1906 col.transparent = transparent;
1907 }
1908 valid
1909 }
1910 (DAV, "resourcetype") if creating => {
1911 let wanted = match kind {
1912 PimKind::Calendar => (CALDAV, "calendar"),
1913 PimKind::AddressBook => (CARDDAV, "addressbook"),
1914 };
1915 xml::child(p, wanted.0, wanted.1).is_some()
1916 }
1917 (CALDAV, "supported-calendar-component-set") if creating && cal => {
1918 let comps: Vec<_> = xml::elements(p)
1919 .filter(|c| Name::of(c).is(CALDAV, "comp"))
1920 .filter_map(|c| c.attributes.get("name"))
1921 .map(|n| n.to_ascii_uppercase())
1922 .collect();
1923 let valid = !comps.is_empty()
1924 && comps
1925 .iter()
1926 .all(|c| ["VEVENT", "VTODO", "VJOURNAL"].contains(&c.as_str()));
1927 if valid {
1928 col.components = comps.join(",");
1929 }
1930 valid
1931 }
1932 _ => return None,
1933 })
1934}
1935
1936/// Removes one of a collection's own properties. `None` if it is none of
1937/// them.
1938fn remove_own(kind: PimKind, col: &mut PimCollection, name: &Name) -> Option<()> {
1939 let cal = kind == PimKind::Calendar;
1940 if cal && name.is(CALDAV, "schedule-calendar-transp") {
1941 col.transparent = false;
1942 return Some(());
1943 }
1944 let field = match (name.ns.as_str(), name.local.as_str()) {
1945 (DAV, "displayname") => &mut col.displayname,
1946 (CALDAV, "calendar-description") if cal => &mut col.description,
1947 (CARDDAV, "addressbook-description") if !cal => &mut col.description,
1948 (APPLE, "calendar-color") if cal => &mut col.color,
1949 (APPLE, "calendar-order") if cal => &mut col.sort_order,
1950 (CALDAV, "calendar-timezone") if cal => &mut col.timezone,
1951 _ => return None,
1952 };
1953 *field = None;
1954 Some(())
1955}
1956
1957/// A VCALENDAR holding a VTIMEZONE, as `calendar-timezone` must be.
1958fn is_timezone(v: &str) -> bool {
1959 use pimdav::calcard::icalendar::{ICalendar, ICalendarComponentType};
1960 ICalendar::parse(v).is_ok_and(|c| {
1961 c.components
1962 .iter()
1963 .any(|c| c.component_type == ICalendarComponentType::VTimezone)
1964 })
1965}
1966
1967// ---------------------------------------------------------------------------
1968// Objects
1969// ---------------------------------------------------------------------------
1970
1971impl Cx<'_> {
1972 async fn get(&self, target: &Target, headers: &HeaderMap, head: bool) -> Reply {
1973 let Target::Object(kind, _, slug, name) = target else {
1974 return self.get_collection(target, head).await;
1975 };
1976 let found = match self.collection(*kind, slug).await? {
1977 Some(col) => self.member(&col.c, name).await?,
1978 None => None,
1979 };
1980 let Some((o, mut data)) = found else {
1981 return Ok(status(StatusCode::NOT_FOUND));
1982 };
1983 if *kind == PimKind::AddressBook {
1984 let accept = headers.get("accept").and_then(|v| v.to_str().ok());
1985 let req = render::AddressData {
1986 props: None,
1987 version: Some(render::accepted_version(accept)),
1988 };
1989 data = blocking(move || -> Result<_, ApiError> {
1990 Ok(render::address_data(&String::from_utf8_lossy(&data), &req).into_bytes())
1991 })
1992 .await?;
1993 }
1994 let body = if head {
1995 Body::empty()
1996 } else {
1997 Body::from(data)
1998 };
1999 let mut r = (
2000 StatusCode::OK,
2001 [
2002 (CONTENT_TYPE, content_type(*kind, &o.component)),
2003 (ETAG, o.etag),
2004 ],
2005 body,
2006 )
2007 .into_response();
2008 with_schedule_tag(&mut r, o.schedule_tag.as_deref());
2009 Ok(r)
2010 }
2011
2012 /// Clients that discover with GET, as RFC 6764 allows, expect a 2xx on
2013 /// every collection on the way.
2014 async fn get_collection(&self, target: &Target, head: bool) -> Reply {
2015 if let Target::Collection(kind, _, slug) = target
2016 && !(*kind == PimKind::Calendar && slug == OUTBOX && self.space().mine)
2017 && self.collection(*kind, slug).await?.is_none()
2018 {
2019 return Ok(status(StatusCode::NOT_FOUND));
2020 }
2021 let body = match head {
2022 true => "",
2023 false => "CalDAV and CardDAV collection. Open it with a calendar or contacts app.\n",
2024 };
2025 Ok((
2026 StatusCode::OK,
2027 [(CONTENT_TYPE, "text/plain; charset=utf-8")],
2028 body,
2029 )
2030 .into_response())
2031 }
2032
2033 async fn put(&self, target: &Target, headers: &HeaderMap, body: Body) -> Reply {
2034 let Target::Object(kind, _, slug, name) = target else {
2035 return Ok(status(StatusCode::METHOD_NOT_ALLOWED));
2036 };
2037 let Some(Col { c: col, access, .. }) = self.collection(*kind, slug).await? else {
2038 return Ok(status(StatusCode::CONFLICT));
2039 };
2040 let space = self.space();
2041 // The server alone delivers into the inbox.
2042 if access < Access::Write || col.slug == INBOX {
2043 return Ok(denied(&space.collection(*kind, slug), "bind"));
2044 }
2045 let ns = kind_ns(*kind);
2046 let Some(data) = read_body(body, MAX_RESOURCE_SIZE).await else {
2047 return Ok(error(StatusCode::FORBIDDEN, el(ns, "max-resource-size")));
2048 };
2049 let (kind_c, components, name_c) = (*kind, col.components.clone(), name.clone());
2050 let (parsed, stamped, data) = blocking(move || -> Result<_, ApiError> {
2051 let parsed = match kind_c {
2052 PimKind::Calendar => {
2053 let supported: Vec<&str> = components.split(',').collect();
2054 object::calendar(&data, &supported).map(|o| (o.uid, o.component.to_string()))
2055 }
2056 PimKind::AddressBook => {
2057 object::vcard(&data).map(|uid| (uid.unwrap_or(name_c), "VCARD".into()))
2058 }
2059 };
2060 let stamped = match (&parsed, kind_c) {
2061 (Ok(_), PimKind::Calendar) => object::with_dtstamp(&data, chrono::Utc::now()),
2062 _ => None,
2063 };
2064 Ok((parsed, stamped, data))
2065 })
2066 .await?;
2067 let (uid, component) = match parsed {
2068 Ok(v) => v,
2069 Err(invalid) => return Ok(error(StatusCode::FORBIDDEN, invalid.condition())),
2070 };
2071 let data = stamped.as_deref().unwrap_or(&data);
2072
2073 let _lock = pim_schedule::LOCK.lock().await;
2074 // A DELETE of the collection or of the share may have run meanwhile.
2075 let access = match self.collection(*kind, slug).await? {
2076 Some(now) if now.c.id == col.id => now.access,
2077 _ => return Ok(status(StatusCode::CONFLICT)),
2078 };
2079 if access < Access::Write {
2080 return Ok(denied(&space.collection(*kind, slug), "bind"));
2081 }
2082 let db = &self.state.db;
2083 let current = self.member(&col, name).await?;
2084 if refuses(headers, current.as_ref().map(|(o, _)| o)) {
2085 return Ok(status(StatusCode::PRECONDITION_FAILED));
2086 }
2087 if let Some(holder) = db.pim_uid_holder(col.id, &uid, name).await? {
2088 return Ok(error(
2089 StatusCode::FORBIDDEN,
2090 with_children(
2091 el(ns, "no-uid-conflict"),
2092 hrefs([space.object(*kind, slug, &holder).as_str()]),
2093 ),
2094 ));
2095 }
2096 let stored = match kind {
2097 PimKind::Calendar => {
2098 let dir = Directory::load(self.state).await?;
2099 let owner = self.owner(&col, &dir).await?;
2100 let w = self.writer(&owner, access);
2101 let old = current.as_ref().map(|(_, d)| d.as_slice());
2102 match pim_schedule::put(self.state, &dir, &w, (col.id, name), old, data).await? {
2103 Ok(s) => s,
2104 Err(condition) => return Ok(error(StatusCode::FORBIDDEN, condition)),
2105 }
2106 }
2107 PimKind::AddressBook => Stored {
2108 data: data.to_vec(),
2109 changed: false,
2110 schedule_tag: None,
2111 ops: Vec::new(),
2112 },
2113 };
2114 let etag = etag_of(&stored.data);
2115 let mut ops = vec![PimOp::Put {
2116 collection_id: col.id,
2117 obj: PimObject {
2118 name: name.clone(),
2119 uid,
2120 component,
2121 etag: etag.clone(),
2122 schedule_tag: stored.schedule_tag.clone(),
2123 ..Default::default()
2124 },
2125 data: stored.data,
2126 }];
2127 ops.extend(stored.ops);
2128 db.pim_apply(&ops).await?;
2129 let code = match current {
2130 Some(_) => StatusCode::NO_CONTENT,
2131 None => StatusCode::CREATED,
2132 };
2133 let mut r = status(code);
2134 // Only when the stored bytes are the request bytes (RFC 4791, 5.3.4).
2135 if !stored.changed && stamped.is_none() {
2136 r.headers_mut()
2137 .insert(ETAG, etag.parse().expect("hex is a valid header"));
2138 }
2139 with_schedule_tag(&mut r, stored.schedule_tag.as_deref());
2140 Ok(r)
2141 }
2142
2143 /// The signed-in account writing into a calendar of `owner`.
2144 fn writer<'a>(&self, owner: &'a PimPrincipal, access: Access) -> Writer<'a> {
2145 Writer {
2146 owner,
2147 may_schedule: access >= Access::Schedule,
2148 sent_by: (access != Access::Own).then(|| self.me.address.clone()),
2149 }
2150 }
2151
2152 /// The principal owning a collection, whose addresses decide how it takes
2153 /// part in the objects there.
2154 async fn owner(&self, col: &PimCollection, dir: &Directory) -> Result<PimPrincipal, ApiError> {
2155 let owner = match self.state.db.pim_collection_by_id(col.id).await? {
2156 Some((id, _, _)) => dir.get(id).cloned(),
2157 None => None,
2158 };
2159 owner.ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, "collection not found"))
2160 }
2161
2162 async fn delete(&self, target: &Target, headers: &HeaderMap) -> Reply {
2163 let (kind, slug, name) = match target {
2164 Target::Collection(k, _, s) => (k, s, None),
2165 Target::Object(k, _, s, n) => (k, s, Some(n)),
2166 _ => return Ok(status(StatusCode::FORBIDDEN)),
2167 };
2168 // Under the lock, so a revoked share applies at once. `delete_own`
2169 // takes it for a collection.
2170 let _lock = match name {
2171 Some(_) => Some(pim_schedule::LOCK.lock().await),
2172 None => None,
2173 };
2174 let Some(Col { c: col, access, .. }) = self.collection(*kind, slug).await? else {
2175 return Ok(status(StatusCode::NOT_FOUND));
2176 };
2177 let space = self.space();
2178 let href = space.collection(*kind, slug);
2179 let scheduling = *kind == PimKind::Calendar && col.slug != INBOX;
2180 let db = &self.state.db;
2181 let Some(name) = name else {
2182 return Ok(match access {
2183 Access::Own if *kind == PimKind::Calendar && col.slug == INBOX => {
2184 denied(&space.home(*kind), "unbind")
2185 }
2186 Access::Own => match delete_own(self.state, space.id, *kind, &col).await? {
2187 Ok(()) => status(StatusCode::NO_CONTENT),
2188 Err(condition) => error(StatusCode::FORBIDDEN, condition),
2189 },
2190 // Deleting a lent collection only takes it out of this home.
2191 _ if slug.starts_with(SHARED_PREFIX) && space.mine => {
2192 let _lock = pim_schedule::LOCK.lock().await;
2193 db.pim_remove_share(col.id, self.me.id).await?;
2194 status(StatusCode::NO_CONTENT)
2195 }
2196 _ => denied(&space.home(*kind), "unbind"),
2197 });
2198 };
2199 if access < Access::Write {
2200 return Ok(denied(&href, "unbind"));
2201 }
2202 let Some((obj, data)) = self.member(&col, name).await? else {
2203 return Ok(status(StatusCode::NOT_FOUND));
2204 };
2205 if refuses(headers, Some(&obj)) {
2206 return Ok(status(StatusCode::PRECONDITION_FAILED));
2207 }
2208 let mut ops = vec![PimOp::Delete {
2209 collection_id: col.id,
2210 name: name.clone(),
2211 }];
2212 if scheduling {
2213 let dir = Directory::load(self.state).await?;
2214 let owner = self.owner(&col, &dir).await?;
2215 let w = self.writer(&owner, access);
2216 let reply = headers.get("schedule-reply").and_then(|v| v.to_str().ok()) != Some("F");
2217 match pim_schedule::delete(self.state, &dir, &w, &data, reply).await? {
2218 Ok(more) => ops.extend(more),
2219 Err(condition) => return Ok(error(StatusCode::FORBIDDEN, condition)),
2220 }
2221 }
2222 db.pim_apply(&ops).await?;
2223 Ok(status(StatusCode::NO_CONTENT))
2224 }
2225}
2226
2227/// Whether If-Match, If-None-Match or If-Schedule-Tag-Match fails against
2228/// the current object.
2229fn refuses(headers: &HeaderMap, current: Option<&PimObject>) -> bool {
2230 if !precondition(headers).allows(current.map(|o| o.etag.as_str())) {
2231 return true;
2232 }
2233 headers
2234 .get("if-schedule-tag-match")
2235 .and_then(|v| v.to_str().ok())
2236 .is_some_and(|tag| current.and_then(|o| o.schedule_tag.as_deref()) != Some(tag.trim()))
2237}
2238
2239fn with_schedule_tag(r: &mut Response<Body>, tag: Option<&str>) {
2240 if let Some(v) = tag.and_then(|t| t.parse().ok()) {
2241 r.headers_mut().insert("schedule-tag", v);
2242 }
2243}
2244
2245fn precondition(headers: &HeaderMap) -> Precondition {
2246 let header = |name: &str| {
2247 headers
2248 .get(name)
2249 .and_then(|v| v.to_str().ok())
2250 .map(str::to_string)
2251 };
2252 Precondition {
2253 if_match: header("if-match"),
2254 if_none_match: header("if-none-match"),
2255 }
2256}
2257
2258// ---------------------------------------------------------------------------
2259// REPORT
2260// ---------------------------------------------------------------------------
2261
2262impl Cx<'_> {
2263 async fn report(&self, target: &Target, body: Body) -> Reply {
2264 let Some(body) = read_body(body, MAX_XML_SIZE).await else {
2265 return Ok(status(StatusCode::PAYLOAD_TOO_LARGE));
2266 };
2267 let report = match report::parse(&body) {
2268 Ok(r) => r,
2269 Err(Refused::Invalid) => return Ok(status(StatusCode::BAD_REQUEST)),
2270 Err(Refused::Condition(c)) => return Ok(error(StatusCode::FORBIDDEN, c.element())),
2271 };
2272 let unsupported = || Ok(error(StatusCode::FORBIDDEN, el(DAV, "supported-report")));
2273 let on_principals = matches!(
2274 target,
2275 Target::Root | Target::Principals | Target::Principal(_)
2276 );
2277 match report {
2278 Report::PrincipalSearch(search) if on_principals => {
2279 return self.principal_search(&search).await;
2280 }
2281 Report::PrincipalSearchPropertySet if on_principals => {
2282 return Ok(search_property_set());
2283 }
2284 Report::PrincipalSearch(_) | Report::PrincipalSearchPropertySet => {
2285 return unsupported();
2286 }
2287 _ => {}
2288 }
2289 let Target::Collection(kind, _, slug) = target else {
2290 return unsupported();
2291 };
2292 let calendar_report = matches!(
2293 report,
2294 Report::CalendarMultiget { .. } | Report::CalendarQuery { .. } | Report::FreeBusy(_)
2295 );
2296 let card_report = matches!(
2297 report,
2298 Report::AddressbookMultiget { .. } | Report::AddressbookQuery { .. }
2299 );
2300 if (calendar_report && *kind != PimKind::Calendar)
2301 || (card_report && *kind != PimKind::AddressBook)
2302 {
2303 return unsupported();
2304 }
2305 let Some(Col { c: col, .. }) = self.collection(*kind, slug).await? else {
2306 return Ok(status(StatusCode::NOT_FOUND));
2307 };
2308 // Busy time comes from calendars, never from messages (RFC 6638, 2.3).
2309 if col.slug == INBOX && matches!(report, Report::FreeBusy(_)) {
2310 return unsupported();
2311 }
2312 let floating = col
2313 .timezone
2314 .as_deref()
2315 .and_then(zone::from_vtimezone)
2316 .unwrap_or(Zone::Utc);
2317 let mut out = Out {
2318 me: self.me.clone(),
2319 space: self.space().clone(),
2320 kind: *kind,
2321 col: col.clone(),
2322 expanded: 0,
2323 };
2324
2325 match report {
2326 Report::CalendarMultiget { props, hrefs }
2327 | Report::AddressbookMultiget { props, hrefs } => {
2328 let members = self.generated_members(&col).await?;
2329 let mut seen = HashSet::new();
2330 let mut found = Vec::new();
2331 let mut loaded = 0;
2332 let mut cut = false;
2333 for href in hrefs {
2334 if !seen.insert(href.clone()) {
2335 continue;
2336 }
2337 if found.len() >= MAX_MULTIGET_HREFS || loaded > MAX_MULTIGET_BYTES {
2338 cut = true;
2339 break;
2340 }
2341 let hit = match self.own_object(*kind, &href) {
2342 Some((slug, name)) if slug == col.slug => match &members {
2343 Some(m) => m.get(&name).cloned(),
2344 None => self.state.db.pim_object(col.id, &name).await?,
2345 },
2346 _ => None,
2347 };
2348 loaded += hit.as_ref().map_or(0, |(_, data)| data.len());
2349 found.push((href, hit));
2350 }
2351 blocking(move || -> Reply {
2352 let mut responses = Vec::new();
2353 for (href, hit) in found {
2354 if out.full() {
2355 cut = true;
2356 break;
2357 }
2358 responses.push(match hit {
2359 // The href as the client wrote it, so it can match it.
2360 Some((o, data)) => match out.object(&o, &data, &props, &floating) {
2361 Ok(r) => xml::Response { href, ..r },
2362 Err(TooManyInstances) => return Ok(too_many()),
2363 },
2364 None => xml::Response::status(href, 404),
2365 });
2366 }
2367 if cut {
2368 responses.push(out.over_limit());
2369 }
2370 Ok(multistatus(&responses, None))
2371 })
2372 .await
2373 }
2374 Report::CalendarQuery {
2375 props,
2376 filter,
2377 timezone,
2378 } => {
2379 let floating = timezone.unwrap_or(floating);
2380 let members = self.members(&col).await?;
2381 blocking(move || -> Reply {
2382 let mut responses = Vec::new();
2383 for (o, data) in members {
2384 let Ok(cal) = ICalendar::parse(String::from_utf8_lossy(&data).as_ref())
2385 else {
2386 continue;
2387 };
2388 if !filter::matches_calendar(&cal, &filter, &floating) {
2389 continue;
2390 }
2391 if out.full() {
2392 responses.push(out.over_limit());
2393 break;
2394 }
2395 match out.object(&o, &data, &props, &floating) {
2396 Ok(r) => responses.push(r),
2397 Err(TooManyInstances) => return Ok(too_many()),
2398 }
2399 }
2400 Ok(multistatus(&responses, None))
2401 })
2402 .await
2403 }
2404 Report::AddressbookQuery {
2405 props,
2406 filter,
2407 limit,
2408 } => {
2409 let members = self.members(&col).await?;
2410 blocking(move || -> Reply {
2411 let mut responses = Vec::new();
2412 let mut truncated = false;
2413 for (o, data) in members {
2414 let Ok(card) = VCard::parse(String::from_utf8_lossy(&data).as_ref()) else {
2415 continue;
2416 };
2417 if !filter::matches_card(&card, &filter) {
2418 continue;
2419 }
2420 if limit.is_some_and(|n| responses.len() >= n) {
2421 truncated = true;
2422 break;
2423 }
2424 if let Ok(r) = out.object(&o, &data, &props, &floating) {
2425 responses.push(r);
2426 }
2427 }
2428 if truncated {
2429 responses.push(out.over_limit());
2430 }
2431 Ok(multistatus(&responses, None))
2432 })
2433 .await
2434 }
2435 Report::SyncCollection {
2436 token,
2437 props,
2438 limit,
2439 } => {
2440 let (since, issued) = match token.is_empty() {
2441 true => (None, None),
2442 false => match parse_sync_token(&token) {
2443 // A generated collection has no change log: only its
2444 // current token is valid.
2445 Some((id, seq, None))
2446 if id == col.id && generated(id) && seq == col.seq =>
2447 {
2448 (Some(seq), None)
2449 }
2450 Some((id, seq, issued))
2451 if id == col.id
2452 && !generated(id)
2453 && seq <= col.seq
2454 && issued.is_none_or(|i| seq <= i && i <= col.seq) =>
2455 {
2456 (Some(seq), issued)
2457 }
2458 _ => return Ok(invalid_sync_token()),
2459 },
2460 };
2461 // A generated collection has no change log to resume a cut
2462 // answer from. It is small, so it always answers in full.
2463 let limit = limit.filter(|_| !generated(col.id));
2464 // The changes come first: a write between the two reads then
2465 // only makes the next sync refetch a member.
2466 let mut changes = match generated(col.id) {
2467 true => Vec::new(),
2468 false => match self.state.db.pim_changes(col.id, since, issued).await? {
2469 Some(c) => c,
2470 None => return Ok(invalid_sync_token()),
2471 },
2472 };
2473 // An initial sync reads every member at once, not one per change.
2474 let mut members = match since {
2475 None => Some(self.member_map(&col).await?),
2476 Some(_) => None,
2477 };
2478 if let (Some(m), true) = (&members, generated(col.id)) {
2479 let mut names: Vec<_> = m.keys().cloned().collect();
2480 names.sort();
2481 changes = names.into_iter().map(|n| (n, col.seq, false)).collect();
2482 }
2483 // The client of a cut initial sync saw nothing deleted before it
2484 // began, so pruning up to there leaves its resume token valid.
2485 let issued = issued.or(since.is_none().then_some(col.seq));
2486 let truncated = limit.is_some_and(|n| changes.len() > n);
2487 if let Some(n) = limit {
2488 changes.truncate(n);
2489 }
2490 // A truncated answer hands out the token of its last change, so
2491 // the next sync resumes after it.
2492 let seq = match (truncated, changes.last()) {
2493 _ if generated(col.id) => col.seq,
2494 (true, Some((_, s, _))) => *s,
2495 (_, last) => col.seq.max(last.map_or(0, |(_, s, _)| *s)),
2496 };
2497 let mut found = Vec::with_capacity(changes.len());
2498 for (name, change, deleted) in changes {
2499 let hit = match (deleted, members.as_mut().and_then(|m| m.remove(&name))) {
2500 (true, _) => None,
2501 (false, Some(hit)) => Some(hit),
2502 // Written after the member map was read.
2503 (false, None) if !generated(col.id) => {
2504 self.state.db.pim_object(col.id, &name).await?
2505 }
2506 (false, None) => None,
2507 };
2508 found.push((name, change, hit));
2509 }
2510 let slug = col.slug.clone();
2511 let cuttable = !generated(col.id);
2512 blocking(move || -> Reply {
2513 let (mut responses, mut seq, mut truncated) = (Vec::new(), seq, truncated);
2514 let mut last = seq;
2515 for (name, change, hit) in found {
2516 // Cut like a client limit: the token of the last change answered.
2517 if cuttable && out.full() {
2518 (seq, truncated) = (last, true);
2519 break;
2520 }
2521 last = change;
2522 responses.push(match hit {
2523 Some((o, data)) => match out.object(&o, &data, &props, &floating) {
2524 Ok(r) => r,
2525 Err(TooManyInstances) => return Ok(too_many()),
2526 },
2527 None => {
2528 xml::Response::status(out.space.object(out.kind, &slug, &name), 404)
2529 }
2530 });
2531 }
2532 if truncated {
2533 responses.push(out.over_limit());
2534 }
2535 let token = sync_token(col.id, seq, issued.filter(|_| truncated));
2536 Ok(multistatus(
2537 &responses,
2538 Some(with_text(el(DAV, "sync-token"), token)),
2539 ))
2540 })
2541 .await
2542 }
2543 Report::FreeBusy(range) => {
2544 let members = self.members(&col).await?;
2545 blocking(move || -> Reply {
2546 let mut busy = Vec::new();
2547 for (_, data) in members {
2548 if let Ok(cal) = ICalendar::parse(String::from_utf8_lossy(&data).as_ref()) {
2549 // ponytail: one period per instance, so a long range over
2550 // a frequent series makes a long answer.
2551 busy.extend(freebusy::busy(&cal, &range, &floating, None));
2552 }
2553 }
2554 let body =
2555 freebusy::vfreebusy(&freebusy::merge(busy), &range, chrono::Utc::now());
2556 Ok((
2557 StatusCode::OK,
2558 [(CONTENT_TYPE, "text/calendar; charset=utf-8")],
2559 body,
2560 )
2561 .into_response())
2562 })
2563 .await
2564 }
2565 Report::PrincipalSearch(_) | Report::PrincipalSearchPropertySet => {
2566 unreachable!("answered above")
2567 }
2568 }
2569 }
2570
2571 /// principal-property-search and calendarserver-principal-search.
2572 async fn principal_search(&self, search: &Search) -> Reply {
2573 let mut responses = Vec::new();
2574 let mut truncated = false;
2575 for p in self.state.db.pim_principals(true).await? {
2576 let view = PrincipalView::of(&p, self.me);
2577 let addresses = view.addresses();
2578 let candidate = Principal {
2579 name: &p.name,
2580 display: p.display(),
2581 addresses: &addresses,
2582 kind: p.kind,
2583 };
2584 if !search.matches(&candidate) {
2585 continue;
2586 }
2587 if search.limit.is_some_and(|n| responses.len() >= n) {
2588 truncated = true;
2589 break;
2590 }
2591 let href = principal_href(&p.name);
2592 responses.push(select(
2593 href,
2594 &search.find,
2595 self.props(&Res::Principal(view)),
2596 ));
2597 }
2598 if truncated {
2599 let mut r = xml::Response::status(format!("{PIM}/principals/"), 507);
2600 r.error = Some(el(DAV, "number-of-matches-within-limits"));
2601 responses.push(r);
2602 }
2603 Ok(multistatus(&responses, None))
2604 }
2605
2606 /// `(collection slug, object name)` of an href to an object of `kind` in
2607 /// the space of this request. Takes a path or a full URL.
2608 fn own_object(&self, kind: PimKind, href: &str) -> Option<(String, String)> {
2609 let path = match href.starts_with('/') {
2610 true => href.to_string(),
2611 false => href.parse::<axum::http::Uri>().ok()?.path().to_string(),
2612 };
2613 let space = self.space?;
2614 match parse_target(path.strip_prefix(PIM)?)? {
2615 Target::Object(k, owner, slug, name)
2616 if k == kind && owner.eq_ignore_ascii_case(&space.path) =>
2617 {
2618 Some((slug, name))
2619 }
2620 _ => None,
2621 }
2622 }
2623}
2624
2625fn search_property_set() -> Response<Body> {
2626 let body = xml::document(&with_children(
2627 el(DAV, "principal-search-property-set"),
2628 principal::SEARCHABLE.map(|(ns, local, description)| {
2629 with_children(
2630 el(DAV, "principal-search-property"),
2631 [
2632 with_children(el(DAV, "prop"), [el(ns, local)]),
2633 with_attr(
2634 with_text(el(DAV, "description"), description),
2635 "xml:lang",
2636 "en",
2637 ),
2638 ],
2639 )
2640 }),
2641 ));
2642 xml_response(StatusCode::OK, body)
2643}
2644
2645/// Instances `expand` may produce for one REPORT answer, across its objects.
2646/// Beyond it the answer is cut short with a 507, as for a client limit.
2647const MAX_EXPANDED_PER_ANSWER: usize = 20_000;
2648
2649/// Hrefs and object bytes one multiget loads. Beyond them it answers 507.
2650const MAX_MULTIGET_HREFS: usize = 1000;
2651const MAX_MULTIGET_BYTES: usize = 32 * 1024 * 1024;
2652
2653/// What a REPORT answer about one collection needs. Owned, so the answer
2654/// can be built on the blocking pool.
2655struct Out {
2656 me: Me,
2657 space: Space,
2658 kind: PimKind,
2659 col: PimCollection,
2660 /// Instances `expand` produced for this answer so far.
2661 expanded: usize,
2662}
2663
2664impl Out {
2665 fn object(
2666 &mut self,
2667 o: &PimObject,
2668 data: &[u8],
2669 props: &Props,
2670 floating: &Zone,
2671 ) -> Result<xml::Response, TooManyInstances> {
2672 let mut all = live_props(
2673 &self.me,
2674 Some(&self.space),
2675 &Res::Object(self.kind, o.clone()),
2676 );
2677 let raw = String::from_utf8_lossy(data);
2678 if let Some(req) = &props.calendar {
2679 let (text, instances) = render::calendar_data(&raw, req, floating)?;
2680 self.expanded += instances;
2681 all.push(with_text(el(CALDAV, "calendar-data"), text));
2682 }
2683 if let Some(req) = &props.address {
2684 all.push(with_text(
2685 el(CARDDAV, "address-data"),
2686 render::address_data(&raw, req),
2687 ));
2688 }
2689 let href = self.space.object(self.kind, &self.col.slug, &o.name);
2690 Ok(select(href, &props.find, all))
2691 }
2692
2693 fn full(&self) -> bool {
2694 self.expanded > MAX_EXPANDED_PER_ANSWER
2695 }
2696
2697 /// The response a query or sync adds when a limit cut it short.
2698 fn over_limit(&self) -> xml::Response {
2699 let href = self.space.collection(self.kind, &self.col.slug);
2700 let mut r = xml::Response::status(href, 507);
2701 r.error = Some(el(DAV, "number-of-matches-within-limits"));
2702 r
2703 }
2704}
2705
2706fn invalid_sync_token() -> Response<Body> {
2707 error(StatusCode::FORBIDDEN, el(DAV, "valid-sync-token"))
2708}
2709
2710fn too_many() -> Response<Body> {
2711 error(StatusCode::FORBIDDEN, el(CALDAV, "max-instances"))
2712}
2713
2714/// `(collection id, seq, issued)` of a token [`sync_token`] made.
2715fn parse_sync_token(token: &str) -> Option<(i64, i64, Option<i64>)> {
2716 let rest = token.strip_prefix("urn:dovenest:sync:")?;
2717 let (rest, issued) = match rest.split_once('.') {
2718 Some((r, i)) => (r, Some(i.parse().ok()?)),
2719 None => (rest, None),
2720 };
2721 // The birthday calendar's id is negative.
2722 let (id, seq) = rest.rsplit_once('-')?;
2723 Some((id.parse().ok()?, seq.parse().ok()?, issued))
2724}
2725
2726// ---------------------------------------------------------------------------
2727// POST
2728// ---------------------------------------------------------------------------
2729
2730impl Cx<'_> {
2731 /// A free-busy request to the own scheduling outbox (RFC 6638, 5).
2732 async fn post(&self, target: &Target, body: Body) -> Reply {
2733 let space = match target {
2734 Target::Collection(PimKind::Calendar, _, slug) if slug == OUTBOX => self.space(),
2735 _ => return Ok(status(StatusCode::METHOD_NOT_ALLOWED)),
2736 };
2737 if !space.mine {
2738 let href = space.collection(PimKind::Calendar, OUTBOX);
2739 return Ok(error(
2740 StatusCode::FORBIDDEN,
2741 need_privilege(&href, CALDAV, "schedule-send-freebusy"),
2742 ));
2743 }
2744 let Some(body) = read_body(body, MAX_XML_SIZE).await else {
2745 return Ok(status(StatusCode::PAYLOAD_TOO_LARGE));
2746 };
2747 let request = match freebusy::request(&body) {
2748 Ok(r) => r,
2749 Err(condition) => return Ok(error(StatusCode::FORBIDDEN, condition.element())),
2750 };
2751 let dir = Directory::load(self.state).await?;
2752 if !dir.is(self.me.pid)(&request.organizer) {
2753 return Ok(error(
2754 StatusCode::FORBIDDEN,
2755 el(CALDAV, "organizer-allowed"),
2756 ));
2757 }
2758 let answers = pim_schedule::free_busy(self.state, &dir, &request).await?;
2759 Ok(xml_response(
2760 StatusCode::OK,
2761 freebusy::schedule_response(&answers),
2762 ))
2763 }
2764}
2765
2766// ---------------------------------------------------------------------------
2767// MOVE
2768// ---------------------------------------------------------------------------
2769
2770impl Cx<'_> {
2771 async fn move_object(&self, target: &Target, headers: &HeaderMap) -> Reply {
2772 let Target::Object(kind, _, slug, name) = target else {
2773 return Ok(status(StatusCode::METHOD_NOT_ALLOWED));
2774 };
2775 let destination = headers.get("destination").and_then(|v| v.to_str().ok());
2776 let Some((to_slug, to_name)) = destination.and_then(|d| self.own_object(*kind, d)) else {
2777 return Ok(status(StatusCode::FORBIDDEN));
2778 };
2779 if (&to_slug, &to_name) == (slug, name) {
2780 return Ok(status(StatusCode::FORBIDDEN));
2781 }
2782 let space = self.space();
2783 let _lock = pim_schedule::LOCK.lock().await;
2784 let Some(from) = self.collection(*kind, slug).await? else {
2785 return Ok(status(StatusCode::NOT_FOUND));
2786 };
2787 let Some(to) = self.collection(*kind, &to_slug).await? else {
2788 return Ok(status(StatusCode::CONFLICT));
2789 };
2790 if from.access < Access::Write || from.c.slug == INBOX {
2791 return Ok(denied(&space.collection(*kind, slug), "unbind"));
2792 }
2793 if to.access < Access::Write || to.c.slug == INBOX {
2794 return Ok(denied(&space.collection(*kind, &to_slug), "bind"));
2795 }
2796 // A meeting stays in its organizer's calendars (`elsewhere` allows one
2797 // scheduling object per UID and principal), so an object never changes owner. Clients fall back to
2798 // PUT and DELETE, which schedule as usual.
2799 if !from.owner.eq_ignore_ascii_case(&to.owner) {
2800 return Ok(status(StatusCode::FORBIDDEN));
2801 }
2802 let Some((obj, _)) = self.member(&from.c, name).await? else {
2803 return Ok(status(StatusCode::NOT_FOUND));
2804 };
2805 // Moving between calendars schedules nothing (RFC 6638, 3.2.3.4).
2806 if refuses(headers, Some(&obj)) {
2807 return Ok(status(StatusCode::PRECONDITION_FAILED));
2808 }
2809 if *kind == PimKind::Calendar && !to.c.components.split(',').any(|c| c == obj.component) {
2810 return Ok(error(
2811 StatusCode::FORBIDDEN,
2812 el(CALDAV, "supported-calendar-component"),
2813 ));
2814 }
2815 let overwrite = headers.get("overwrite").and_then(|v| v.to_str().ok()) != Some("F");
2816 // Overwriting a meeting would drop it without telling its attendees.
2817 if overwrite
2818 && self
2819 .member(&to.c, &to_name)
2820 .await?
2821 .is_some_and(|(o, _)| o.schedule_tag.is_some())
2822 {
2823 return Ok(status(StatusCode::FORBIDDEN));
2824 }
2825 let written = self
2826 .state
2827 .db
2828 .pim_move_object(
2829 from.c.id,
2830 name,
2831 to.c.id,
2832 &to_name,
2833 overwrite,
2834 &precondition(headers),
2835 )
2836 .await?;
2837 Ok(match written {
2838 PimWrite::Created | PimWrite::Updated => {
2839 let code = match written {
2840 PimWrite::Created => StatusCode::CREATED,
2841 _ => StatusCode::NO_CONTENT,
2842 };
2843 let mut r = status(code);
2844 with_schedule_tag(&mut r, obj.schedule_tag.as_deref());
2845 r
2846 }
2847 PimWrite::NotFound => status(StatusCode::NOT_FOUND),
2848 PimWrite::PreconditionFailed => status(StatusCode::PRECONDITION_FAILED),
2849 PimWrite::UidConflict(holder) => error(
2850 StatusCode::FORBIDDEN,
2851 with_children(
2852 el(kind_ns(*kind), "no-uid-conflict"),
2853 hrefs([space.object(*kind, &to_slug, &holder).as_str()]),
2854 ),
2855 ),
2856 PimWrite::Deleted => status(StatusCode::INTERNAL_SERVER_ERROR),
2857 })
2858 }
2859}
2860