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