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