Completed the first two filter tests.
[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                         )
85                         && (crp->filters)                       // Make sure we actually allocated an array
86         ) {
87
88                 char newfilter[SIZ];
89                 int a = 0;
90                 int len = snprintf(newfilter, SIZ, "%d|", crp->tag_nesting_level - crp->filter_nest - 1);
91                 len += snprintf(&newfilter[len], SIZ-len, "%s", &el[CALLEN]);           // filter name without the namespace
92                 while (attr[a]) {
93                         len += snprintf(&newfilter[len], SIZ-len, "|%s", attr[a++]);    // now save the attributes
94                 }
95                 array_append(crp->filters, newfilter);
96         }
97
98 }
99
100
101 // XML parser callback
102 void caldav_xml_end(void *data, const char *el) {
103         struct cr_params *crp = (struct cr_params *) data;
104
105         --crp->tag_nesting_level;
106
107 #ifdef DEBUG_XML_PARSE
108         // logging
109         int i;
110         char indent[256];
111         indent[0] = 0;
112         for (i=0; i<crp->tag_nesting_level; ++i) {
113                 strcat(indent, "  ");
114         }
115         syslog(LOG_DEBUG, "%s</%s>", indent, el);
116         // end logging
117 #endif
118
119         if ((!strcasecmp(el, "DAV::href")) || (!strcasecmp(el, "DAV:href"))) {
120                 if (crp->Hrefs == NULL) {       // append crp->Chardata to crp->Hrefs
121                         crp->Hrefs = NewStrBuf();
122                 }
123                 else {
124                         StrBufAppendBufPlain(crp->Hrefs, HKEY("|"), 0);
125                 }
126                 StrBufAppendBuf(crp->Hrefs, crp->Chardata, 0);
127         }
128
129         if (crp->Chardata != NULL) {            // Tag is closed; chardata is now out of scope.
130                 FreeStrBuf(&crp->Chardata);     // Free the buffer.
131                 crp->Chardata = NULL;
132         }
133 }
134
135
136 // XML parser callback
137 void caldav_xml_chardata(void *data, const XML_Char *s, int len) {
138         struct cr_params *crp = (struct cr_params *) data;
139
140         char *app = malloc(len+1);
141         if (!app) {
142                 return;
143         }
144         memcpy(app, s, len);
145         app[len] = 0;
146
147         if (crp->Chardata == NULL) {
148                 crp->Chardata = NewStrBuf();
149         }
150
151         StrBufAppendBufPlain(crp->Chardata, app, len, 0);
152
153 #ifdef DEBUG_XML_PARSE
154         // logging
155         string_trim(app);               // remove leading/trailing whitespace.  ok to mangle it because we've already appended.
156         if (!IsEmptyStr(app)) {
157                 int i;
158                 char indent[256];
159                 indent[0] = 0;
160                 for (i=0; i<crp->tag_nesting_level; ++i) {
161                         strcat(indent, "  ");
162                 }
163                 syslog(LOG_DEBUG, "%s%s", indent, app, len);
164         }
165         // end logging
166 #endif
167
168         free(app);
169         return;
170 }
171
172
173 // Called by caldav_report_one_item() to fetch a message (by number) in the current room,
174 // and return only the icalendar data as a StrBuf.  Returns NULL if not found.
175 //
176 // NOTE: this function expects that "MSGP text/calendar" was issued at the beginning
177 // of a REPORT operation to set our preferred MIME type to calendar data.
178 StrBuf *fetch_ical(struct ctdlsession *c, long msgnum) {
179         char buf[1024];
180         StrBuf *Buf = NULL;
181
182         ctdl_printf(c, "MSG4 %ld", msgnum);
183         ctdl_readline(c, buf, sizeof(buf));
184         if (buf[0] != '1') {
185                 return NULL;
186         }
187
188         while (ctdl_readline(c, buf, sizeof(buf)), strcmp(buf, "000")) {
189                 if (Buf != NULL) {              // already in body
190                         StrBufAppendPrintf(Buf, "%s\n", buf);
191                 }
192                 else if (IsEmptyStr(buf)) {     // beginning of body
193                         Buf = NewStrBuf();
194                 }
195         }
196
197         return Buf;
198 }
199
200
201 // Called by multiple REPORT types to actually perform the output in "multiget" format.
202 // We need to already know the source message number and the href, but also already have the output data.
203 void cal_multiget_out(long msgnum, StrBuf *ThisHref, StrBuf *Caldata, StrBuf *ReportOut) {
204
205         StrBufAppendPrintf(ReportOut, "<D:response>");
206         StrBufAppendPrintf(ReportOut, "<D:href>");
207         StrBufXMLEscAppend(ReportOut, ThisHref, NULL, 0, 0);
208         StrBufAppendPrintf(ReportOut, "</D:href>");
209         StrBufAppendPrintf(ReportOut, "<D:propstat>");
210
211         if (Caldata != NULL) {
212                 // syslog(LOG_DEBUG, "caldav_report_one_item(%s) 200 OK", ChrPtr(ThisHref));
213                 StrBufAppendPrintf(ReportOut, "<D:status>");
214                 StrBufAppendPrintf(ReportOut, "HTTP/1.1 200 OK");
215                 StrBufAppendPrintf(ReportOut, "</D:status>");
216                 StrBufAppendPrintf(ReportOut, "<D:prop>");
217                 StrBufAppendPrintf(ReportOut, "<D:getetag>");
218                 StrBufAppendPrintf(ReportOut, "%ld", msgnum);
219                 StrBufAppendPrintf(ReportOut, "</D:getetag>");
220                 StrBufAppendPrintf(ReportOut, "<C:calendar-data>");
221                 StrBufXMLEscAppend(ReportOut, Caldata, NULL, 0, 0);
222                 StrBufAppendPrintf(ReportOut, "</C:calendar-data>");
223                 StrBufAppendPrintf(ReportOut, "</D:prop>");
224         }
225         else {
226                 // syslog(LOG_DEBUG, "caldav_report_one_item(%s) 404 not found", ChrPtr(ThisHref));
227                 StrBufAppendPrintf(ReportOut, "<D:status>");
228                 StrBufAppendPrintf(ReportOut, "HTTP/1.1 404 not found");
229                 StrBufAppendPrintf(ReportOut, "</D:status>");
230         }
231
232         StrBufAppendPrintf(ReportOut, "</D:propstat>");
233         StrBufAppendPrintf(ReportOut, "</D:response>");
234 }
235
236
237 // Called by caldav_report() to output a single item.
238 // Our policy is to throw away the list of properties the client asked for, and just send everything.
239 void caldav_report_one_item(struct http_transaction *h, struct ctdlsession *c, StrBuf *ReportOut, StrBuf *ThisHref) {
240         long msgnum;
241         StrBuf *Caldata = NULL;
242         char *euid;
243
244         euid = strrchr(ChrPtr(ThisHref), '/');
245         if (euid != NULL) {
246                 ++euid;
247         }
248         else {
249                 euid = (char *) ChrPtr(ThisHref);
250         }
251
252         char *unescaped_euid = strdup(euid);
253         if (!unescaped_euid) {
254                 return;
255         }
256         unescape_input(unescaped_euid);
257
258         msgnum = locate_message_by_uid(c, unescaped_euid);
259         free(unescaped_euid);
260         if (msgnum > 0) {
261                 Caldata = fetch_ical(c, msgnum);
262         }
263         else {
264                 Caldata = NULL;
265         }
266
267         cal_multiget_out(msgnum, ThisHref, Caldata, ReportOut);
268
269         if (Caldata != NULL) {
270                 FreeStrBuf(&Caldata);
271         }
272 }
273
274
275 // Recursive function to apply CalDAV FILTERS to a calendar item.
276 // Returns zero if the calendar item was disqualified by a filter, nonzero if the calendar item still qualifies.
277 int caldav_apply_filters(void *cal, Array *filters) {
278
279         int f = 0;                                      // filter number iterator
280         int qual = 1;                                   // 0 for disqualify, 1 for qualify
281
282         while ( (f<array_len(filters)) && (qual) ) {
283
284                 // Tokenize the filter (a future performance hack would be to pre-tokenize instead of storing delimited strings)
285                 char this_filter[SIZ];
286                 safestrncpy(this_filter, array_get_element_at(filters, f), sizeof(this_filter));
287                 char *t[10] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL } ;
288                 char *ft = this_filter;
289                 int num_tokens = 0;
290                 while ( (t[num_tokens]=strtok_r(ft, "|", &ft)) && (num_tokens<10) ) {
291                         ++num_tokens;
292                 }
293                 int level = atoi(t[0]);
294                 syslog(LOG_DEBUG, "caldav_apply_filters() filter=%d, level=%d, <%s>", f, level, array_get_element_at(filters, f) );
295
296                 // Handle the individual filters defined in RFC4791 9.7.1 through 9.7.5
297
298                 if (!strcasecmp(t[1], "comp-filter")) {                         // RFC4791 9.7.1 - filter by component
299                         syslog(LOG_DEBUG, "component filter at level %d", level);
300
301                         // Root element is NOT a component, but the root filter is "comp-filter" -- reject!
302                         if ( (!icalcomponent_isa_component(cal)) && (level == 0) ) {
303                                 syslog(LOG_DEBUG, "caldav: root element is not a component, rejecting");
304                                 return(0);
305                         }
306
307                         // Root element IS a component and the root filter is "comp-filter" -- see if it matches the requested type
308                         if (    (icalcomponent_isa_component(cal))
309                                 && (level == 0)
310                                 && (!strcasecmp(t[2], "name"))
311                         ) {
312                                 if (icalcomponent_isa(cal) != icalcomponent_string_to_kind(t[3]) ) {
313                                         syslog(LOG_DEBUG, "caldav: root component is <%s>, looking for <%s>, rejecting",
314                                                 icalcomponent_kind_to_string(icalcomponent_isa(cal)), t[3]
315                                         );
316                                         return(0);
317                                 }
318                         }
319
320                 }
321
322                 else if (!strcasecmp(t[1], "prop-filter")) {                    // RFC4791 9.7.2 - filter by property
323                         syslog(LOG_DEBUG, "property filter FIXME not implemented yet");
324                 }
325
326                 else if (!strcasecmp(t[1], "param-filter")) {                   // RFC4791 9.7.3 - filter by parameter
327                         syslog(LOG_DEBUG, "parameter filter FIXME not implemented yet");
328                 }
329
330                 else if (!strcasecmp(t[1], "is-not-defined")) {                 // RFC4791 9.7.4
331                         syslog(LOG_DEBUG, "is-not-defined filter FIXME not implemented yet");
332                 }
333
334                 else if (!strcasecmp(t[1], "text-match")) {                     // RFC4791 9.7.5
335                         syslog(LOG_DEBUG, "text match filter FIXME not implemented yet");
336                 }
337
338                 ++f;
339         }
340
341         return(qual);
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                                 syslog(LOG_DEBUG, "Evaluating message \033[33m%ld\033[0m...", m);
407                                 qualify = caldav_apply_filters(cal, crp.filters);
408                                 syslog(LOG_DEBUG, "Message %ld %s\033[0m qualify", m, (qualify ? "\033[32mDOES" : "\033[31mDOES NOT"));
409                                 syslog(LOG_DEBUG, "");
410
411                                 // Did this calendar item match the query?  If so, output it.
412                                 if (qualify) {
413                                         // FIXME need to populate the Href instead of NULL
414                                         cal_multiget_out(m, NULL, one_item, ReportOut);
415                                 }
416
417                                 icalcomponent_free(cal);
418                                 FreeStrBuf(&one_item);
419
420                         }
421                         array_free(msglist);
422                 }
423         }
424
425         // RFC4791 7.9 "calendar-multiget" REPORT - go get the specific Hrefs the client asked for.
426         // Can we move this back into citserver too?
427         else if ( (crp.report_type == cr_calendar_multiget) && (crp.Hrefs != NULL) ) {
428
429                 StrBuf *ThisHref = NewStrBuf();
430                 const char *pvset = NULL;
431                 while (StrBufExtract_NextToken(ThisHref, crp.Hrefs, &pvset, '|') >= 0) {
432                         StrBufTrim(ThisHref);                           // remove leading/trailing whitespace from the href
433                         caldav_report_one_item(h, c, ReportOut, ThisHref);
434                 }
435                 FreeStrBuf(&ThisHref);
436         }
437
438         // RFC4791 7.10 "free-busy-query" REPORT
439         else if (crp.report_type == cr_freebusy_query) {
440                 // FIXME build this REPORT.  At the moment we send an empty multistatus.
441         }
442
443         // Free any query parameters that might have been allocated during the xml parse
444         if (crp.Hrefs != NULL) {
445                 FreeStrBuf(&crp.Hrefs);
446                 crp.Hrefs = NULL;
447         }
448         if (crp.filters) {
449                 array_free(crp.filters);
450                 crp.filters = NULL;
451         }
452
453         StrBufAppendPrintf(ReportOut, "</D:multistatus>\n");            // End the REPORT.
454
455         add_response_header(h, strdup("Content-type"), strdup("text/xml"));
456         h->response_code = 207;
457         h->response_string = strdup("Multi-Status");
458         h->response_body_length = StrLength(ReportOut);
459         h->response_body = SmashStrBuf(&ReportOut);
460 }