Defined 19010101T010101Z-99991231T235959Z consts.
[citadel.git] / webcit-ng / server / caldav_reports.c
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.
4
5 #include "webcit.h"
6
7 #define CALDAV "urn:ietf:params:xml:ns:caldav:"         // Shorthand for the XML namespace of CalDAV
8 #define CALDAVLEN sizeof(CALDAV)-1                      // And the length of that string
9
10 const char *the_beginning_of_time       = "19010101T010101Z";
11 const char *the_end_of_time             = "99991231T235959Z";
12
13 // A CalDAV REPORT can only be one type.  This is stored in the report_type member.
14 enum cr_type {
15         cr_calendar_query,
16         cr_calendar_multiget,
17         cr_freebusy_query
18 };
19
20 // Data type for CalDAV Report Parameters.
21 // As we slog our way through the XML we learn what the client is asking for
22 // and build up the contents of this data type.
23 struct cr_params {
24         int comp_filter_nesting_level;
25         enum cr_type report_type;       // which RFC4791 section 7 REPORT are we generating
26         StrBuf *Chardata;               // XML chardata in between tags is built up here
27         StrBuf *Hrefs;                  // list of items requested by a `calendar-multiget` REPORT
28         Array *filters;                 // If the query contains a FILTER stanza, the filter criteria are populated here
29         int filter_nest;                // tag nesting level where a FILTER stanza begins
30 };
31
32
33 // XML parser callback
34 void caldav_xml_start(void *data, const char *el, const char **attr) {
35         struct cr_params *crp = (struct cr_params *) data;
36
37 #ifdef DEBUG_XML_PARSE
38         // logging
39         syslog(LOG_DEBUG, "<%s>", el);
40         for (int i = 0; attr[i] != NULL; i += 2) {
41                 syslog(LOG_DEBUG, "Attribute '%s' = '%s'", attr[i], attr[i + 1]);
42         }
43         // end logging
44 #endif
45
46         // RFC4791 7.8 "calendar-query" REPORT - Client will send a lot of search criteria.
47         if (!strcasecmp(el, CALDAV"calendar-query")) {
48                 crp->report_type = cr_calendar_query;
49         }
50
51         // RFC4791 7.9 "calendar-multiget" REPORT - Client will supply a list of specific hrefs.
52         else if (!strcasecmp(el, CALDAV"calendar-multiget")) {
53                 crp->report_type = cr_calendar_multiget;
54         }
55
56         // RFC4791 7.10 "free-busy-query" REPORT
57         else if (!strcasecmp(el, CALDAV"free-busy-query")) {
58                 crp->report_type = cr_freebusy_query;
59         }
60
61         // RFC4791 9.7 create a filter array if this query contains a "filter" stanza
62         else if (!strcasecmp(el, CALDAV"filter")) {
63                 crp->filters = array_new(SIZ);
64                 crp->filter_nest = crp->comp_filter_nesting_level;
65         }
66
67         // Handle the filters defined in RFC4791 9.7.1 through 9.7.5
68         else if (       (       (!strcasecmp(el, CALDAV"comp-filter"))
69                                 || (!strcasecmp(el, CALDAV"prop-filter"))
70                                 || (!strcasecmp(el, CALDAV"param-filter"))
71                                 || (!strcasecmp(el, CALDAV"is-not-defined"))
72                                 || (!strcasecmp(el, CALDAV"text-match"))
73                                 || (!strcasecmp(el, CALDAV"time-range"))
74                         )
75                         && (crp->filters)                       // Make sure we actually allocated an array
76         ) {
77
78                 if (!strcasecmp(el, CALDAV"comp-filter")) {
79                         ++crp->comp_filter_nesting_level;
80                 }
81
82                 char newfilter[SIZ];
83                 int a = 0;
84                 int len = snprintf(newfilter, SIZ, "%d|", crp->comp_filter_nesting_level - crp->filter_nest - 1);
85                 len += snprintf(&newfilter[len], SIZ-len, "%s", &el[CALDAVLEN]);                // filter name without the namespace
86                 while (attr[a]) {
87                         len += snprintf(&newfilter[len], SIZ-len, "|%s", attr[a++]);    // now save the attributes
88                 }
89                 array_append(crp->filters, newfilter);
90         }
91
92 }
93
94
95 // XML parser callback
96 void caldav_xml_end(void *data, const char *el) {
97         struct cr_params *crp = (struct cr_params *) data;
98
99 #ifdef DEBUG_XML_PARSE
100         // logging
101         int i;
102         syslog(LOG_DEBUG, "</%s>", el);
103         // end logging
104 #endif
105
106         if (!strcasecmp(el, CALDAV"comp-filter")) {
107                 --crp->comp_filter_nesting_level;
108         }
109
110
111         if ((!strcasecmp(el, "DAV::href")) || (!strcasecmp(el, "DAV:href"))) {
112                 if (crp->Hrefs == NULL) {       // append crp->Chardata to crp->Hrefs
113                         crp->Hrefs = NewStrBuf();
114                 }
115                 else {
116                         StrBufAppendBufPlain(crp->Hrefs, HKEY("|"), 0);
117                 }
118                 StrBufAppendBuf(crp->Hrefs, crp->Chardata, 0);
119         }
120
121         if (crp->Chardata != NULL) {            // Tag is closed; chardata is now out of scope.
122                 FreeStrBuf(&crp->Chardata);     // Free the buffer.
123                 crp->Chardata = NULL;
124         }
125 }
126
127
128 // XML parser callback
129 void caldav_xml_chardata(void *data, const XML_Char *s, int len) {
130         struct cr_params *crp = (struct cr_params *) data;
131
132         char *app = malloc(len+1);
133         if (!app) {
134                 return;
135         }
136         memcpy(app, s, len);
137         app[len] = 0;
138
139         if (crp->Chardata == NULL) {
140                 crp->Chardata = NewStrBuf();
141         }
142
143         StrBufAppendBufPlain(crp->Chardata, app, len, 0);
144
145 #ifdef DEBUG_XML_PARSE
146         // logging
147         string_trim(app);               // remove leading/trailing whitespace.  ok to mangle it because we've already appended.
148         if (!IsEmptyStr(app)) {
149                 int i;
150                 syslog(LOG_DEBUG, "%s", app, len);
151         }
152         // end logging
153 #endif
154
155         free(app);
156         return;
157 }
158
159
160 // Called by caldav_report_one_item() to fetch a message (by number) in the current room,
161 // and return only the icalendar data as a StrBuf.  Returns NULL if not found.
162 //
163 // NOTE: this function expects that "MSGP text/calendar" was issued at the beginning
164 // of a REPORT operation to set our preferred MIME type to calendar data.
165 StrBuf *fetch_ical(struct ctdlsession *c, long msgnum) {
166         char buf[1024];
167         StrBuf *Buf = NULL;
168
169         ctdl_printf(c, "MSG4 %ld", msgnum);
170         ctdl_readline(c, buf, sizeof(buf));
171         if (buf[0] != '1') {
172                 return NULL;
173         }
174
175         while (ctdl_readline(c, buf, sizeof(buf)), strcmp(buf, "000")) {
176                 if (Buf != NULL) {              // already in body
177                         StrBufAppendPrintf(Buf, "%s\n", buf);
178                 }
179                 else if (IsEmptyStr(buf)) {     // beginning of body
180                         Buf = NewStrBuf();
181                 }
182         }
183
184         return Buf;
185 }
186
187
188 // Called by multiple REPORT types to actually perform the output in "multiget" format.
189 // We need to already know the source message number and the href, but also already have the output data.
190 void cal_multiget_out(long msgnum, StrBuf *ThisHref, StrBuf *Caldata, StrBuf *ReportOut) {
191
192         StrBufAppendPrintf(ReportOut, "<D:response>");
193         StrBufAppendPrintf(ReportOut, "<D:href>");
194         StrBufXMLEscAppend(ReportOut, ThisHref, NULL, 0, 0);
195         StrBufAppendPrintf(ReportOut, "</D:href>");
196         StrBufAppendPrintf(ReportOut, "<D:propstat>");
197
198         if (Caldata != NULL) {
199                 // syslog(LOG_DEBUG, "caldav_report_one_item(%s) 200 OK", ChrPtr(ThisHref));
200                 StrBufAppendPrintf(ReportOut, "<D:status>");
201                 StrBufAppendPrintf(ReportOut, "HTTP/1.1 200 OK");
202                 StrBufAppendPrintf(ReportOut, "</D:status>");
203                 StrBufAppendPrintf(ReportOut, "<D:prop>");
204                 StrBufAppendPrintf(ReportOut, "<D:getetag>");
205                 StrBufAppendPrintf(ReportOut, "%ld", msgnum);
206                 StrBufAppendPrintf(ReportOut, "</D:getetag>");
207                 StrBufAppendPrintf(ReportOut, "<C:calendar-data>");
208                 StrBufXMLEscAppend(ReportOut, Caldata, NULL, 0, 0);
209                 StrBufAppendPrintf(ReportOut, "</C:calendar-data>");
210                 StrBufAppendPrintf(ReportOut, "</D:prop>");
211         }
212         else {
213                 // syslog(LOG_DEBUG, "caldav_report_one_item(%s) 404 not found", ChrPtr(ThisHref));
214                 StrBufAppendPrintf(ReportOut, "<D:status>");
215                 StrBufAppendPrintf(ReportOut, "HTTP/1.1 404 not found");
216                 StrBufAppendPrintf(ReportOut, "</D:status>");
217         }
218
219         StrBufAppendPrintf(ReportOut, "</D:propstat>");
220         StrBufAppendPrintf(ReportOut, "</D:response>");
221 }
222
223
224 // Called by caldav_report() to output a single item.
225 // Our policy is to throw away the list of properties the client asked for, and just send everything.
226 void caldav_report_one_item(struct http_transaction *h, struct ctdlsession *c, StrBuf *ReportOut, StrBuf *ThisHref) {
227         long msgnum;
228         StrBuf *Caldata = NULL;
229         char *euid;
230
231         euid = strrchr(ChrPtr(ThisHref), '/');
232         if (euid != NULL) {
233                 ++euid;
234         }
235         else {
236                 euid = (char *) ChrPtr(ThisHref);
237         }
238
239         char *unescaped_euid = strdup(euid);
240         if (!unescaped_euid) {
241                 return;
242         }
243         unescape_input(unescaped_euid);
244
245         msgnum = locate_message_by_uid(c, unescaped_euid);
246         free(unescaped_euid);
247         if (msgnum > 0) {
248                 Caldata = fetch_ical(c, msgnum);
249         }
250         else {
251                 Caldata = NULL;
252         }
253
254         cal_multiget_out(msgnum, ThisHref, Caldata, ReportOut);
255
256         if (Caldata != NULL) {
257                 FreeStrBuf(&Caldata);
258         }
259 }
260
261
262 // Compare function for "time-range" tests (RFC4791 section 9.9)
263 // Returns nonzero if the supplied icalcomponent occurs within the specified time range
264 int caldav_time_range_filter_matches(icalcomponent *cal, char *start_str, char *end_str) {
265
266         struct icaltimetype start = icaltime_from_string(start_str);
267         syslog(LOG_DEBUG, "   search start: \033[36m%16s\033[0m (%s)", icaltime_as_ical_string_r(start), icaltime_get_tzid(start));
268
269         struct icaltimetype end = icaltime_from_string(end_str);
270         syslog(LOG_DEBUG, "   search   end: \033[36m%16s\033[0m (%s)", icaltime_as_ical_string_r(end), icaltime_get_tzid(end));
271
272         // IMPLEMENTATION NOTE:
273         // ical_ctdl_is_overlap() works because icaltime_compare() is really smart.
274         // It looks at the time zone of the dtstart/dtend and can apparently go back up the icalcomponent
275         // hierarchy to find its time zone data.  I tested this by creating an event with a fictional
276         // time zone and it did the right thing.  It even showed the fictional name to me.  This saves us
277         // from having to convert everything to UTC before comparing.  Nice!
278
279         icaltimetype dts = icalcomponent_get_dtstart(cal);
280         syslog(LOG_DEBUG, "component start: \033[36m%16s\033[0m (%s)", icaltime_as_ical_string_r(dts), icaltime_get_tzid(dts));
281
282         icaltimetype dte = icalcomponent_get_dtend(cal);
283         syslog(LOG_DEBUG, "component   end: \033[36m%16s\033[0m (%s)", icaltime_as_ical_string_r(dte), icaltime_get_tzid(dte));
284
285         return(ical_ctdl_is_overlap(dts, dte, start, end));     // We have a convenience function for this.
286 }
287
288
289 // Recursive function to apply CalDAV FILTERS to a calendar item.
290 // Returns zero if the calendar item was disqualified by a filter, nonzero if the calendar item still qualifies.
291 int caldav_apply_filters(void *cal, Array *filters, int apply_at_level) {
292
293         int f = 0;                                      // filter number iterator
294         int qual = 1;                                   // 0 for disqualify, 1 for qualify
295         int previous_level = -1;
296         int disregard_further_comp_filters = 0;
297
298         while ( (f<array_len(filters)) && (qual) ) {
299
300                 // Tokenize the filter (a future performance hack would be to pre-tokenize instead of storing delimited strings)
301                 char this_filter[SIZ];
302                 safestrncpy(this_filter, array_get_element_at(filters, f), sizeof(this_filter));
303                 char *t[10] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL } ;
304                 char *ft = this_filter;
305                 int num_tokens = 0;
306                 while ( (t[num_tokens]=strtok_r(ft, "|", &ft)) && (num_tokens<10) ) {
307                         ++num_tokens;
308                 }
309                 int this_rule_level = atoi(t[0]);
310                 syslog(LOG_DEBUG, "caldav_apply_filters() filter=%d, level=%d, <%s>", f, this_rule_level, array_get_element_at(filters, f) );
311
312                 // Handle the individual filters defined in RFC4791 9.7.1 through 9.7.5
313
314                 if (apply_at_level < previous_level) {
315                         syslog(LOG_DEBUG, "caldav: walking back down");
316                         return(qual);
317                 }
318
319                 else if (this_rule_level != apply_at_level) {
320                         syslog(LOG_DEBUG, "caldav: apply_at_level=%d, this_rule_level=%d, skipping this rule", apply_at_level, this_rule_level);
321                 }
322
323                 else if (       (!strcasecmp(t[1], "comp-filter"))              // RFC4791 9.7.1 - filter by component
324                                 && (!disregard_further_comp_filters)            // one is enough to succeed
325                         ) {
326                         syslog(LOG_DEBUG, "component filter at level %d", this_rule_level);
327
328                         // comp-filter requires exactly one parameter (name="VXXXX")
329                         if (num_tokens < 4) {
330                                 syslog(LOG_DEBUG, "caldav: comp-filter has no parameters - rejecting");
331                                 return(0);
332                         }
333
334                         // Root element is NOT a component, but the root filter is "comp-filter" -- reject!
335                         if ( (!icalcomponent_isa_component(cal)) && (this_rule_level == 0) ) {
336                                 syslog(LOG_DEBUG, "caldav: root element is not a component, rejecting");
337                                 return(0);
338                         }
339
340                         // Current element is a component and the filter is "comp-filter" -- see if it matches the requested type
341                         if (    (icalcomponent_isa_component(cal))
342                                 && (!strcasecmp(t[2], "name"))
343                         ) {
344                                 if (icalcomponent_isa(cal) == icalcomponent_string_to_kind(t[3]) ) {
345                                         syslog(LOG_DEBUG, "caldav: component at level %d is <%s>, looking for <%s>, recursing...",
346                                                 apply_at_level,
347                                                 icalcomponent_kind_to_string(icalcomponent_isa(cal)), t[3]
348                                         );
349
350                                         // We have a match.  Drill down into the subcomponents.
351
352                                         icalcomponent *c = NULL;
353                                         int number_of_subcomponents = 0;
354                                         int number_of_matches = 0;
355                                         for (   c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
356                                                 (c != 0);                                                
357                                                 c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)
358                                         ) {
359                                                 ++number_of_subcomponents;
360                                                 if (caldav_apply_filters(c, filters, apply_at_level+1)) {
361                                                         syslog(LOG_DEBUG, "Subcomponent %d might match", number_of_subcomponents);
362                                                         ++number_of_matches;
363                                                 }
364                                         }
365                                         if (number_of_matches > 0) {                    // something matched
366                                                 qual = 1;
367                                                 disregard_further_comp_filters = 1;
368
369                                         }
370                                         else if (number_of_subcomponents > 0) {         // nothing matched
371                                                 return(0);                              // but only fail if there *were* subcomponents.
372                                         }
373
374                                 }
375                                 else {
376                                         syslog(LOG_DEBUG, "caldav: component at level %d is <%s>, looking for <%s>, rejecting",
377                                                 apply_at_level,
378                                                 icalcomponent_kind_to_string(icalcomponent_isa(cal)),
379                                                 t[3]
380                                         );
381                                         return(0);
382                                 }
383                         }
384
385                 }
386
387                 else if (!strcasecmp(t[1], "prop-filter")) {                    // RFC4791 9.7.2 - filter by property
388                         syslog(LOG_DEBUG, "property filter at level %d FIXME not implemented yet", this_rule_level);
389                 }
390
391                 else if (!strcasecmp(t[1], "param-filter")) {                   // RFC4791 9.7.3 - filter by parameter
392                         syslog(LOG_DEBUG, "parameter filter at level %d FIXME not implemented yet", this_rule_level);
393                 }
394
395                 else if (!strcasecmp(t[1], "is-not-defined")) {                 // RFC4791 9.7.4
396                         syslog(LOG_DEBUG, "is-not-defined filter at level %d FIXME not implemented yet", this_rule_level);
397                 }
398
399                 else if (!strcasecmp(t[1], "text-match")) {                     // RFC4791 9.7.5
400                         syslog(LOG_DEBUG, "text match filter at level %d FIXME not implemented yet", this_rule_level);
401                 }
402
403                 else if (!strcasecmp(t[1], "time-range")) {                     // RFC4791 9.9
404                         syslog(LOG_DEBUG, "time range filter at level %d FIXME add recur", this_rule_level);
405                         for (int i=2; (i+1)<num_tokens; i+=2) {
406                                 char *tr_start  = (char *)the_beginning_of_time;        // default if not specified
407                                 char *tr_end    = (char *)the_end_of_time;              // default if not specified
408                                 if (!strcasecmp(t[i], "start")) {
409                                         tr_start = t[i+1];
410                                 }
411                                 else if (!strcasecmp(t[i], "end")) {
412                                         tr_end = t[i+1];
413                                 }
414                                 if (caldav_time_range_filter_matches(cal, tr_start, tr_end)) {
415                                         syslog(LOG_DEBUG, "time range matches");
416                                 }
417                                 else {
418                                         syslog(LOG_DEBUG, "time range does not match -- rejecting");
419                                         qual = 0;
420                                 }
421                         }
422                 }
423
424                 ++f;
425         }
426
427         syslog(LOG_DEBUG, "caldav: we reached the end of level %d , returning %d", apply_at_level, qual);
428         return(qual);
429 }
430
431
432 // Called by report_the_room_itself() in room_functions.c when a CalDAV REPORT method
433 // is requested on a calendar room.  We fire up an XML Parser to decode the request and
434 // hopefully produce the correct output.
435 void caldav_report(struct http_transaction *h, struct ctdlsession *c) {
436         struct cr_params crp;
437         char buf[1024];
438
439         memset(&crp, 0, sizeof(struct cr_params));
440
441         XML_Parser xp = XML_ParserCreateNS("UTF-8", ':');
442         if (xp == NULL) {
443                 syslog(LOG_INFO, "Cannot create XML parser!");
444                 do_404(h);
445                 return;
446         }
447
448         XML_SetElementHandler(xp, caldav_xml_start, caldav_xml_end);
449         XML_SetCharacterDataHandler(xp, caldav_xml_chardata);
450         XML_SetUserData(xp, &crp);
451         XML_SetDefaultHandler(xp, NULL);        // Disable internal entity expansion to prevent "billion laughs attack"
452         XML_Parse(xp, h->request_body, h->request_body_length, 1);
453         XML_ParserFree(xp);
454
455         if (crp.Chardata != NULL) {             // Discard any trailing chardata ... normally nothing here
456                 FreeStrBuf(&crp.Chardata);
457                 crp.Chardata = NULL;
458         }
459
460         // We're going to make a lot of MSG4 calls, and the preferred MIME type we want is "text/calendar".
461         // The iCalendar standard is mature now, and we are no longer interested in text/x-vcal or application/ics.
462         ctdl_printf(c, "MSGP text/calendar");
463         ctdl_readline(c, buf, sizeof buf);
464
465         // Now begin the REPORT.
466         syslog(LOG_DEBUG, "CalDAV REPORT type is: %d", crp.report_type);
467         StrBuf *ReportOut = NewStrBuf();
468         StrBufAppendPrintf(ReportOut,
469                 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
470                 "<D:multistatus "
471                 "xmlns:D=\"DAV:\" "
472                 "xmlns:C=\"urn:ietf:params:xml:ns:caldav\""
473                 ">"
474         );
475
476         // RFC4791 7.8 "calendar-query" REPORT - Client will send a lot of search criteria.
477         if (crp.report_type == cr_calendar_query) {
478                 int i = 0;
479                 Array *msglist = get_msglist(c, "ALL");
480                 if (msglist != NULL) {
481                         for (i = 0; i < array_len(msglist); ++i) {
482                                 long m;
483                                 memcpy(&m, array_get_element_at(msglist, i), sizeof(long));
484
485                                 // load and parse one calendar item
486                                 StrBuf *one_item = fetch_ical(c, m);
487                                 icalcomponent *cal = icalcomponent_new_from_string(ChrPtr(one_item));
488
489                                 // Does this calendar item qualify for output?
490                                 int qualify = 1;
491
492                                 // If there was a filter stanza, run this calendar item through the filters.
493                                 syslog(LOG_DEBUG, "Evaluating message \033[33m%ld\033[0m...", m);
494                                 qualify = caldav_apply_filters(cal, crp.filters, 0);
495                                 syslog(LOG_DEBUG, "Message %ld %s\033[0m qualify", m, (qualify ? "\033[32mDOES" : "\033[31mDOES NOT"));
496                                 syslog(LOG_DEBUG, "");
497
498                                 // Did this calendar item match the query?  If so, output it.
499                                 if (qualify) {
500                                         // FIXME need to populate the Href instead of NULL
501                                         cal_multiget_out(m, NULL, one_item, ReportOut);
502                                 }
503
504                                 icalcomponent_free(cal);
505                                 FreeStrBuf(&one_item);
506
507                         }
508                         array_free(msglist);
509                 }
510         }
511
512         // RFC4791 7.9 "calendar-multiget" REPORT - go get the specific Hrefs the client asked for.
513         // Can we move this back into citserver too?
514         else if ( (crp.report_type == cr_calendar_multiget) && (crp.Hrefs != NULL) ) {
515
516                 StrBuf *ThisHref = NewStrBuf();
517                 const char *pvset = NULL;
518                 while (StrBufExtract_NextToken(ThisHref, crp.Hrefs, &pvset, '|') >= 0) {
519                         StrBufTrim(ThisHref);                           // remove leading/trailing whitespace from the href
520                         caldav_report_one_item(h, c, ReportOut, ThisHref);
521                 }
522                 FreeStrBuf(&ThisHref);
523         }
524
525         // RFC4791 7.10 "free-busy-query" REPORT
526         else if (crp.report_type == cr_freebusy_query) {
527                 // FIXME build this REPORT.  At the moment we send an empty multistatus.
528         }
529
530         // Free any query parameters that might have been allocated during the xml parse
531         if (crp.Hrefs != NULL) {
532                 FreeStrBuf(&crp.Hrefs);
533                 crp.Hrefs = NULL;
534         }
535         if (crp.filters) {
536                 array_free(crp.filters);
537                 crp.filters = NULL;
538         }
539
540         StrBufAppendPrintf(ReportOut, "</D:multistatus>\n");            // End the REPORT.
541
542         add_response_header(h, strdup("Content-type"), strdup("text/xml"));
543         h->response_code = 207;
544         h->response_string = strdup("Multi-Status");
545         h->response_body_length = StrLength(ReportOut);
546         h->response_body = SmashStrBuf(&ReportOut);
547 }