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