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 tag_nesting_level; // not needed, just kept for pretty-printing
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
40 for (i=0; i<crp->tag_nesting_level; ++i) {
43 syslog(LOG_DEBUG, "%s<%s>", indent, el);
45 ++crp->tag_nesting_level;
46 #ifdef DEBUG_XML_PARSE
48 for (i=0; i<crp->tag_nesting_level; ++i) {
51 for (i = 0; attr[i] != NULL; i += 2) {
52 syslog(LOG_DEBUG, "%sAttribute '%s' = '%s'", indent, attr[i], attr[i + 1]);
57 // RFC4791 7.8 "calendar-query" REPORT - Client will send a lot of search criteria.
58 if (!strcasecmp(el, CAL"calendar-query")) {
59 crp->report_type = cr_calendar_query;
62 // RFC4791 7.9 "calendar-multiget" REPORT - Client will supply a list of specific hrefs.
63 else if (!strcasecmp(el, CAL"calendar-multiget")) {
64 crp->report_type = cr_calendar_multiget;
67 // RFC4791 7.10 "free-busy-query" REPORT
68 else if (!strcasecmp(el, CAL"free-busy-query")) {
69 crp->report_type = cr_freebusy_query;
72 // RFC4791 9.7 create a filter array if this query contains a "filter" stanza
73 else if (!strcasecmp(el, CAL"filter")) {
74 crp->filters = array_new(SIZ);
75 crp->filter_nest = crp->tag_nesting_level;
78 // Handle the filters defined in RFC4791 9.7.1 through 9.7.5
79 else if ( ( (!strcasecmp(el, CAL"comp-filter"))
80 || (!strcasecmp(el, CAL"prop-filter"))
81 || (!strcasecmp(el, CAL"param-filter"))
82 || (!strcasecmp(el, CAL"is-not-defined"))
83 || (!strcasecmp(el, CAL"text-match"))
84 || (!strcasecmp(el, CAL"time-range"))
86 && (crp->filters) // Make sure we actually allocated an array
91 int len = snprintf(newfilter, SIZ, "%d|", crp->tag_nesting_level - crp->filter_nest - 1);
92 len += snprintf(&newfilter[len], SIZ-len, "%s", &el[CALLEN]); // filter name without the namespace
94 len += snprintf(&newfilter[len], SIZ-len, "|%s", attr[a++]); // now save the attributes
96 array_append(crp->filters, newfilter);
102 // XML parser callback
103 void caldav_xml_end(void *data, const char *el) {
104 struct cr_params *crp = (struct cr_params *) data;
106 --crp->tag_nesting_level;
108 #ifdef DEBUG_XML_PARSE
113 for (i=0; i<crp->tag_nesting_level; ++i) {
116 syslog(LOG_DEBUG, "%s</%s>", indent, el);
120 if ((!strcasecmp(el, "DAV::href")) || (!strcasecmp(el, "DAV:href"))) {
121 if (crp->Hrefs == NULL) { // append crp->Chardata to crp->Hrefs
122 crp->Hrefs = NewStrBuf();
125 StrBufAppendBufPlain(crp->Hrefs, HKEY("|"), 0);
127 StrBufAppendBuf(crp->Hrefs, crp->Chardata, 0);
130 if (crp->Chardata != NULL) { // Tag is closed; chardata is now out of scope.
131 FreeStrBuf(&crp->Chardata); // Free the buffer.
132 crp->Chardata = NULL;
137 // XML parser callback
138 void caldav_xml_chardata(void *data, const XML_Char *s, int len) {
139 struct cr_params *crp = (struct cr_params *) data;
141 char *app = malloc(len+1);
148 if (crp->Chardata == NULL) {
149 crp->Chardata = NewStrBuf();
152 StrBufAppendBufPlain(crp->Chardata, app, len, 0);
154 #ifdef DEBUG_XML_PARSE
156 string_trim(app); // remove leading/trailing whitespace. ok to mangle it because we've already appended.
157 if (!IsEmptyStr(app)) {
161 for (i=0; i<crp->tag_nesting_level; ++i) {
164 syslog(LOG_DEBUG, "%s%s", indent, app, len);
174 // Called by caldav_report_one_item() to fetch a message (by number) in the current room,
175 // and return only the icalendar data as a StrBuf. Returns NULL if not found.
177 // NOTE: this function expects that "MSGP text/calendar" was issued at the beginning
178 // of a REPORT operation to set our preferred MIME type to calendar data.
179 StrBuf *fetch_ical(struct ctdlsession *c, long msgnum) {
183 ctdl_printf(c, "MSG4 %ld", msgnum);
184 ctdl_readline(c, buf, sizeof(buf));
189 while (ctdl_readline(c, buf, sizeof(buf)), strcmp(buf, "000")) {
190 if (Buf != NULL) { // already in body
191 StrBufAppendPrintf(Buf, "%s\n", buf);
193 else if (IsEmptyStr(buf)) { // beginning of body
202 // Called by multiple REPORT types to actually perform the output in "multiget" format.
203 // We need to already know the source message number and the href, but also already have the output data.
204 void cal_multiget_out(long msgnum, StrBuf *ThisHref, StrBuf *Caldata, StrBuf *ReportOut) {
206 StrBufAppendPrintf(ReportOut, "<D:response>");
207 StrBufAppendPrintf(ReportOut, "<D:href>");
208 StrBufXMLEscAppend(ReportOut, ThisHref, NULL, 0, 0);
209 StrBufAppendPrintf(ReportOut, "</D:href>");
210 StrBufAppendPrintf(ReportOut, "<D:propstat>");
212 if (Caldata != NULL) {
213 // syslog(LOG_DEBUG, "caldav_report_one_item(%s) 200 OK", ChrPtr(ThisHref));
214 StrBufAppendPrintf(ReportOut, "<D:status>");
215 StrBufAppendPrintf(ReportOut, "HTTP/1.1 200 OK");
216 StrBufAppendPrintf(ReportOut, "</D:status>");
217 StrBufAppendPrintf(ReportOut, "<D:prop>");
218 StrBufAppendPrintf(ReportOut, "<D:getetag>");
219 StrBufAppendPrintf(ReportOut, "%ld", msgnum);
220 StrBufAppendPrintf(ReportOut, "</D:getetag>");
221 StrBufAppendPrintf(ReportOut, "<C:calendar-data>");
222 StrBufXMLEscAppend(ReportOut, Caldata, NULL, 0, 0);
223 StrBufAppendPrintf(ReportOut, "</C:calendar-data>");
224 StrBufAppendPrintf(ReportOut, "</D:prop>");
227 // syslog(LOG_DEBUG, "caldav_report_one_item(%s) 404 not found", ChrPtr(ThisHref));
228 StrBufAppendPrintf(ReportOut, "<D:status>");
229 StrBufAppendPrintf(ReportOut, "HTTP/1.1 404 not found");
230 StrBufAppendPrintf(ReportOut, "</D:status>");
233 StrBufAppendPrintf(ReportOut, "</D:propstat>");
234 StrBufAppendPrintf(ReportOut, "</D:response>");
238 // Called by caldav_report() to output a single item.
239 // Our policy is to throw away the list of properties the client asked for, and just send everything.
240 void caldav_report_one_item(struct http_transaction *h, struct ctdlsession *c, StrBuf *ReportOut, StrBuf *ThisHref) {
242 StrBuf *Caldata = NULL;
245 euid = strrchr(ChrPtr(ThisHref), '/');
250 euid = (char *) ChrPtr(ThisHref);
253 char *unescaped_euid = strdup(euid);
254 if (!unescaped_euid) {
257 unescape_input(unescaped_euid);
259 msgnum = locate_message_by_uid(c, unescaped_euid);
260 free(unescaped_euid);
262 Caldata = fetch_ical(c, msgnum);
268 cal_multiget_out(msgnum, ThisHref, Caldata, ReportOut);
270 if (Caldata != NULL) {
271 FreeStrBuf(&Caldata);
276 // Recursive function to apply CalDAV FILTERS to a calendar item.
277 // Returns zero if the calendar item was disqualified by a filter, nonzero if the calendar item still qualifies.
278 int caldav_apply_filters(void *cal, Array *filters, int apply_at_level) {
280 int f = 0; // filter number iterator
281 int qual = 1; // 0 for disqualify, 1 for qualify
282 int previous_level = -1;
283 int disregard_further_comp_filters = 0;
285 while ( (f<array_len(filters)) && (qual) ) {
287 // Tokenize the filter (a future performance hack would be to pre-tokenize instead of storing delimited strings)
288 char this_filter[SIZ];
289 safestrncpy(this_filter, array_get_element_at(filters, f), sizeof(this_filter));
290 char *t[10] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL } ;
291 char *ft = this_filter;
293 while ( (t[num_tokens]=strtok_r(ft, "|", &ft)) && (num_tokens<10) ) {
296 int this_rule_level = atoi(t[0]);
297 syslog(LOG_DEBUG, "caldav_apply_filters() filter=%d, level=%d, <%s>", f, this_rule_level, array_get_element_at(filters, f) );
299 // Handle the individual filters defined in RFC4791 9.7.1 through 9.7.5
301 if (apply_at_level < previous_level) {
302 syslog(LOG_DEBUG, "caldav: walking back down");
306 else if (this_rule_level != apply_at_level) {
307 syslog(LOG_DEBUG, "caldav: apply_at_level=%d, this_rule_level=%d, skipping this rule", apply_at_level, this_rule_level);
310 else if ( (!strcasecmp(t[1], "comp-filter"))
311 && (!disregard_further_comp_filters)
312 ) { // RFC4791 9.7.1 - filter by component
313 syslog(LOG_DEBUG, "component filter at level %d", this_rule_level);
315 // Root element is NOT a component, but the root filter is "comp-filter" -- reject!
316 if ( (!icalcomponent_isa_component(cal)) && (this_rule_level == 0) ) {
317 syslog(LOG_DEBUG, "caldav: root element is not a component, rejecting");
321 // Current element is a component and the filter is "comp-filter" -- see if it matches the requested type
322 if ( (icalcomponent_isa_component(cal))
323 && (!strcasecmp(t[2], "name"))
325 if (icalcomponent_isa(cal) == icalcomponent_string_to_kind(t[3]) ) {
326 syslog(LOG_DEBUG, "caldav: component at level %d is <%s>, looking for <%s>, recursing...",
328 icalcomponent_kind_to_string(icalcomponent_isa(cal)), t[3]
331 // We have a match. Drill down into the subcomponents.
333 icalcomponent *c = NULL;
334 int number_of_subcomponents = 0;
335 int number_of_matches = 0;
336 for ( c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
338 c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)
340 ++number_of_subcomponents;
341 if (caldav_apply_filters(c, filters, apply_at_level+1)) {
342 syslog(LOG_DEBUG, "Subcomponent %d might match", number_of_subcomponents);
346 if (number_of_matches > 0) { // something matched
348 disregard_further_comp_filters = 1;
351 else if (number_of_subcomponents > 0) { // nothing matched
352 return(0); // but only fail if there *were* subcomponents.
357 syslog(LOG_DEBUG, "caldav: component at level %d is <%s>, looking for <%s>, rejecting",
359 icalcomponent_kind_to_string(icalcomponent_isa(cal)),
368 else if (!strcasecmp(t[1], "prop-filter")) { // RFC4791 9.7.2 - filter by property
369 syslog(LOG_DEBUG, "property filter at level %d FIXME not implemented yet", this_rule_level);
372 else if (!strcasecmp(t[1], "param-filter")) { // RFC4791 9.7.3 - filter by parameter
373 syslog(LOG_DEBUG, "parameter filter at level %d FIXME not implemented yet", this_rule_level);
376 else if (!strcasecmp(t[1], "is-not-defined")) { // RFC4791 9.7.4
377 syslog(LOG_DEBUG, "is-not-defined filter at level %d FIXME not implemented yet", this_rule_level);
380 else if (!strcasecmp(t[1], "text-match")) { // RFC4791 9.7.5
381 syslog(LOG_DEBUG, "text match filter at level %d FIXME not implemented yet", this_rule_level);
384 else if (!strcasecmp(t[1], "time-range")) {
385 syslog(LOG_DEBUG, "time range filter at level %d FIXME not implemented yet", this_rule_level);
391 syslog(LOG_DEBUG, "caldav: we reached the end of level %d , returning %d", apply_at_level, qual);
396 // Called by report_the_room_itself() in room_functions.c when a CalDAV REPORT method
397 // is requested on a calendar room. We fire up an XML Parser to decode the request and
398 // hopefully produce the correct output.
399 void caldav_report(struct http_transaction *h, struct ctdlsession *c) {
400 struct cr_params crp;
403 memset(&crp, 0, sizeof(struct cr_params));
405 XML_Parser xp = XML_ParserCreateNS("UTF-8", ':');
407 syslog(LOG_INFO, "Cannot create XML parser!");
412 XML_SetElementHandler(xp, caldav_xml_start, caldav_xml_end);
413 XML_SetCharacterDataHandler(xp, caldav_xml_chardata);
414 XML_SetUserData(xp, &crp);
415 XML_SetDefaultHandler(xp, NULL); // Disable internal entity expansion to prevent "billion laughs attack"
416 XML_Parse(xp, h->request_body, h->request_body_length, 1);
419 if (crp.Chardata != NULL) { // Discard any trailing chardata ... normally nothing here
420 FreeStrBuf(&crp.Chardata);
424 // We're going to make a lot of MSG4 calls, and the preferred MIME type we want is "text/calendar".
425 // The iCalendar standard is mature now, and we are no longer interested in text/x-vcal or application/ics.
426 ctdl_printf(c, "MSGP text/calendar");
427 ctdl_readline(c, buf, sizeof buf);
429 // Now begin the REPORT.
430 syslog(LOG_DEBUG, "CalDAV REPORT type is: %d", crp.report_type);
431 StrBuf *ReportOut = NewStrBuf();
432 StrBufAppendPrintf(ReportOut,
433 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
436 "xmlns:C=\"urn:ietf:params:xml:ns:caldav\""
440 // RFC4791 7.8 "calendar-query" REPORT - Client will send a lot of search criteria.
441 if (crp.report_type == cr_calendar_query) {
443 Array *msglist = get_msglist(c, "ALL");
444 if (msglist != NULL) {
445 for (i = 0; i < array_len(msglist); ++i) {
447 memcpy(&m, array_get_element_at(msglist, i), sizeof(long));
449 // load and parse one calendar item
450 StrBuf *one_item = fetch_ical(c, m);
451 icalcomponent *cal = icalcomponent_new_from_string(ChrPtr(one_item));
453 // Does this calendar item qualify for output?
456 // If there was a filter stanza, run this calendar item through the filters.
457 syslog(LOG_DEBUG, "Evaluating message \033[33m%ld\033[0m...", m);
458 qualify = caldav_apply_filters(cal, crp.filters, 0);
459 syslog(LOG_DEBUG, "Message %ld %s\033[0m qualify", m, (qualify ? "\033[32mDOES" : "\033[31mDOES NOT"));
460 syslog(LOG_DEBUG, "");
462 // Did this calendar item match the query? If so, output it.
464 // FIXME need to populate the Href instead of NULL
465 cal_multiget_out(m, NULL, one_item, ReportOut);
468 icalcomponent_free(cal);
469 FreeStrBuf(&one_item);
476 // RFC4791 7.9 "calendar-multiget" REPORT - go get the specific Hrefs the client asked for.
477 // Can we move this back into citserver too?
478 else if ( (crp.report_type == cr_calendar_multiget) && (crp.Hrefs != NULL) ) {
480 StrBuf *ThisHref = NewStrBuf();
481 const char *pvset = NULL;
482 while (StrBufExtract_NextToken(ThisHref, crp.Hrefs, &pvset, '|') >= 0) {
483 StrBufTrim(ThisHref); // remove leading/trailing whitespace from the href
484 caldav_report_one_item(h, c, ReportOut, ThisHref);
486 FreeStrBuf(&ThisHref);
489 // RFC4791 7.10 "free-busy-query" REPORT
490 else if (crp.report_type == cr_freebusy_query) {
491 // FIXME build this REPORT. At the moment we send an empty multistatus.
494 // Free any query parameters that might have been allocated during the xml parse
495 if (crp.Hrefs != NULL) {
496 FreeStrBuf(&crp.Hrefs);
500 array_free(crp.filters);
504 StrBufAppendPrintf(ReportOut, "</D:multistatus>\n"); // End the REPORT.
506 add_response_header(h, strdup("Content-type"), strdup("text/xml"));
507 h->response_code = 207;
508 h->response_string = strdup("Multi-Status");
509 h->response_body_length = StrLength(ReportOut);
510 h->response_body = SmashStrBuf(&ReportOut);