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