I wish much death and suffering to Cyrus Daboo, Lisa M. Dusseault, and Bernard Desrui...
[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 // Shorthand for the XML namespace of CalDAV
8 #define CAL "urn:ietf:params:xml:ns:caldav:"
9 #define CALLEN sizeof(CAL)-1
10
11 // A CalDAV REPORT can only be one type.  This is stored in the report_type member.
12 enum cr_type {
13         cr_calendar_query,
14         cr_calendar_multiget,
15         cr_freebusy_query
16 };
17
18
19 // Data type for CalDAV Report Parameters.
20 // As we slog our way through the XML we learn what the client is asking for
21 // and build up the contents of this data type.
22 struct cr_params {
23         int tag_nesting_level;          // not needed, just kept for pretty-printing
24         enum cr_type report_type;       // which RFC4791 section 7 REPORT are we generating
25         StrBuf *Chardata;               // XML chardata in between tags is built up here
26         StrBuf *Hrefs;                  // list of items requested by a `calendar-multiget` REPORT
27         Array *filters;                 // If the query contains a FILTER stanza, the filter criteria are populated here
28         int filter_nest;                // tag nesting level where a FILTER stanza begins
29 };
30
31
32 // XML parser callback
33 void caldav_xml_start(void *data, const char *el, const char **attr) {
34         struct cr_params *crp = (struct cr_params *) data;
35
36 #ifdef DEBUG_XML_PARSE
37         // logging
38         int i;
39         char indent[256];
40         indent[0] = 0;
41         for (i=0; i<crp->tag_nesting_level; ++i) {
42                 strcat(indent, "  ");
43         }
44         syslog(LOG_DEBUG, "%s<%s>", indent, el);
45 #endif
46         ++crp->tag_nesting_level;
47 #ifdef DEBUG_XML_PARSE
48         indent[0] = 0;
49         for (i=0; i<crp->tag_nesting_level; ++i) {
50                 strcat(indent, "  ");
51         }
52         for (i = 0; attr[i] != NULL; i += 2) {
53                 syslog(LOG_DEBUG, "%sAttribute '%s' = '%s'", indent, attr[i], attr[i + 1]);
54         }
55         // end logging
56 #endif
57
58         // RFC4791 7.8 "calendar-query" REPORT - Client will send a lot of search criteria.
59         if (!strcasecmp(el, CAL"calendar-query")) {
60                 crp->report_type = cr_calendar_query;
61         }
62
63         // RFC4791 7.9 "calendar-multiget" REPORT - Client will supply a list of specific hrefs.
64         else if (!strcasecmp(el, CAL"calendar-multiget")) {
65                 crp->report_type = cr_calendar_multiget;
66         }
67
68         // RFC4791 7.10 "free-busy-query" REPORT
69         else if (!strcasecmp(el, CAL"free-busy-query")) {
70                 crp->report_type = cr_freebusy_query;
71         }
72
73         // RFC4791 9.7 create a filter array if this query contains a "filter" stanza
74         else if (!strcasecmp(el, CAL"filter")) {
75                 crp->filters = array_new(SIZ);
76                 crp->filter_nest = crp->tag_nesting_level;
77         }
78
79         // Handle the filters defined in RFC4791 9.7.1 through 9.7.5
80         else if (       (       (!strcasecmp(el, CAL"comp-filter"))
81                                 || (!strcasecmp(el, CAL"prop-filter"))
82                                 || (!strcasecmp(el, CAL"param-filter"))
83                                 || (!strcasecmp(el, CAL"is-not-defined"))
84                                 || (!strcasecmp(el, CAL"text-match"))
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 // Called by caldav_apply_filters() to apply ONE filter.
277 // Returns 0 if the calendar item does not match the filter.
278 // Returns 1 if the calendar item DOES match the filter.
279 int caldav_apply_one_filter(void *cal, char *filter) {
280         syslog(LOG_DEBUG, "applying filter: %s", filter);
281
282         char this_filter[SIZ];          // we have to copy the filter string because we will destructively tokenize it
283         safestrncpy(this_filter, filter, sizeof(this_filter));
284
285         char *t[10] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL } ;
286         char *f = this_filter;
287         int num_tokens = 0;
288         while ( (t[num_tokens]=strtok_r(f, "|", &f)) && (num_tokens<10) ) {
289                 ++num_tokens;
290         }
291
292         // BEGIN experimental block -- see what happens when we cast to the wrong type
293
294         //icalcomponent *foo_comp = (icalcomponent *) cal;
295         //icalproperty *foo_prop = (icalproperty *) cal;
296         //icalparameter *foo_param = (icalparameter *) cal;
297
298         // END experimental block
299
300         // Handle the individual filters defined in RFC4791 9.7.1 through 9.7.5
301
302         if (!strcasecmp(t[1], "comp-filter")) {                         // RFC4791 9.7.1 - filter by component
303                 syslog(LOG_DEBUG, "component filter FIXME not implemented yet");
304                 if (icalcomponent_isa_component(cal)) {
305                         syslog(LOG_DEBUG, "\033[32m yes this is a component \033[0m");
306                 }
307                 else {
308                         syslog(LOG_DEBUG, "\033[31m no this is not a component \033[0m");
309                 }
310         }
311
312         else if (!strcasecmp(t[1], "prop-filter")) {                    // RFC4791 9.7.2 - filter by property
313                 syslog(LOG_DEBUG, "property filter FIXME not implemented yet");
314         }
315
316         else if (!strcasecmp(t[1], "param-filter")) {                   // RFC4791 9.7.3 - filter by parameter
317                 syslog(LOG_DEBUG, "parameter filter FIXME not implemented yet");
318         }
319
320         else if (!strcasecmp(t[1], "is-not-defined")) {                 // RFC4791 9.7.4
321                 syslog(LOG_DEBUG, "is-not-defined filter FIXME not implemented yet");
322         }
323
324         else if (!strcasecmp(t[1], "text-match")) {                     // RFC4791 9.7.5
325                 syslog(LOG_DEBUG, "text match filter FIXME not implemented yet");
326         }
327
328         return(1);
329 }
330
331
332 // Recursive function to apply CalDAV FILTERS to a calendar item.
333 // Returns zero if the calendar item was disqualified by a filter, nonzero if the calendar item still qualifies.
334 int caldav_apply_filters(void *cal, Array *filters, int index) {
335
336         // Apply *this* filter.
337         if (caldav_apply_one_filter(cal, array_get_element_at(filters, index)) == 0) {
338                 return(0);
339         }
340
341         // If we get to this point, the current filter has passed, and we move on to the next one.
342         if (index < array_len(filters)-1) {
343                 return(caldav_apply_filters(cal, filters, index+1));
344         }
345
346         // If we got this far, every filter passed, and the calendar item qualifies for output.
347         return(1);
348 }
349
350
351 // Called by report_the_room_itself() in room_functions.c when a CalDAV REPORT method
352 // is requested on a calendar room.  We fire up an XML Parser to decode the request and
353 // hopefully produce the correct output.
354 void caldav_report(struct http_transaction *h, struct ctdlsession *c) {
355         struct cr_params crp;
356         char buf[1024];
357
358         memset(&crp, 0, sizeof(struct cr_params));
359
360         XML_Parser xp = XML_ParserCreateNS("UTF-8", ':');
361         if (xp == NULL) {
362                 syslog(LOG_INFO, "Cannot create XML parser!");
363                 do_404(h);
364                 return;
365         }
366
367         XML_SetElementHandler(xp, caldav_xml_start, caldav_xml_end);
368         XML_SetCharacterDataHandler(xp, caldav_xml_chardata);
369         XML_SetUserData(xp, &crp);
370         XML_SetDefaultHandler(xp, NULL);        // Disable internal entity expansion to prevent "billion laughs attack"
371         XML_Parse(xp, h->request_body, h->request_body_length, 1);
372         XML_ParserFree(xp);
373
374         if (crp.Chardata != NULL) {             // Discard any trailing chardata ... normally nothing here
375                 FreeStrBuf(&crp.Chardata);
376                 crp.Chardata = NULL;
377         }
378
379         // We're going to make a lot of MSG4 calls, and the preferred MIME type we want is "text/calendar".
380         // The iCalendar standard is mature now, and we are no longer interested in text/x-vcal or application/ics.
381         ctdl_printf(c, "MSGP text/calendar");
382         ctdl_readline(c, buf, sizeof buf);
383
384         // Now begin the REPORT.
385         syslog(LOG_DEBUG, "CalDAV REPORT type is: %d", crp.report_type);
386         StrBuf *ReportOut = NewStrBuf();
387         StrBufAppendPrintf(ReportOut,
388                 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
389                 "<D:multistatus "
390                 "xmlns:D=\"DAV:\" "
391                 "xmlns:C=\"urn:ietf:params:xml:ns:caldav\""
392                 ">"
393         );
394
395         // RFC4791 7.8 "calendar-query" REPORT - Client will send a lot of search criteria.
396         if (crp.report_type == cr_calendar_query) {
397                 int i = 0;
398                 Array *msglist = get_msglist(c, "ALL");
399                 if (msglist != NULL) {
400                         for (i = 0; i < array_len(msglist); ++i) {
401                                 long m;
402                                 memcpy(&m, array_get_element_at(msglist, i), sizeof(long));
403
404                                 // load and parse one calendar item
405                                 StrBuf *one_item = fetch_ical(c, m);
406                                 icalcomponent *cal = icalcomponent_new_from_string(ChrPtr(one_item));
407
408                                 // Does this calendar item qualify for output?
409                                 int qualify = 1;
410
411                                 // If there was a filter stanza, run this calendar item through the filters.
412                                 qualify = caldav_apply_filters(cal, crp.filters, 0);
413                                 syslog(LOG_DEBUG, "Message %ld does%s qualify", m, (qualify ? "" : " NOT"));
414
415                                 // Did this calendar item match the query?  If so, output it.
416                                 if (qualify) {
417                                         // FIXME need to populate the Href instead of NULL
418                                         cal_multiget_out(m, NULL, one_item, ReportOut);
419                                 }
420
421                                 icalcomponent_free(cal);
422                                 FreeStrBuf(&one_item);
423
424                         }
425                         array_free(msglist);
426                 }
427         }
428
429         // RFC4791 7.9 "calendar-multiget" REPORT - go get the specific Hrefs the client asked for.
430         // Can we move this back into citserver too?
431         else if ( (crp.report_type == cr_calendar_multiget) && (crp.Hrefs != NULL) ) {
432
433                 StrBuf *ThisHref = NewStrBuf();
434                 const char *pvset = NULL;
435                 while (StrBufExtract_NextToken(ThisHref, crp.Hrefs, &pvset, '|') >= 0) {
436                         StrBufTrim(ThisHref);                           // remove leading/trailing whitespace from the href
437                         caldav_report_one_item(h, c, ReportOut, ThisHref);
438                 }
439                 FreeStrBuf(&ThisHref);
440         }
441
442         // RFC4791 7.10 "free-busy-query" REPORT
443         else if (crp.report_type == cr_freebusy_query) {
444                 // FIXME build this REPORT.  At the moment we send an empty multistatus.
445         }
446
447         // Free any query parameters that might have been allocated during the xml parse
448         if (crp.Hrefs != NULL) {
449                 FreeStrBuf(&crp.Hrefs);
450                 crp.Hrefs = NULL;
451         }
452         if (crp.filters) {
453                 array_free(crp.filters);
454                 crp.filters = NULL;
455         }
456
457         StrBufAppendPrintf(ReportOut, "</D:multistatus>\n");            // End the REPORT.
458
459         add_response_header(h, strdup("Content-type"), strdup("text/xml"));
460         h->response_code = 207;
461         h->response_string = strdup("Multi-Status");
462         h->response_body_length = StrLength(ReportOut);
463         h->response_body = SmashStrBuf(&ReportOut);
464 }