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