1 // This file contains functions which handle all of the CalDAV "REPORT" queries specified in RFC4791 section 7.
2 // Copyright (c) 2023-2024 by the citadel.org team
3 // This program is open source software. Use, duplication, or disclosure is subject to the GNU General Public License v3.
7 #define CAL "urn:ietf:params:xml:ns:caldav:" // Shorthand for the XML namespace of CalDAV
8 #define CALLEN sizeof(CAL)-1 // And the length of that string
10 // A CalDAV REPORT can only be one type. This is stored in the report_type member.
18 // Data type for CalDAV Report Parameters.
19 // As we slog our way through the XML we learn what the client is asking for
20 // and build up the contents of this data type.
22 int comp_filter_nesting_level;
23 enum cr_type report_type; // which RFC4791 section 7 REPORT are we generating
24 StrBuf *Chardata; // XML chardata in between tags is built up here
25 StrBuf *Hrefs; // list of items requested by a `calendar-multiget` REPORT
26 Array *filters; // If the query contains a FILTER stanza, the filter criteria are populated here
27 int filter_nest; // tag nesting level where a FILTER stanza begins
31 // XML parser callback
32 void caldav_xml_start(void *data, const char *el, const char **attr) {
33 struct cr_params *crp = (struct cr_params *) data;
35 #ifdef DEBUG_XML_PARSE
37 syslog(LOG_DEBUG, "<%s>", el);
38 for (int i = 0; attr[i] != NULL; i += 2) {
39 syslog(LOG_DEBUG, "Attribute '%s' = '%s'", attr[i], attr[i + 1]);
44 // RFC4791 7.8 "calendar-query" REPORT - Client will send a lot of search criteria.
45 if (!strcasecmp(el, CAL"calendar-query")) {
46 crp->report_type = cr_calendar_query;
49 // RFC4791 7.9 "calendar-multiget" REPORT - Client will supply a list of specific hrefs.
50 else if (!strcasecmp(el, CAL"calendar-multiget")) {
51 crp->report_type = cr_calendar_multiget;
54 // RFC4791 7.10 "free-busy-query" REPORT
55 else if (!strcasecmp(el, CAL"free-busy-query")) {
56 crp->report_type = cr_freebusy_query;
59 // RFC4791 9.7 create a filter array if this query contains a "filter" stanza
60 else if (!strcasecmp(el, CAL"filter")) {
61 crp->filters = array_new(SIZ);
62 crp->filter_nest = crp->comp_filter_nesting_level;
65 // Handle the filters defined in RFC4791 9.7.1 through 9.7.5
66 else if ( ( (!strcasecmp(el, CAL"comp-filter"))
67 || (!strcasecmp(el, CAL"prop-filter"))
68 || (!strcasecmp(el, CAL"param-filter"))
69 || (!strcasecmp(el, CAL"is-not-defined"))
70 || (!strcasecmp(el, CAL"text-match"))
71 || (!strcasecmp(el, CAL"time-range"))
73 && (crp->filters) // Make sure we actually allocated an array
76 if (!strcasecmp(el, CAL"comp-filter")) {
77 ++crp->comp_filter_nesting_level;
82 int len = snprintf(newfilter, SIZ, "%d|", crp->comp_filter_nesting_level - crp->filter_nest - 1);
83 len += snprintf(&newfilter[len], SIZ-len, "%s", &el[CALLEN]); // filter name without the namespace
85 len += snprintf(&newfilter[len], SIZ-len, "|%s", attr[a++]); // now save the attributes
87 array_append(crp->filters, newfilter);
93 // XML parser callback
94 void caldav_xml_end(void *data, const char *el) {
95 struct cr_params *crp = (struct cr_params *) data;
97 #ifdef DEBUG_XML_PARSE
100 syslog(LOG_DEBUG, "</%s>", el);
104 if (!strcasecmp(el, CAL"comp-filter")) {
105 --crp->comp_filter_nesting_level;
109 if ((!strcasecmp(el, "DAV::href")) || (!strcasecmp(el, "DAV:href"))) {
110 if (crp->Hrefs == NULL) { // append crp->Chardata to crp->Hrefs
111 crp->Hrefs = NewStrBuf();
114 StrBufAppendBufPlain(crp->Hrefs, HKEY("|"), 0);
116 StrBufAppendBuf(crp->Hrefs, crp->Chardata, 0);
119 if (crp->Chardata != NULL) { // Tag is closed; chardata is now out of scope.
120 FreeStrBuf(&crp->Chardata); // Free the buffer.
121 crp->Chardata = NULL;
126 // XML parser callback
127 void caldav_xml_chardata(void *data, const XML_Char *s, int len) {
128 struct cr_params *crp = (struct cr_params *) data;
130 char *app = malloc(len+1);
137 if (crp->Chardata == NULL) {
138 crp->Chardata = NewStrBuf();
141 StrBufAppendBufPlain(crp->Chardata, app, len, 0);
143 #ifdef DEBUG_XML_PARSE
145 string_trim(app); // remove leading/trailing whitespace. ok to mangle it because we've already appended.
146 if (!IsEmptyStr(app)) {
148 syslog(LOG_DEBUG, "%s", app, len);
158 // Called by caldav_report_one_item() to fetch a message (by number) in the current room,
159 // and return only the icalendar data as a StrBuf. Returns NULL if not found.
161 // NOTE: this function expects that "MSGP text/calendar" was issued at the beginning
162 // of a REPORT operation to set our preferred MIME type to calendar data.
163 StrBuf *fetch_ical(struct ctdlsession *c, long msgnum) {
167 ctdl_printf(c, "MSG4 %ld", msgnum);
168 ctdl_readline(c, buf, sizeof(buf));
173 while (ctdl_readline(c, buf, sizeof(buf)), strcmp(buf, "000")) {
174 if (Buf != NULL) { // already in body
175 StrBufAppendPrintf(Buf, "%s\n", buf);
177 else if (IsEmptyStr(buf)) { // beginning of body
186 // Called by multiple REPORT types to actually perform the output in "multiget" format.
187 // We need to already know the source message number and the href, but also already have the output data.
188 void cal_multiget_out(long msgnum, StrBuf *ThisHref, StrBuf *Caldata, StrBuf *ReportOut) {
190 StrBufAppendPrintf(ReportOut, "<D:response>");
191 StrBufAppendPrintf(ReportOut, "<D:href>");
192 StrBufXMLEscAppend(ReportOut, ThisHref, NULL, 0, 0);
193 StrBufAppendPrintf(ReportOut, "</D:href>");
194 StrBufAppendPrintf(ReportOut, "<D:propstat>");
196 if (Caldata != NULL) {
197 // syslog(LOG_DEBUG, "caldav_report_one_item(%s) 200 OK", ChrPtr(ThisHref));
198 StrBufAppendPrintf(ReportOut, "<D:status>");
199 StrBufAppendPrintf(ReportOut, "HTTP/1.1 200 OK");
200 StrBufAppendPrintf(ReportOut, "</D:status>");
201 StrBufAppendPrintf(ReportOut, "<D:prop>");
202 StrBufAppendPrintf(ReportOut, "<D:getetag>");
203 StrBufAppendPrintf(ReportOut, "%ld", msgnum);
204 StrBufAppendPrintf(ReportOut, "</D:getetag>");
205 StrBufAppendPrintf(ReportOut, "<C:calendar-data>");
206 StrBufXMLEscAppend(ReportOut, Caldata, NULL, 0, 0);
207 StrBufAppendPrintf(ReportOut, "</C:calendar-data>");
208 StrBufAppendPrintf(ReportOut, "</D:prop>");
211 // syslog(LOG_DEBUG, "caldav_report_one_item(%s) 404 not found", ChrPtr(ThisHref));
212 StrBufAppendPrintf(ReportOut, "<D:status>");
213 StrBufAppendPrintf(ReportOut, "HTTP/1.1 404 not found");
214 StrBufAppendPrintf(ReportOut, "</D:status>");
217 StrBufAppendPrintf(ReportOut, "</D:propstat>");
218 StrBufAppendPrintf(ReportOut, "</D:response>");
222 // Called by caldav_report() to output a single item.
223 // Our policy is to throw away the list of properties the client asked for, and just send everything.
224 void caldav_report_one_item(struct http_transaction *h, struct ctdlsession *c, StrBuf *ReportOut, StrBuf *ThisHref) {
226 StrBuf *Caldata = NULL;
229 euid = strrchr(ChrPtr(ThisHref), '/');
234 euid = (char *) ChrPtr(ThisHref);
237 char *unescaped_euid = strdup(euid);
238 if (!unescaped_euid) {
241 unescape_input(unescaped_euid);
243 msgnum = locate_message_by_uid(c, unescaped_euid);
244 free(unescaped_euid);
246 Caldata = fetch_ical(c, msgnum);
252 cal_multiget_out(msgnum, ThisHref, Caldata, ReportOut);
254 if (Caldata != NULL) {
255 FreeStrBuf(&Caldata);
260 // Compare function for "time-range" tests (RFC4791 section 9.9)
261 // Returns nonzero if the supplied icalcomponent occurs within the specified time range
262 int caldav_time_range_filter_matches(icalcomponent *cal, char *start_str, char *end_str) {
264 struct icaltimetype start = (
265 (!IsEmptyStr(start_str))
266 ? icaltime_from_string(start_str)
267 : icaltime_from_string("19010101T010101Z")
269 syslog(LOG_DEBUG, " search start: %16s --> \033[36m%s\033[0m", start_str, icaltime_as_ical_string_r(start));
271 struct icaltimetype end = (
272 (!IsEmptyStr(end_str))
273 ? icaltime_from_string(end_str)
274 : icaltime_from_string("99991231T235959Z") // ISO8601 is not Y10K compliant
276 syslog(LOG_DEBUG, " search end: %16s --> \033[36m%s\033[0m", end_str, icaltime_as_ical_string_r(end));
278 // IMPLEMENTATION NOTE:
279 // ical_ctdl_is_overlap() works because icaltime_compare() is really smart.
280 // It looks at the time zone of the dtstart/dtend and can apparently go back up the icalcomponent
281 // hierarchy to find its time zone data. I tested this by creating an event with a fictional
282 // time zone and it did the right thing. It even showed the fictional name to me. This saves us
283 // from having to convert everything to UTC before comparing. Nice!
285 icaltimetype dts = icalcomponent_get_dtstart(cal);
286 syslog(LOG_DEBUG, "component start: \033[36m%s\033[0m", icaltime_as_ical_string_r(dts));
288 icaltimetype dte = icalcomponent_get_dtend(cal);
289 syslog(LOG_DEBUG, "component end: \033[36m%s\033[0m", icaltime_as_ical_string_r(dte));
291 return(ical_ctdl_is_overlap(dts, dte, start, end)); // We have a convenience function for this.
295 // Recursive function to apply CalDAV FILTERS to a calendar item.
296 // Returns zero if the calendar item was disqualified by a filter, nonzero if the calendar item still qualifies.
297 int caldav_apply_filters(void *cal, Array *filters, int apply_at_level) {
299 int f = 0; // filter number iterator
300 int qual = 1; // 0 for disqualify, 1 for qualify
301 int previous_level = -1;
302 int disregard_further_comp_filters = 0;
304 while ( (f<array_len(filters)) && (qual) ) {
306 // Tokenize the filter (a future performance hack would be to pre-tokenize instead of storing delimited strings)
307 char this_filter[SIZ];
308 safestrncpy(this_filter, array_get_element_at(filters, f), sizeof(this_filter));
309 char *t[10] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL } ;
310 char *ft = this_filter;
312 while ( (t[num_tokens]=strtok_r(ft, "|", &ft)) && (num_tokens<10) ) {
315 int this_rule_level = atoi(t[0]);
316 syslog(LOG_DEBUG, "caldav_apply_filters() filter=%d, level=%d, <%s>", f, this_rule_level, array_get_element_at(filters, f) );
318 // Handle the individual filters defined in RFC4791 9.7.1 through 9.7.5
320 if (apply_at_level < previous_level) {
321 syslog(LOG_DEBUG, "caldav: walking back down");
325 else if (this_rule_level != apply_at_level) {
326 syslog(LOG_DEBUG, "caldav: apply_at_level=%d, this_rule_level=%d, skipping this rule", apply_at_level, this_rule_level);
329 else if ( (!strcasecmp(t[1], "comp-filter")) // RFC4791 9.7.1 - filter by component
330 && (!disregard_further_comp_filters) // one is enough to succeed
332 syslog(LOG_DEBUG, "component filter at level %d", this_rule_level);
334 // comp-filter requires exactly one parameter (name="VXXXX")
335 if (num_tokens < 4) {
336 syslog(LOG_DEBUG, "caldav: comp-filter has no parameters - rejecting");
340 // Root element is NOT a component, but the root filter is "comp-filter" -- reject!
341 if ( (!icalcomponent_isa_component(cal)) && (this_rule_level == 0) ) {
342 syslog(LOG_DEBUG, "caldav: root element is not a component, rejecting");
346 // Current element is a component and the filter is "comp-filter" -- see if it matches the requested type
347 if ( (icalcomponent_isa_component(cal))
348 && (!strcasecmp(t[2], "name"))
350 if (icalcomponent_isa(cal) == icalcomponent_string_to_kind(t[3]) ) {
351 syslog(LOG_DEBUG, "caldav: component at level %d is <%s>, looking for <%s>, recursing...",
353 icalcomponent_kind_to_string(icalcomponent_isa(cal)), t[3]
356 // We have a match. Drill down into the subcomponents.
358 icalcomponent *c = NULL;
359 int number_of_subcomponents = 0;
360 int number_of_matches = 0;
361 for ( c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
363 c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)
365 ++number_of_subcomponents;
366 if (caldav_apply_filters(c, filters, apply_at_level+1)) {
367 syslog(LOG_DEBUG, "Subcomponent %d might match", number_of_subcomponents);
371 if (number_of_matches > 0) { // something matched
373 disregard_further_comp_filters = 1;
376 else if (number_of_subcomponents > 0) { // nothing matched
377 return(0); // but only fail if there *were* subcomponents.
382 syslog(LOG_DEBUG, "caldav: component at level %d is <%s>, looking for <%s>, rejecting",
384 icalcomponent_kind_to_string(icalcomponent_isa(cal)),
393 else if (!strcasecmp(t[1], "prop-filter")) { // RFC4791 9.7.2 - filter by property
394 syslog(LOG_DEBUG, "property filter at level %d FIXME not implemented yet", this_rule_level);
397 else if (!strcasecmp(t[1], "param-filter")) { // RFC4791 9.7.3 - filter by parameter
398 syslog(LOG_DEBUG, "parameter filter at level %d FIXME not implemented yet", this_rule_level);
401 else if (!strcasecmp(t[1], "is-not-defined")) { // RFC4791 9.7.4
402 syslog(LOG_DEBUG, "is-not-defined filter at level %d FIXME not implemented yet", this_rule_level);
405 else if (!strcasecmp(t[1], "text-match")) { // RFC4791 9.7.5
406 syslog(LOG_DEBUG, "text match filter at level %d FIXME not implemented yet", this_rule_level);
409 else if (!strcasecmp(t[1], "time-range")) { // RFC4791 9.9
410 syslog(LOG_DEBUG, "time range filter at level %d FIXME not implemented yet", this_rule_level);
411 for (int i=2; (i+1)<num_tokens; i+=2) {
412 char *tr_start = NULL;
414 if (!strcasecmp(t[i], "start")) {
417 else if (!strcasecmp(t[i], "end")) {
420 if (caldav_time_range_filter_matches(cal, tr_start, tr_end)) {
421 syslog(LOG_DEBUG, "time range matches");
424 syslog(LOG_DEBUG, "time range does not match -- rejecting");
433 syslog(LOG_DEBUG, "caldav: we reached the end of level %d , returning %d", apply_at_level, qual);
438 // Called by report_the_room_itself() in room_functions.c when a CalDAV REPORT method
439 // is requested on a calendar room. We fire up an XML Parser to decode the request and
440 // hopefully produce the correct output.
441 void caldav_report(struct http_transaction *h, struct ctdlsession *c) {
442 struct cr_params crp;
445 memset(&crp, 0, sizeof(struct cr_params));
447 XML_Parser xp = XML_ParserCreateNS("UTF-8", ':');
449 syslog(LOG_INFO, "Cannot create XML parser!");
454 XML_SetElementHandler(xp, caldav_xml_start, caldav_xml_end);
455 XML_SetCharacterDataHandler(xp, caldav_xml_chardata);
456 XML_SetUserData(xp, &crp);
457 XML_SetDefaultHandler(xp, NULL); // Disable internal entity expansion to prevent "billion laughs attack"
458 XML_Parse(xp, h->request_body, h->request_body_length, 1);
461 if (crp.Chardata != NULL) { // Discard any trailing chardata ... normally nothing here
462 FreeStrBuf(&crp.Chardata);
466 // We're going to make a lot of MSG4 calls, and the preferred MIME type we want is "text/calendar".
467 // The iCalendar standard is mature now, and we are no longer interested in text/x-vcal or application/ics.
468 ctdl_printf(c, "MSGP text/calendar");
469 ctdl_readline(c, buf, sizeof buf);
471 // Now begin the REPORT.
472 syslog(LOG_DEBUG, "CalDAV REPORT type is: %d", crp.report_type);
473 StrBuf *ReportOut = NewStrBuf();
474 StrBufAppendPrintf(ReportOut,
475 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
478 "xmlns:C=\"urn:ietf:params:xml:ns:caldav\""
482 // RFC4791 7.8 "calendar-query" REPORT - Client will send a lot of search criteria.
483 if (crp.report_type == cr_calendar_query) {
485 Array *msglist = get_msglist(c, "ALL");
486 if (msglist != NULL) {
487 for (i = 0; i < array_len(msglist); ++i) {
489 memcpy(&m, array_get_element_at(msglist, i), sizeof(long));
491 // load and parse one calendar item
492 StrBuf *one_item = fetch_ical(c, m);
493 icalcomponent *cal = icalcomponent_new_from_string(ChrPtr(one_item));
495 // Does this calendar item qualify for output?
498 // If there was a filter stanza, run this calendar item through the filters.
499 syslog(LOG_DEBUG, "Evaluating message \033[33m%ld\033[0m...", m);
500 qualify = caldav_apply_filters(cal, crp.filters, 0);
501 syslog(LOG_DEBUG, "Message %ld %s\033[0m qualify", m, (qualify ? "\033[32mDOES" : "\033[31mDOES NOT"));
502 syslog(LOG_DEBUG, "");
504 // Did this calendar item match the query? If so, output it.
506 // FIXME need to populate the Href instead of NULL
507 cal_multiget_out(m, NULL, one_item, ReportOut);
510 icalcomponent_free(cal);
511 FreeStrBuf(&one_item);
518 // RFC4791 7.9 "calendar-multiget" REPORT - go get the specific Hrefs the client asked for.
519 // Can we move this back into citserver too?
520 else if ( (crp.report_type == cr_calendar_multiget) && (crp.Hrefs != NULL) ) {
522 StrBuf *ThisHref = NewStrBuf();
523 const char *pvset = NULL;
524 while (StrBufExtract_NextToken(ThisHref, crp.Hrefs, &pvset, '|') >= 0) {
525 StrBufTrim(ThisHref); // remove leading/trailing whitespace from the href
526 caldav_report_one_item(h, c, ReportOut, ThisHref);
528 FreeStrBuf(&ThisHref);
531 // RFC4791 7.10 "free-busy-query" REPORT
532 else if (crp.report_type == cr_freebusy_query) {
533 // FIXME build this REPORT. At the moment we send an empty multistatus.
536 // Free any query parameters that might have been allocated during the xml parse
537 if (crp.Hrefs != NULL) {
538 FreeStrBuf(&crp.Hrefs);
542 array_free(crp.filters);
546 StrBufAppendPrintf(ReportOut, "</D:multistatus>\n"); // End the REPORT.
548 add_response_header(h, strdup("Content-type"), strdup("text/xml"));
549 h->response_code = 207;
550 h->response_string = strdup("Multi-Status");
551 h->response_body_length = StrLength(ReportOut);
552 h->response_body = SmashStrBuf(&ReportOut);