xmpp_sasl_service.c: style cleanup
[citadel.git] / webcit-ng / server / caldav_reports.c
index 1c95c380652d39abfd84dbf2ab745f627aba7fcd..374d50ee5f754842dadd2fadce83e81e40641a8b 100644 (file)
@@ -1,13 +1,14 @@
-// This file contains functions which handle all of the CalDAV "REPORT" queries
-// specified in RFC4791 section 7.
-//
+// This file contains functions which handle all of the CalDAV "REPORT" queries specified in RFC4791 section 7.
 // Copyright (c) 2023-2024 by the citadel.org team
-//
-// This program is open source software.  Use, duplication, or
-// disclosure is subject to the GNU General Public License v3.
+// This program is open source software.  Use, duplication, or disclosure is subject to the GNU General Public License v3.
 
 #include "webcit.h"
 
+#define CALDAV "urn:ietf:params:xml:ns:caldav:"                // Shorthand for the XML namespace of CalDAV
+#define CALDAVLEN sizeof(CALDAV)-1                     // And the length of that string
+
+const char *the_beginning_of_time      = "19010101T010101Z";
+const char *the_end_of_time            = "99991231T235959Z";
 
 // A CalDAV REPORT can only be one type.  This is stored in the report_type member.
 enum cr_type {
@@ -16,57 +17,95 @@ enum cr_type {
        cr_freebusy_query
 };
 
-
 // Data type for CalDAV Report Parameters.
 // As we slog our way through the XML we learn what the client is asking for
 // and build up the contents of this data type.
-struct cr_parms {
-       int tag_nesting_level;          // not needed, just kept for pretty-printing
+struct cr_params {
+       int comp_filter_nesting_level;
        enum cr_type report_type;       // which RFC4791 section 7 REPORT are we generating
        StrBuf *Chardata;               // XML chardata in between tags is built up here
        StrBuf *Hrefs;                  // list of items requested by a `calendar-multiget` REPORT
+       Array *filters;                 // If the query contains a FILTER stanza, the filter criteria are populated here
+       int filter_nest;                // tag nesting level where a FILTER stanza begins
 };
 
 
 // XML parser callback
 void caldav_xml_start(void *data, const char *el, const char **attr) {
-       struct cr_parms *crp = (struct cr_parms *) data;
-       int i;
+       struct cr_params *crp = (struct cr_params *) data;
 
-       // syslog(LOG_DEBUG, "CALDAV ELEMENT START: <%s> %d", el, crp->tag_nesting_level);
-
-       for (i = 0; attr[i] != NULL; i += 2) {
-               syslog(LOG_DEBUG, "                    Attribute '%s' = '%s'", attr[i], attr[i + 1]);
+#ifdef DEBUG_XML_PARSE
+       // logging
+       syslog(LOG_DEBUG, "<%s>", el);
+       for (int i = 0; attr[i] != NULL; i += 2) {
+               syslog(LOG_DEBUG, "Attribute '%s' = '%s'", attr[i], attr[i + 1]);
        }
+       // end logging
+#endif
 
        // RFC4791 7.8 "calendar-query" REPORT - Client will send a lot of search criteria.
-       if (!strcasecmp(el, "urn:ietf:params:xml:ns:caldav:calendar-query")) {
+       if (!strcasecmp(el, CALDAV"calendar-query")) {
                crp->report_type = cr_calendar_query;
        }
 
        // RFC4791 7.9 "calendar-multiget" REPORT - Client will supply a list of specific hrefs.
-       else if (!strcasecmp(el, "urn:ietf:params:xml:ns:caldav:calendar-multiget")) {
+       else if (!strcasecmp(el, CALDAV"calendar-multiget")) {
                crp->report_type = cr_calendar_multiget;
        }
 
        // RFC4791 7.10 "free-busy-query" REPORT
-       else if (!strcasecmp(el, "urn:ietf:params:xml:ns:caldav:free-busy-query")) {
+       else if (!strcasecmp(el, CALDAV"free-busy-query")) {
                crp->report_type = cr_freebusy_query;
        }
 
-       ++crp->tag_nesting_level;
+       // RFC4791 9.7 create a filter array if this query contains a "filter" stanza
+       else if (!strcasecmp(el, CALDAV"filter")) {
+               crp->filters = array_new(SIZ);
+               crp->filter_nest = crp->comp_filter_nesting_level;
+       }
+
+       // Handle the filters defined in RFC4791 9.7.1 through 9.7.5
+       else if (       (       (!strcasecmp(el, CALDAV"comp-filter"))
+                               || (!strcasecmp(el, CALDAV"prop-filter"))
+                               || (!strcasecmp(el, CALDAV"param-filter"))
+                               || (!strcasecmp(el, CALDAV"is-not-defined"))
+                               || (!strcasecmp(el, CALDAV"text-match"))
+                               || (!strcasecmp(el, CALDAV"time-range"))
+                       )
+                       && (crp->filters)                       // Make sure we actually allocated an array
+       ) {
+
+               if (!strcasecmp(el, CALDAV"comp-filter")) {
+                       ++crp->comp_filter_nesting_level;
+               }
+
+               char newfilter[SIZ];
+               int a = 0;
+               int len = snprintf(newfilter, SIZ, "%d|", crp->comp_filter_nesting_level - crp->filter_nest - 1);
+               len += snprintf(&newfilter[len], SIZ-len, "%s", &el[CALDAVLEN]);        // filter name without the namespace
+               while (attr[a]) {
+                       len += snprintf(&newfilter[len], SIZ-len, "|%s", attr[a++]);    // now save the attributes
+               }
+               array_append(crp->filters, newfilter);
+       }
 }
 
 
 // XML parser callback
 void caldav_xml_end(void *data, const char *el) {
-       struct cr_parms *crp = (struct cr_parms *) data;
-       --crp->tag_nesting_level;
+       struct cr_params *crp = (struct cr_params *) data;
 
-       if (crp->Chardata != NULL) {
-               // syslog(LOG_DEBUG, "CALDAV CHARDATA     : %s", ChrPtr(crp->Chardata));
+#ifdef DEBUG_XML_PARSE
+       // logging
+       int i;
+       syslog(LOG_DEBUG, "</%s>", el);
+       // end logging
+#endif
+
+       if (!strcasecmp(el, CALDAV"comp-filter")) {
+               --crp->comp_filter_nesting_level;
        }
-       // syslog(LOG_DEBUG, "CALDAV ELEMENT END  : <%s> %d", el, crp->tag_nesting_level);
+
 
        if ((!strcasecmp(el, "DAV::href")) || (!strcasecmp(el, "DAV:href"))) {
                if (crp->Hrefs == NULL) {       // append crp->Chardata to crp->Hrefs
@@ -86,15 +125,33 @@ void caldav_xml_end(void *data, const char *el) {
 
 
 // XML parser callback
-void caldav_xml_chardata(void *data, const XML_Char * s, int len) {
-       struct cr_parms *crp = (struct cr_parms *) data;
+void caldav_xml_chardata(void *data, const XML_Char *s, int len) {
+       struct cr_params *crp = (struct cr_params *) data;
+
+       char *app = malloc(len+1);
+       if (!app) {
+               return;
+       }
+       memcpy(app, s, len);
+       app[len] = 0;
 
        if (crp->Chardata == NULL) {
                crp->Chardata = NewStrBuf();
        }
 
-       StrBufAppendBufPlain(crp->Chardata, s, len, 0);
+       StrBufAppendBufPlain(crp->Chardata, app, len, 0);
+
+#ifdef DEBUG_XML_PARSE
+       // logging
+       string_trim(app);               // remove leading/trailing whitespace.  ok to mangle it because we've already appended.
+       if (!IsEmptyStr(app)) {
+               int i;
+               syslog(LOG_DEBUG, "%s", app, len);
+       }
+       // end logging
+#endif
 
+       free(app);
        return;
 }
 
@@ -201,14 +258,189 @@ void caldav_report_one_item(struct http_transaction *h, struct ctdlsession *c, S
 }
 
 
+// Compare function for "time-range" tests (RFC4791 section 9.9)
+// Returns nonzero if the supplied icalcomponent occurs within the specified time range
+int caldav_time_range_filter_matches(icalcomponent *cal, char *start_str, char *end_str) {
+
+       // syslog(LOG_DEBUG, "caldav_time_range_filter_matches() comparing:\n\033[35m%s\033[0m", icalcomponent_as_ical_string(cal));
+
+       // NOTE TO ME:
+       // Recurrence info is available at this level.  We can handle it here.
+
+       // IMPLEMENTATION NOTE:
+       // ical_ctdl_is_overlap() works because icaltime_compare() is really smart.
+       // It looks at the time zone of the dtstart/dtend and can apparently go back up the icalcomponent
+       // hierarchy to find its time zone data.  I tested this by creating an event with a fictional
+       // time zone and it did the right thing.  It even showed the fictional name to me.  This saves us
+       // from having to convert everything to UTC before comparing.  Nice!
+
+       icaltimetype dts = icalcomponent_get_dtstart(cal);
+       syslog(LOG_DEBUG, "component start: \033[36m%-16s\033[0m (%s)", icaltime_as_ical_string_r(dts), icaltime_get_tzid(dts));
+
+       icaltimetype dte = icalcomponent_get_dtend(cal);
+       syslog(LOG_DEBUG, "component   end: \033[36m%-16s\033[0m (%s)", icaltime_as_ical_string_r(dte), icaltime_get_tzid(dte));
+
+       struct icaltimetype start = icaltime_from_string(start_str);
+       syslog(LOG_DEBUG, "   search start: \033[36m%-16s\033[0m (%s)", icaltime_as_ical_string_r(start), icaltime_get_tzid(start));
+
+       struct icaltimetype end = icaltime_from_string(end_str);
+       syslog(LOG_DEBUG, "   search   end: \033[36m%-16s\033[0m (%s)", icaltime_as_ical_string_r(end), icaltime_get_tzid(end));
+
+       return(ical_ctdl_is_overlap(dts, dte, start, end));     // We have a convenience function for this.
+}
+
+
+// Recursive function to apply CalDAV FILTERS to a calendar item.
+// Returns zero if the calendar item was disqualified by a filter, nonzero if the calendar item still qualifies.
+int caldav_apply_filters(void *cal, Array *filters, int apply_at_level) {
+
+       int f = 0;                                              // filter number iterator
+       int qual = 1;                                           // 0 for disqualify, 1 for qualify
+       int previous_level = -1;
+       int disregard_further_comp_filters = 0;
+
+       while ( (f<array_len(filters)) && (qual) ) {
+
+               // Tokenize the filter (a future performance hack would be to pre-tokenize instead of storing delimited strings)
+               char this_filter[SIZ];
+               safestrncpy(this_filter, array_get_element_at(filters, f), sizeof(this_filter));
+               char *t[10] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL } ;
+               char *ft = this_filter;
+               int num_tokens = 0;
+               while ( (t[num_tokens]=strtok_r(ft, "|", &ft)) && (num_tokens<10) ) {
+                       ++num_tokens;
+               }
+               int this_rule_level = atoi(t[0]);
+               syslog(LOG_DEBUG, "caldav_apply_filters() filter=%d, level=%d, <%s>", f, this_rule_level, array_get_element_at(filters, f) );
+
+               // Handle the individual filters defined in RFC4791 9.7.1 through 9.7.5
+
+               if (apply_at_level < previous_level) {
+                       syslog(LOG_DEBUG, "caldav: walking back down");
+                       return(qual);
+               }
+
+               else if (this_rule_level != apply_at_level) {
+                       syslog(LOG_DEBUG, "caldav: apply_at_level=%d, this_rule_level=%d, skipping this rule", apply_at_level, this_rule_level);
+               }
+
+               else if (       (!strcasecmp(t[1], "comp-filter"))              // RFC4791 9.7.1 - filter by component
+                               && (!disregard_further_comp_filters)            // one is enough to succeed
+                       ) {
+                       syslog(LOG_DEBUG, "component filter at level %d", this_rule_level);
+
+                       // comp-filter requires exactly one parameter (name="VXXXX")
+                       if (num_tokens < 4) {
+                               syslog(LOG_DEBUG, "caldav: comp-filter has no parameters - rejecting");
+                               return(0);
+                       }
+
+                       // Root element is NOT a component, but the root filter is "comp-filter" -- reject!
+                       if ( (!icalcomponent_isa_component(cal)) && (this_rule_level == 0) ) {
+                               syslog(LOG_DEBUG, "caldav: root element is not a component, rejecting");
+                               return(0);
+                       }
+
+                       // Current element is a component and the filter is "comp-filter" -- see if it matches the requested type
+                       if (    (icalcomponent_isa_component(cal))
+                               && (!strcasecmp(t[2], "name"))
+                       ) {
+                               if (icalcomponent_isa(cal) == icalcomponent_string_to_kind(t[3]) ) {
+                                       syslog(LOG_DEBUG, "caldav: component at level %d is <%s>, looking for <%s>, recursing...",
+                                               apply_at_level,
+                                               icalcomponent_kind_to_string(icalcomponent_isa(cal)), t[3]
+                                       );
+
+                                       // We have a match.  Drill down into the subcomponents.
+
+                                       icalcomponent *c = NULL;
+                                       int number_of_subcomponents = 0;
+                                       int number_of_matches = 0;
+                                       for (   c = icalcomponent_get_first_component(cal, ICAL_ANY_COMPONENT);
+                                               (c != 0);                                                
+                                               c = icalcomponent_get_next_component(cal, ICAL_ANY_COMPONENT)
+                                       ) {
+                                               ++number_of_subcomponents;
+                                               if (caldav_apply_filters(c, filters, apply_at_level+1)) {
+                                                       syslog(LOG_DEBUG, "Subcomponent %d might match", number_of_subcomponents);
+                                                       ++number_of_matches;
+                                               }
+                                       }
+                                       if (number_of_matches > 0) {                    // something matched
+                                               qual = 1;
+                                               disregard_further_comp_filters = 1;
+
+                                       }
+                                       else if (number_of_subcomponents > 0) {         // nothing matched
+                                               return(0);                              // but only fail if there *were* subcomponents.
+                                       }
+
+                               }
+                               else {
+                                       syslog(LOG_DEBUG, "caldav: component at level %d is <%s>, looking for <%s>, rejecting",
+                                               apply_at_level,
+                                               icalcomponent_kind_to_string(icalcomponent_isa(cal)),
+                                               t[3]
+                                       );
+                                       return(0);
+                               }
+                       }
+
+               }
+
+               else if (!strcasecmp(t[1], "prop-filter")) {                    // RFC4791 9.7.2 - filter by property
+                       syslog(LOG_DEBUG, "property filter at level %d FIXME not implemented yet", this_rule_level);
+               }
+
+               else if (!strcasecmp(t[1], "param-filter")) {                   // RFC4791 9.7.3 - filter by parameter
+                       syslog(LOG_DEBUG, "parameter filter at level %d FIXME not implemented yet", this_rule_level);
+               }
+
+               else if (!strcasecmp(t[1], "is-not-defined")) {                 // RFC4791 9.7.4
+                       syslog(LOG_DEBUG, "is-not-defined filter at level %d FIXME not implemented yet", this_rule_level);
+               }
+
+               else if (!strcasecmp(t[1], "text-match")) {                     // RFC4791 9.7.5
+                       syslog(LOG_DEBUG, "text match filter at level %d FIXME not implemented yet", this_rule_level);
+               }
+
+               else if (!strcasecmp(t[1], "time-range")) {                     // RFC4791 9.9
+                       syslog(LOG_DEBUG, "time range filter at level %d FIXME add recurrence", this_rule_level);
+                       for (int i=2; (i+1)<num_tokens; i+=2) {
+                               char *tr_start  = (char *)the_beginning_of_time;        // default if not specified
+                               char *tr_end    = (char *)the_end_of_time;              // default if not specified
+                               if (!strcasecmp(t[i], "start")) {
+                                       tr_start = t[i+1];
+                               }
+                               else if (!strcasecmp(t[i], "end")) {
+                                       tr_end = t[i+1];
+                               }
+                               if (caldav_time_range_filter_matches(cal, tr_start, tr_end)) {
+                                       syslog(LOG_DEBUG, "time range matches");
+                               }
+                               else {
+                                       syslog(LOG_DEBUG, "time range does not match -- rejecting");
+                                       qual = 0;
+                               }
+                       }
+               }
+
+               ++f;
+       }
+
+       syslog(LOG_DEBUG, "caldav: we reached the end of level %d , returning %d", apply_at_level, qual);
+       return(qual);
+}
+
+
 // Called by report_the_room_itself() in room_functions.c when a CalDAV REPORT method
 // is requested on a calendar room.  We fire up an XML Parser to decode the request and
 // hopefully produce the correct output.
 void caldav_report(struct http_transaction *h, struct ctdlsession *c) {
-       struct cr_parms crp;
+       struct cr_params crp;
        char buf[1024];
 
-       memset(&crp, 0, sizeof(struct cr_parms));
+       memset(&crp, 0, sizeof(struct cr_params));
 
        XML_Parser xp = XML_ParserCreateNS("UTF-8", ':');
        if (xp == NULL) {
@@ -258,17 +490,17 @@ void caldav_report(struct http_transaction *h, struct ctdlsession *c) {
                                StrBuf *one_item = fetch_ical(c, m);
                                icalcomponent *cal = icalcomponent_new_from_string(ChrPtr(one_item));
 
-                               // qualify will be set to nonzero if this calendar item is a match for the QUERY.
-                               int qualify = 0;
-
-                               // this is a horrible temporary hack to output every item (for now)
-                               qualify = 1;
-
-                               // Did this calendar item match the query?  If so, output it.
-                               if (qualify) {
+                               // Does this calendar item qualify for output?  Run this calendar item through the filters.
+                               syslog(LOG_DEBUG, "Evaluating message \033[33m%ld\033[0m...", m);
+                               if (caldav_apply_filters(cal, crp.filters, 0)) {
+                                       syslog(LOG_DEBUG, "Message %ld \033[32mQUALIFIES\033[0m");
                                        // FIXME need to populate the Href instead of NULL
                                        cal_multiget_out(m, NULL, one_item, ReportOut);
                                }
+                               else {
+                                       syslog(LOG_DEBUG, "Message %ld \033[31mDOES NOT QUALIFY\033[0m");
+                               }
+                               syslog(LOG_DEBUG, "");
 
                                icalcomponent_free(cal);
                                FreeStrBuf(&one_item);
@@ -301,6 +533,10 @@ void caldav_report(struct http_transaction *h, struct ctdlsession *c) {
                FreeStrBuf(&crp.Hrefs);
                crp.Hrefs = NULL;
        }
+       if (crp.filters) {
+               array_free(crp.filters);
+               crp.filters = NULL;
+       }
 
        StrBufAppendPrintf(ReportOut, "</D:multistatus>\n");            // End the REPORT.