9c0fe32a004d8bdd987e372e02de4f2d9adf53bf
[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 };
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         lor (i=0; i<crp->tag_nesting_level; ++i) {
41                 strcat(indent, "  ");
42         }
43         syslog(LOG_DEBUG, "%s<%s>", indent, el);
44         ++crp->tag_nesting_level;
45         indent[0] = 0;
46         for (i=0; i<crp->tag_nesting_level; ++i) {
47                 strcat(indent, "  ");
48         }
49         for (i = 0; attr[i] != NULL; i += 2) {
50                 syslog(LOG_DEBUG, "%sAttribute '%s' = '%s'", indent, attr[i], attr[i + 1]);
51         }
52         // end logging
53 #endif
54
55         // RFC4791 7.8 "calendar-query" REPORT - Client will send a lot of search criteria.
56         if (!strcasecmp(el, CAL"calendar-query")) {
57                 crp->report_type = cr_calendar_query;
58         }
59
60         // RFC4791 7.9 "calendar-multiget" REPORT - Client will supply a list of specific hrefs.
61         else if (!strcasecmp(el, CAL"calendar-multiget")) {
62                 crp->report_type = cr_calendar_multiget;
63         }
64
65         // RFC4791 7.10 "free-busy-query" REPORT
66         else if (!strcasecmp(el, CAL"free-busy-query")) {
67                 crp->report_type = cr_freebusy_query;
68         }
69
70         // RFC4791 9.7 create a filter array if this query contains a "filter" stanza
71         else if (!strcasecmp(el, CAL"filter")) {
72                 crp->filters = array_new(SIZ);
73         }
74
75         // Handle the filters defined in RFC4791 9.7.1 through 9.7.5
76         else if (       (       (!strcasecmp(el, CAL"comp-filter"))
77                                 || (!strcasecmp(el, CAL"prop-filter"))
78                                 || (!strcasecmp(el, CAL"param-filter"))
79                                 || (!strcasecmp(el, CAL"is-not-defined"))
80                                 || (!strcasecmp(el, CAL"text-match"))
81                         )
82                         && (crp->filters)                       // Make sure we actually allocated an array
83         ) {
84                 char newfilter[SIZ];
85                 int a = 0;
86                 int len = snprintf(newfilter, SIZ, &el[CALLEN]);        // strip off the namespace for our purposes
87                 while (attr[a]) {
88                         len += snprintf(&newfilter[len], SIZ-len, "|%s", attr[a++]);    // now save the attributes
89                 }
90                 array_append(crp->filters, newfilter);
91         }
92
93 }
94
95
96 // XML parser callback
97 void caldav_xml_end(void *data, const char *el) {
98         struct cr_params *crp = (struct cr_params *) data;
99
100         --crp->tag_nesting_level;
101
102 #ifdef DEBUG_XML_PARSE
103         // logging
104         int i;
105         char indent[256];
106         indent[0] = 0;
107         for (i=0; i<crp->tag_nesting_level; ++i) {
108                 strcat(indent, "  ");
109         }
110         syslog(LOG_DEBUG, "%s</%s>", indent, el);
111         // end logging
112 #endif
113
114         if ((!strcasecmp(el, "DAV::href")) || (!strcasecmp(el, "DAV:href"))) {
115                 if (crp->Hrefs == NULL) {       // append crp->Chardata to crp->Hrefs
116                         crp->Hrefs = NewStrBuf();
117                 }
118                 else {
119                         StrBufAppendBufPlain(crp->Hrefs, HKEY("|"), 0);
120                 }
121                 StrBufAppendBuf(crp->Hrefs, crp->Chardata, 0);
122         }
123
124         if (crp->Chardata != NULL) {            // Tag is closed; chardata is now out of scope.
125                 FreeStrBuf(&crp->Chardata);     // Free the buffer.
126                 crp->Chardata = NULL;
127         }
128 }
129
130
131 // XML parser callback
132 void caldav_xml_chardata(void *data, const XML_Char *s, int len) {
133         struct cr_params *crp = (struct cr_params *) data;
134
135         char *app = malloc(len+1);
136         if (!app) {
137                 return;
138         }
139         memcpy(app, s, len);
140         app[len] = 0;
141
142         if (crp->Chardata == NULL) {
143                 crp->Chardata = NewStrBuf();
144         }
145
146         StrBufAppendBufPlain(crp->Chardata, app, len, 0);
147
148 #ifdef DEBUG_XML_PARSE
149         // logging
150         string_trim(app);               // remove leading/trailing whitespace.  ok to mangle it because we've already appended.
151         if (!IsEmptyStr(app)) {
152                 int i;
153                 char indent[256];
154                 indent[0] = 0;
155                 for (i=0; i<crp->tag_nesting_level; ++i) {
156                         strcat(indent, "  ");
157                 }
158                 syslog(LOG_DEBUG, "%s%s", indent, app, len);
159         }
160         // end logging
161 #endif
162
163         free(app);
164         return;
165 }
166
167
168 // Called by caldav_report_one_item() to fetch a message (by number) in the current room,
169 // and return only the icalendar data as a StrBuf.  Returns NULL if not found.
170 //
171 // NOTE: this function expects that "MSGP text/calendar" was issued at the beginning
172 // of a REPORT operation to set our preferred MIME type to calendar data.
173 StrBuf *fetch_ical(struct ctdlsession *c, long msgnum) {
174         char buf[1024];
175         StrBuf *Buf = NULL;
176
177         ctdl_printf(c, "MSG4 %ld", msgnum);
178         ctdl_readline(c, buf, sizeof(buf));
179         if (buf[0] != '1') {
180                 return NULL;
181         }
182
183         while (ctdl_readline(c, buf, sizeof(buf)), strcmp(buf, "000")) {
184                 if (Buf != NULL) {              // already in body
185                         StrBufAppendPrintf(Buf, "%s\n", buf);
186                 }
187                 else if (IsEmptyStr(buf)) {     // beginning of body
188                         Buf = NewStrBuf();
189                 }
190         }
191
192         return Buf;
193 }
194
195
196 // Called by multiple REPORT types to actually perform the output in "multiget" format.
197 // We need to already know the source message number and the href, but also already have the output data.
198 void cal_multiget_out(long msgnum, StrBuf *ThisHref, StrBuf *Caldata, StrBuf *ReportOut) {
199
200         StrBufAppendPrintf(ReportOut, "<D:response>");
201         StrBufAppendPrintf(ReportOut, "<D:href>");
202         StrBufXMLEscAppend(ReportOut, ThisHref, NULL, 0, 0);
203         StrBufAppendPrintf(ReportOut, "</D:href>");
204         StrBufAppendPrintf(ReportOut, "<D:propstat>");
205
206         if (Caldata != NULL) {
207                 // syslog(LOG_DEBUG, "caldav_report_one_item(%s) 200 OK", ChrPtr(ThisHref));
208                 StrBufAppendPrintf(ReportOut, "<D:status>");
209                 StrBufAppendPrintf(ReportOut, "HTTP/1.1 200 OK");
210                 StrBufAppendPrintf(ReportOut, "</D:status>");
211                 StrBufAppendPrintf(ReportOut, "<D:prop>");
212                 StrBufAppendPrintf(ReportOut, "<D:getetag>");
213                 StrBufAppendPrintf(ReportOut, "%ld", msgnum);
214                 StrBufAppendPrintf(ReportOut, "</D:getetag>");
215                 StrBufAppendPrintf(ReportOut, "<C:calendar-data>");
216                 StrBufXMLEscAppend(ReportOut, Caldata, NULL, 0, 0);
217                 StrBufAppendPrintf(ReportOut, "</C:calendar-data>");
218                 StrBufAppendPrintf(ReportOut, "</D:prop>");
219         }
220         else {
221                 // syslog(LOG_DEBUG, "caldav_report_one_item(%s) 404 not found", ChrPtr(ThisHref));
222                 StrBufAppendPrintf(ReportOut, "<D:status>");
223                 StrBufAppendPrintf(ReportOut, "HTTP/1.1 404 not found");
224                 StrBufAppendPrintf(ReportOut, "</D:status>");
225         }
226
227         StrBufAppendPrintf(ReportOut, "</D:propstat>");
228         StrBufAppendPrintf(ReportOut, "</D:response>");
229 }
230
231
232 // Called by caldav_report() to output a single item.
233 // Our policy is to throw away the list of properties the client asked for, and just send everything.
234 void caldav_report_one_item(struct http_transaction *h, struct ctdlsession *c, StrBuf *ReportOut, StrBuf *ThisHref) {
235         long msgnum;
236         StrBuf *Caldata = NULL;
237         char *euid;
238
239         euid = strrchr(ChrPtr(ThisHref), '/');
240         if (euid != NULL) {
241                 ++euid;
242         }
243         else {
244                 euid = (char *) ChrPtr(ThisHref);
245         }
246
247         char *unescaped_euid = strdup(euid);
248         if (!unescaped_euid) {
249                 return;
250         }
251         unescape_input(unescaped_euid);
252
253         msgnum = locate_message_by_uid(c, unescaped_euid);
254         free(unescaped_euid);
255         if (msgnum > 0) {
256                 Caldata = fetch_ical(c, msgnum);
257         }
258         else {
259                 Caldata = NULL;
260         }
261
262         cal_multiget_out(msgnum, ThisHref, Caldata, ReportOut);
263
264         if (Caldata != NULL) {
265                 FreeStrBuf(&Caldata);
266         }
267 }
268
269
270 // Called by caldav_apply_filters() to apply ONE filter.
271 // Returns 0 if the calendar item does not match the filter.
272 // Returns 1 if the calendar item DOES match the filter.
273 int caldav_apply_one_filter(void *cal, char *filter) {
274         syslog(LOG_DEBUG, "applying filter: %s", filter);
275
276         char this_filter[SIZ];          // we have to copy the filter string because we will destructively tokenize it
277         safestrncpy(this_filter, filter, sizeof(this_filter));
278
279         char *t[10] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL } ;
280         char *f = this_filter;
281         int num_tokens = 0;
282         while ( (t[num_tokens]=strtok_r(f, "|", &f)) && (num_tokens<10) ) {
283                 ++num_tokens;
284         }
285
286         // BEGIN experimental block -- see what happens when we cast to the wrong type
287
288         //icalcomponent *foo_comp = (icalcomponent *) cal;
289         //icalproperty *foo_prop = (icalproperty *) cal;
290         //icalparameter *foo_param = (icalparameter *) cal;
291
292         // END experimental block
293
294         // Handle the individual filters defined in RFC4791 9.7.1 through 9.7.5
295
296         if (!strcasecmp(t[0], "comp-filter")) {                         // RFC4791 9.7.1 - filter by component
297                 syslog(LOG_DEBUG, "component filter FIXME not implemented yet");
298                 if (icalcomponent_isa_component(cal)) {
299                         syslog(LOG_DEBUG, "\033[32m yes this is a component \033[0m");
300                 }
301                 else {
302                         syslog(LOG_DEBUG, "\033[31m no this is not a component \033[0m");
303                 }
304         }
305
306         else if (!strcasecmp(t[0], "prop-filter")) {                    // RFC4791 9.7.2 - filter by property
307                 syslog(LOG_DEBUG, "property filter FIXME not implemented yet");
308         }
309
310         else if (!strcasecmp(t[0], "param-filter")) {                   // RFC4791 9.7.3 - filter by parameter
311                 syslog(LOG_DEBUG, "parameter filter FIXME not implemented yet");
312         }
313
314         else if (!strcasecmp(t[0], "is-not-defined")) {                 // RFC4791 9.7.4
315                 syslog(LOG_DEBUG, "is-not-defined filter FIXME not implemented yet");
316         }
317
318         else if (!strcasecmp(t[0], "text-match")) {                     // RFC4791 9.7.5
319                 syslog(LOG_DEBUG, "text match filter FIXME not implemented yet");
320         }
321
322         return(1);
323 }
324
325
326 // Recursive function to apply CalDAV FILTERS to a calendar item.
327 // Returns zero if the calendar item was disqualified by a filter, nonzero if the calendar item still qualifies.
328 int caldav_apply_filters(void *cal, Array *filters, int index) {
329
330         // Apply *this* filter.
331         if (caldav_apply_one_filter(cal, array_get_element_at(filters, index)) == 0) {
332                 return(0);
333         }
334
335         // If we get to this point, the current filter has passed, and we move on to the next one.
336         if (index < array_len(filters)-1) {
337                 return(caldav_apply_filters(cal, filters, index+1));
338         }
339
340         // If we got this far, every filter passed, and the calendar item qualifies for output.
341         return(1);
342 }
343
344
345 // Called by report_the_room_itself() in room_functions.c when a CalDAV REPORT method
346 // is requested on a calendar room.  We fire up an XML Parser to decode the request and
347 // hopefully produce the correct output.
348 void caldav_report(struct http_transaction *h, struct ctdlsession *c) {
349         struct cr_params crp;
350         char buf[1024];
351
352         memset(&crp, 0, sizeof(struct cr_params));
353
354         XML_Parser xp = XML_ParserCreateNS("UTF-8", ':');
355         if (xp == NULL) {
356                 syslog(LOG_INFO, "Cannot create XML parser!");
357                 do_404(h);
358                 return;
359         }
360
361         XML_SetElementHandler(xp, caldav_xml_start, caldav_xml_end);
362         XML_SetCharacterDataHandler(xp, caldav_xml_chardata);
363         XML_SetUserData(xp, &crp);
364         XML_SetDefaultHandler(xp, NULL);        // Disable internal entity expansion to prevent "billion laughs attack"
365         XML_Parse(xp, h->request_body, h->request_body_length, 1);
366         XML_ParserFree(xp);
367
368         if (crp.Chardata != NULL) {             // Discard any trailing chardata ... normally nothing here
369                 FreeStrBuf(&crp.Chardata);
370                 crp.Chardata = NULL;
371         }
372
373         // We're going to make a lot of MSG4 calls, and the preferred MIME type we want is "text/calendar".
374         // The iCalendar standard is mature now, and we are no longer interested in text/x-vcal or application/ics.
375         ctdl_printf(c, "MSGP text/calendar");
376         ctdl_readline(c, buf, sizeof buf);
377
378         // Now begin the REPORT.
379         syslog(LOG_DEBUG, "CalDAV REPORT type is: %d", crp.report_type);
380         StrBuf *ReportOut = NewStrBuf();
381         StrBufAppendPrintf(ReportOut,
382                 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
383                 "<D:multistatus "
384                 "xmlns:D=\"DAV:\" "
385                 "xmlns:C=\"urn:ietf:params:xml:ns:caldav\""
386                 ">"
387         );
388
389         // RFC4791 7.8 "calendar-query" REPORT - Client will send a lot of search criteria.
390         if (crp.report_type == cr_calendar_query) {
391                 int i = 0;
392                 Array *msglist = get_msglist(c, "ALL");
393                 if (msglist != NULL) {
394                         for (i = 0; i < array_len(msglist); ++i) {
395                                 long m;
396                                 memcpy(&m, array_get_element_at(msglist, i), sizeof(long));
397
398                                 // load and parse one calendar item
399                                 StrBuf *one_item = fetch_ical(c, m);
400                                 icalcomponent *cal = icalcomponent_new_from_string(ChrPtr(one_item));
401
402                                 // Does this calendar item qualify for output?
403                                 int qualify = 1;
404
405                                 // If there was a filter stanza, run this calendar item through the filters.
406                                 qualify = caldav_apply_filters(cal, crp.filters, 0);
407                                 syslog(LOG_DEBUG, "Message %ld does%s qualify", m, (qualify ? "" : " NOT"));
408
409                                 // Did this calendar item match the query?  If so, output it.
410                                 if (qualify) {
411                                         // FIXME need to populate the Href instead of NULL
412                                         cal_multiget_out(m, NULL, one_item, ReportOut);
413                                 }
414
415                                 icalcomponent_free(cal);
416                                 FreeStrBuf(&one_item);
417
418                         }
419                         array_free(msglist);
420                 }
421         }
422
423         // RFC4791 7.9 "calendar-multiget" REPORT - go get the specific Hrefs the client asked for.
424         // Can we move this back into citserver too?
425         else if ( (crp.report_type == cr_calendar_multiget) && (crp.Hrefs != NULL) ) {
426
427                 StrBuf *ThisHref = NewStrBuf();
428                 const char *pvset = NULL;
429                 while (StrBufExtract_NextToken(ThisHref, crp.Hrefs, &pvset, '|') >= 0) {
430                         StrBufTrim(ThisHref);                           // remove leading/trailing whitespace from the href
431                         caldav_report_one_item(h, c, ReportOut, ThisHref);
432                 }
433                 FreeStrBuf(&ThisHref);
434         }
435
436         // RFC4791 7.10 "free-busy-query" REPORT
437         else if (crp.report_type == cr_freebusy_query) {
438                 // FIXME build this REPORT.  At the moment we send an empty multistatus.
439         }
440
441         // Free any query parameters that might have been allocated during the xml parse
442         if (crp.Hrefs != NULL) {
443                 FreeStrBuf(&crp.Hrefs);
444                 crp.Hrefs = NULL;
445         }
446         if (crp.filters) {
447                 array_free(crp.filters);
448                 crp.filters = NULL;
449         }
450
451         StrBufAppendPrintf(ReportOut, "</D:multistatus>\n");            // End the REPORT.
452
453         add_response_header(h, strdup("Content-type"), strdup("text/xml"));
454         h->response_code = 207;
455         h->response_string = strdup("Multi-Status");
456         h->response_body_length = StrLength(ReportOut);
457         h->response_body = SmashStrBuf(&ReportOut);
458 }