0c281efb43554c6f392f1f80f18f13705bff0b4f
[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 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
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         int i;
38         char indent[256];
39         indent[0] = 0;
40         for (i=0; i<crp->tag_nesting_level; ++i) {
41                 strcat(indent, "  ");
42         }
43         syslog(LOG_DEBUG, "%s<%s>", indent, el);
44 #endif
45         ++crp->tag_nesting_level;
46 #ifdef DEBUG_XML_PARSE
47         indent[0] = 0;
48         for (i=0; i<crp->tag_nesting_level; ++i) {
49                 strcat(indent, "  ");
50         }
51         for (i = 0; attr[i] != NULL; i += 2) {
52                 syslog(LOG_DEBUG, "%sAttribute '%s' = '%s'", indent, attr[i], attr[i + 1]);
53         }
54         // end logging
55 #endif
56
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;
60         }
61
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;
65         }
66
67         // RFC4791 7.10 "free-busy-query" REPORT
68         else if (!strcasecmp(el, CAL"free-busy-query")) {
69                 crp->report_type = cr_freebusy_query;
70         }
71
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;
76         }
77
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"))
85                         )
86                         && (crp->filters)                       // Make sure we actually allocated an array
87         ) {
88
89                 char newfilter[SIZ];
90                 int a = 0;
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
93                 while (attr[a]) {
94                         len += snprintf(&newfilter[len], SIZ-len, "|%s", attr[a++]);    // now save the attributes
95                 }
96                 array_append(crp->filters, newfilter);
97         }
98
99 }
100
101
102 // XML parser callback
103 void caldav_xml_end(void *data, const char *el) {
104         struct cr_params *crp = (struct cr_params *) data;
105
106         --crp->tag_nesting_level;
107
108 #ifdef DEBUG_XML_PARSE
109         // logging
110         int i;
111         char indent[256];
112         indent[0] = 0;
113         for (i=0; i<crp->tag_nesting_level; ++i) {
114                 strcat(indent, "  ");
115         }
116         syslog(LOG_DEBUG, "%s</%s>", indent, el);
117         // end logging
118 #endif
119
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();
123                 }
124                 else {
125                         StrBufAppendBufPlain(crp->Hrefs, HKEY("|"), 0);
126                 }
127                 StrBufAppendBuf(crp->Hrefs, crp->Chardata, 0);
128         }
129
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;
133         }
134 }
135
136
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;
140
141         char *app = malloc(len+1);
142         if (!app) {
143                 return;
144         }
145         memcpy(app, s, len);
146         app[len] = 0;
147
148         if (crp->Chardata == NULL) {
149                 crp->Chardata = NewStrBuf();
150         }
151
152         StrBufAppendBufPlain(crp->Chardata, app, len, 0);
153
154 #ifdef DEBUG_XML_PARSE
155         // logging
156         string_trim(app);               // remove leading/trailing whitespace.  ok to mangle it because we've already appended.
157         if (!IsEmptyStr(app)) {
158                 int i;
159                 char indent[256];
160                 indent[0] = 0;
161                 for (i=0; i<crp->tag_nesting_level; ++i) {
162                         strcat(indent, "  ");
163                 }
164                 syslog(LOG_DEBUG, "%s%s", indent, app, len);
165         }
166         // end logging
167 #endif
168
169         free(app);
170         return;
171 }
172
173
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.
176 //
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) {
180         char buf[1024];
181         StrBuf *Buf = NULL;
182
183         ctdl_printf(c, "MSG4 %ld", msgnum);
184         ctdl_readline(c, buf, sizeof(buf));
185         if (buf[0] != '1') {
186                 return NULL;
187         }
188
189         while (ctdl_readline(c, buf, sizeof(buf)), strcmp(buf, "000")) {
190                 if (Buf != NULL) {              // already in body
191                         StrBufAppendPrintf(Buf, "%s\n", buf);
192                 }
193                 else if (IsEmptyStr(buf)) {     // beginning of body
194                         Buf = NewStrBuf();
195                 }
196         }
197
198         return Buf;
199 }
200
201
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) {
205
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>");
211
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>");
225         }
226         else {
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>");
231         }
232
233         StrBufAppendPrintf(ReportOut, "</D:propstat>");
234         StrBufAppendPrintf(ReportOut, "</D:response>");
235 }
236
237
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) {
241         long msgnum;
242         StrBuf *Caldata = NULL;
243         char *euid;
244
245         euid = strrchr(ChrPtr(ThisHref), '/');
246         if (euid != NULL) {
247                 ++euid;
248         }
249         else {
250                 euid = (char *) ChrPtr(ThisHref);
251         }
252
253         char *unescaped_euid = strdup(euid);
254         if (!unescaped_euid) {
255                 return;
256         }
257         unescape_input(unescaped_euid);
258
259         msgnum = locate_message_by_uid(c, unescaped_euid);
260         free(unescaped_euid);
261         if (msgnum > 0) {
262                 Caldata = fetch_ical(c, msgnum);
263         }
264         else {
265                 Caldata = NULL;
266         }
267
268         cal_multiget_out(msgnum, ThisHref, Caldata, ReportOut);
269
270         if (Caldata != NULL) {
271                 FreeStrBuf(&Caldata);
272         }
273 }
274
275
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) {
279
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;
284
285         while ( (f<array_len(filters)) && (qual) ) {
286
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;
292                 int num_tokens = 0;
293                 while ( (t[num_tokens]=strtok_r(ft, "|", &ft)) && (num_tokens<10) ) {
294                         ++num_tokens;
295                 }
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) );
298
299                 // Handle the individual filters defined in RFC4791 9.7.1 through 9.7.5
300
301                 if (apply_at_level < previous_level) {
302                         syslog(LOG_DEBUG, "caldav: walking back down");
303                         return(qual);
304                 }
305
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);
308                 }
309
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);
314
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");
318                                 return(0);
319                         }
320
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"))
324                         ) {
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...",
327                                                 apply_at_level,
328                                                 icalcomponent_kind_to_string(icalcomponent_isa(cal)), t[3]
329                                         );
330
331                                         // We have a match.  Drill down into the subcomponents.
332
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);
337                                                 (c != 0);                                                
338                                                 c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)
339                                         ) {
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);
343                                                         ++number_of_matches;
344                                                 }
345                                         }
346                                         if (number_of_matches > 0) {                    // something matched
347                                                 qual = 1;
348                                                 disregard_further_comp_filters = 1;
349
350                                         }
351                                         else if (number_of_subcomponents > 0) {         // nothing matched
352                                                 return(0);                              // but only fail if there *were* subcomponents.
353                                         }
354
355                                 }
356                                 else {
357                                         syslog(LOG_DEBUG, "caldav: component at level %d is <%s>, looking for <%s>, rejecting",
358                                                 apply_at_level,
359                                                 icalcomponent_kind_to_string(icalcomponent_isa(cal)),
360                                                 t[3]
361                                         );
362                                         return(0);
363                                 }
364                         }
365
366                 }
367
368                 else if (!strcasecmp(t[1], "prop-filter")) {                    // RFC4791 9.7.2 - filter by property
369                         syslog(LOG_DEBUG, "property filter FIXME not implemented yet");
370                 }
371
372                 else if (!strcasecmp(t[1], "param-filter")) {                   // RFC4791 9.7.3 - filter by parameter
373                         syslog(LOG_DEBUG, "parameter filter FIXME not implemented yet");
374                 }
375
376                 else if (!strcasecmp(t[1], "is-not-defined")) {                 // RFC4791 9.7.4
377                         syslog(LOG_DEBUG, "is-not-defined filter FIXME not implemented yet");
378                 }
379
380                 else if (!strcasecmp(t[1], "text-match")) {                     // RFC4791 9.7.5
381                         syslog(LOG_DEBUG, "text match filter FIXME not implemented yet");
382                 }
383
384                 else if (!strcasecmp(t[1], "time-range")) {
385                         syslog(LOG_DEBUG, "time range filter \033[33mFIXME\033[0m not implemented yet");
386                 }
387
388                 ++f;
389         }
390
391         syslog(LOG_DEBUG, "caldav: we reached the end of level %d , returning %d", apply_at_level, qual);
392         return(qual);
393 }
394
395
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;
401         char buf[1024];
402
403         memset(&crp, 0, sizeof(struct cr_params));
404
405         XML_Parser xp = XML_ParserCreateNS("UTF-8", ':');
406         if (xp == NULL) {
407                 syslog(LOG_INFO, "Cannot create XML parser!");
408                 do_404(h);
409                 return;
410         }
411
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);
417         XML_ParserFree(xp);
418
419         if (crp.Chardata != NULL) {             // Discard any trailing chardata ... normally nothing here
420                 FreeStrBuf(&crp.Chardata);
421                 crp.Chardata = NULL;
422         }
423
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);
428
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\"?>"
434                 "<D:multistatus "
435                 "xmlns:D=\"DAV:\" "
436                 "xmlns:C=\"urn:ietf:params:xml:ns:caldav\""
437                 ">"
438         );
439
440         // RFC4791 7.8 "calendar-query" REPORT - Client will send a lot of search criteria.
441         if (crp.report_type == cr_calendar_query) {
442                 int i = 0;
443                 Array *msglist = get_msglist(c, "ALL");
444                 if (msglist != NULL) {
445                         for (i = 0; i < array_len(msglist); ++i) {
446                                 long m;
447                                 memcpy(&m, array_get_element_at(msglist, i), sizeof(long));
448
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));
452
453                                 // Does this calendar item qualify for output?
454                                 int qualify = 1;
455
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, "");
461
462                                 // Did this calendar item match the query?  If so, output it.
463                                 if (qualify) {
464                                         // FIXME need to populate the Href instead of NULL
465                                         cal_multiget_out(m, NULL, one_item, ReportOut);
466                                 }
467
468                                 icalcomponent_free(cal);
469                                 FreeStrBuf(&one_item);
470
471                         }
472                         array_free(msglist);
473                 }
474         }
475
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) ) {
479
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);
485                 }
486                 FreeStrBuf(&ThisHref);
487         }
488
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.
492         }
493
494         // Free any query parameters that might have been allocated during the xml parse
495         if (crp.Hrefs != NULL) {
496                 FreeStrBuf(&crp.Hrefs);
497                 crp.Hrefs = NULL;
498         }
499         if (crp.filters) {
500                 array_free(crp.filters);
501                 crp.filters = NULL;
502         }
503
504         StrBufAppendPrintf(ReportOut, "</D:multistatus>\n");            // End the REPORT.
505
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);
511 }