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