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