Libical API Documentation 4.0 STABLE VERSION [Visit the v3.0 documentation]
Loading...
Searching...
No Matches
icalrecur.c
Go to the documentation of this file.
1/*======================================================================
2 FILE: icalrecur.c
3 CREATOR: eric 16 May 2000
4
5 SPDX-FileCopyrightText: 2000, Eric Busboom <eric@civicknowledge.com>
6 SPDX-License-Identifier: LGPL-2.1-only OR MPL-2.0
7========================================================================*/
8
122
123#ifdef HAVE_CONFIG_H
124#include <config.h>
125#endif
126
127#include "icalrecur.h"
128#include "icalerror_p.h"
129#include "icalerror.h"
130#include "icallimits.h"
131#include "icalmemory.h"
132#include "icaltimezone.h"
133#include "icalvalue.h" /* for print_date[time]_to_string() */
134
135#include <ctype.h>
136#include <stddef.h> /* For offsetof() macro */
137#include <stdint.h>
138#include <stdlib.h>
139
140#if ICAL_SYNC_MODE == ICAL_SYNC_MODE_PTHREAD
141#include <pthread.h>
142static pthread_mutex_t invalid_rrule_mutex = PTHREAD_MUTEX_INITIALIZER;
143#endif
144
145static ICAL_GLOBAL_VAR ical_invalid_rrule_handling invalidRruleHandling = ICAL_RRULE_TREAT_AS_ERROR;
146
147#if defined(HAVE_LIBICU)
148#include <unicode/ucal.h>
149#include <unicode/ustring.h>
150#include <stdbool.h>
151#else
152
153/* The maximums below are based on Gregorian leap years */
154#undef ICAL_BY_MONTH_SIZE
155#undef ICAL_BY_WEEKNO_SIZE
156#undef ICAL_BY_YEARDAY_SIZE
158#define ICAL_BY_MONTH_SIZE 13 /* 1 to 12 */
159#define ICAL_BY_WEEKNO_SIZE 54 /* 1 to 53 */
160#define ICAL_BY_YEARDAY_SIZE 367 /* 1 to 366 */
162#endif
163
165#if defined(HAVE_LIBICU)
166#define MAX_TIME_T_YEAR 20000
167#else
168#if (SIZEOF_ICALTIME_T > 4)
171#define MAX_TIME_T_YEAR 2582
172#else
175#define MAX_TIME_T_YEAR 2037
176#endif
177#endif
178
179#define LEAP_MONTH 0x1000
181
182/****************** Forward declarations ******************/
183static void icalrecurrencetype_clear(struct icalrecurrencetype *recur);
184static short daymask_find_next_bit(const unsigned long *days, short start_index);
185
186/****************** Enumeration Routines ******************/
187
188static const struct freq_map {
190 const char str[9];
191} freq_map[] = {
192 {ICAL_SECONDLY_RECURRENCE, "SECONDLY"},
193 {ICAL_MINUTELY_RECURRENCE, "MINUTELY"},
194 {ICAL_HOURLY_RECURRENCE, "HOURLY"},
195 {ICAL_DAILY_RECURRENCE, "DAILY"},
196 {ICAL_WEEKLY_RECURRENCE, "WEEKLY"},
197 {ICAL_MONTHLY_RECURRENCE, "MONTHLY"},
198 {ICAL_YEARLY_RECURRENCE, "YEARLY"},
199 {ICAL_NO_RECURRENCE, ""}};
200
202{
203 int i;
204
205 for (i = 0; freq_map[i].kind != ICAL_NO_RECURRENCE; i++) {
206 if (strcasecmp(str, freq_map[i].str) == 0) {
207 return freq_map[i].kind;
208 }
209 }
210 return ICAL_NO_RECURRENCE;
211}
212
214{
215 int i;
216
217 for (i = 0; freq_map[i].kind != ICAL_NO_RECURRENCE; i++) {
218 if (freq_map[i].kind == kind) {
219 return freq_map[i].str;
220 }
221 }
222 return 0;
223}
224
225static const struct skip_map {
227 const char str[9];
228} skip_map[] = {
229 {ICAL_SKIP_BACKWARD, "BACKWARD"},
230 {ICAL_SKIP_FORWARD, "FORWARD"},
231 {ICAL_SKIP_OMIT, "OMIT"},
232 {ICAL_SKIP_UNDEFINED, ""}};
233
235{
236 int i;
237
238 for (i = 0; skip_map[i].kind != ICAL_SKIP_UNDEFINED; i++) {
239 if (strcasecmp(str, skip_map[i].str) == 0) {
240 return skip_map[i].kind;
241 }
242 }
243 return ICAL_SKIP_UNDEFINED;
244}
245
247{
248 int i;
249
250 for (i = 0; skip_map[i].kind != ICAL_SKIP_UNDEFINED; i++) {
251 if (skip_map[i].kind == kind) {
252 return skip_map[i].str;
253 }
254 }
255 return 0;
256}
257
258static const struct wd_map {
260 const char str[3];
261} wd_map[] = {
262 {ICAL_SUNDAY_WEEKDAY, "SU"},
263 {ICAL_MONDAY_WEEKDAY, "MO"},
264 {ICAL_TUESDAY_WEEKDAY, "TU"},
266 {ICAL_THURSDAY_WEEKDAY, "TH"},
267 {ICAL_FRIDAY_WEEKDAY, "FR"},
268 {ICAL_SATURDAY_WEEKDAY, "SA"},
269 {ICAL_NO_WEEKDAY, ""}};
270
272{
273 int i;
274
275 for (i = 0; wd_map[i].wd != ICAL_NO_WEEKDAY; i++) {
276 if (wd_map[i].wd == kind) {
277 return wd_map[i].str;
278 }
279 }
280
281 return 0;
282}
283
285{
286 int i;
287
288 for (i = 0; wd_map[i].wd != ICAL_NO_WEEKDAY; i++) {
289 if (strcasecmp(str, wd_map[i].str) == 0) {
290 return wd_map[i].wd;
291 }
292 }
293
294 return ICAL_NO_WEEKDAY;
295}
296
297/*********************** Memory management helper routines ************************/
298
299static void icalrecur_free_by(icalrecurrence_by_data *by)
300{
301 icalmemory_free_buffer(by->data);
302 by->data = NULL;
303 by->size = 0;
304}
305
306bool icalrecur_resize_by(icalrecurrence_by_data *by, short size)
307{
308 if (by->size == size) {
309 return true;
310 }
311
312 if (size == 0) {
313 icalrecur_free_by(by);
314 return true;
315 }
316
317 if ((by->data == NULL) || (by->size == 0)) {
318 if ((by->data != NULL) || (by->size != 0)) {
320 return false;
321 }
322
323 by->data = (short *)icalmemory_new_buffer((size_t)size * sizeof(by->data[0]));
324 if (!by->data) {
325 return false;
326 }
327 } else {
328 short *new_data = (short *)icalmemory_resize_buffer(by->data, (size_t)size * sizeof(by->data[0]));
329 if (!new_data) {
330 return false;
331 }
332
333 by->data = new_data;
334 }
335
336 if (size > by->size) {
337 memset(&by->data[by->size], 0, (size_t)(size - by->size) * sizeof(by->data[0]));
338 }
339
340 by->size = size;
341
342 return true;
343}
344
345/*********************** Rule parsing routines ************************/
346
347struct icalrecur_parser {
348 const char *rule;
349 char *copy;
350 char *this_clause;
351 char *next_clause;
352
353 struct icalrecurrencetype *rt;
354};
355
357enum expand_table
358{
359 UNKNOWN = 0,
360 CONTRACT = 1,
361 EXPAND = 2,
362 ILLEGAL = 3
363};
365
366struct expand_split_map_struct {
368
369 /* Elements of the 'map' array correspond to the BYxxx rules:
370 Second,Minute,Hour,Day,Month Day,Year Day,Week No,Month,SetPos */
371
372 short map[ICAL_BY_NUM_PARTS];
373};
374
381
382static const struct expand_split_map_struct expand_map[] = {
383 /* M W YD MD D h m s P */
384 {ICAL_SECONDLY_RECURRENCE, {1, 3, 1, 1, 1, 1, 1, 1, 1}},
385 {ICAL_MINUTELY_RECURRENCE, {1, 3, 1, 1, 1, 1, 1, 2, 1}},
386 {ICAL_HOURLY_RECURRENCE, {1, 3, 1, 1, 1, 1, 2, 2, 1}},
387 {ICAL_DAILY_RECURRENCE, {1, 3, 3, 1, 1, 2, 2, 2, 1}},
388 {ICAL_WEEKLY_RECURRENCE, {1, 3, 3, 3, 2, 2, 2, 2, 1}},
389 {ICAL_MONTHLY_RECURRENCE, {1, 3, 3, 2, 2, 2, 2, 2, 1}},
390 {ICAL_YEARLY_RECURRENCE, {2, 2, 2, 2, 2, 2, 2, 2, 1}},
391 {ICAL_NO_RECURRENCE, {0, 0, 0, 0, 0, 0, 0, 0, 0}}};
392
393static const struct recur_map {
394 const char *str;
395 int size;
396 int min;
397 int isTime;
398} recur_map[] = {
399 {"BYMONTH", ICAL_BY_MONTH_SIZE, 1, 0},
400 {"BYWEEKNO", ICAL_BY_WEEKNO_SIZE, -1, 0},
401 {"BYYEARDAY", ICAL_BY_YEARDAY_SIZE, -1, 0},
402 {"BYMONTHDAY", ICAL_BY_MONTHDAY_SIZE, -1, 0},
403 {"BYDAY", ICAL_BY_DAY_SIZE, 0, 0},
404 {"BYHOUR", ICAL_BY_HOUR_SIZE, 0, 1},
405 {"BYMINUTE", ICAL_BY_MINUTE_SIZE, 0, 1},
406 {"BYSECOND", ICAL_BY_SECOND_SIZE, 0, 1},
407 {"BYSETPOS", ICAL_BY_SETPOS_SIZE, -1, 0},
408};
409
410static const char *icalrecur_first_clause(struct icalrecur_parser *parser)
411{
412 char *idx;
413
414 parser->this_clause = parser->copy;
415
416 idx = strchr(parser->this_clause, ';');
417
418 if (idx == 0) {
419 parser->next_clause = 0;
420 return 0;
421 }
422
423 *idx = 0;
424 idx++;
425 parser->next_clause = idx;
426
427 return parser->this_clause;
428}
429
430static const char *icalrecur_next_clause(struct icalrecur_parser *parser)
431{
432 char *idx;
433
434 parser->this_clause = parser->next_clause;
435
436 if (parser->this_clause == 0) {
437 return 0;
438 }
439
440 idx = strchr(parser->this_clause, ';');
441
442 if (idx == 0) {
443 parser->next_clause = 0;
444 } else {
445 *idx = 0;
446 idx++;
447 parser->next_clause = idx;
448 }
449
450 return parser->this_clause;
451}
452
453static void icalrecur_clause_name_and_value(struct icalrecur_parser *parser,
454 char **name, char **value)
455{
456 char *idx;
457
458 *name = parser->this_clause;
459
460 idx = strchr(parser->this_clause, '=');
461
462 if (idx == 0) {
463 *name = 0;
464 *value = 0;
465 return;
466 }
467
468 *idx = 0;
469 idx++;
470 *value = idx;
471}
472
473/*
474 * We expect BYHOUR, BYMINUTE, and BYSECOND data to be sorted.
475 */
476static void sort_byrules(icalrecurrence_by_data *by)
477{
478 short *array = by->data;
479
480 int i, j;
481
482 for (i = 1; i < by->size; i++) {
483 for (j = i - 1; j >= 0 && array[j] > array[j + 1]; j--) {
484 short tmp = array[j + 1];
485
486 array[j + 1] = array[j];
487 array[j] = tmp;
488 }
489 }
490}
491
492/*
493 * Sort BYSETPOS list in ascending order of magnitude,
494 * with negatives after positives
495 */
496static void sort_bysetpos(icalrecurrence_by_data *by)
497{
499#define SIGN(A) ((A) < 0 ? -1 : 1)
501 short *array = by->data;
502
503 int i, j;
504
505 for (i = 1; i < by->size; i++) {
506 for (j = i - 1;
507 j >= 0 && ((SIGN(array[j]) == SIGN(array[j + 1]) && abs(array[j]) > abs(array[j + 1])) ||
508 (array[j] < 0 && array[j + 1] > 0));
509 j--) {
510 short tmp = array[j + 1];
511
512 array[j + 1] = array[j];
513 array[j] = tmp;
514 }
515 }
516#undef SIGN
517}
518
519/* returns < 0 if a parsing problem:
520 -2 if an RSCALE rule is encountered yet we don't RSCALE support enabled
521 -1 for all other parsing problems
522*/
523static int icalrecur_add_byrules(const struct icalrecur_parser *parser, icalrecurrence_by_data *by,
524 int min, int size, char *vals)
525{
526 char *t, *n;
527 int i = 0;
528 int max = size - (min == 0);
529
530 n = vals;
531
532 if (!icalrecur_resize_by(by, size)) {
533 return -1;
534 }
535
536 while (n != 0) {
537 if (i == size) {
538 return -1;
539 }
540
541 t = n;
542
543 n = strchr(t, ',');
544
545 if (n != 0) {
546 *n = 0;
547 n++;
548 }
549
550 // empty string is not allowed here
551 if (!*t) {
552 return -1;
553 }
554
555 char *t_end;
556 long v = strtol(t, &t_end, 10);
557
558 // We check for parsing errors later, but not if the string ends with 'L',
559 // so explicitly check the value here.
560 if (t == t_end) {
561 return -1;
562 }
563 t = t_end;
564
565 /* Sanity check value */
566 if (v < 0) {
567 if (min >= 0 || v <= -max) {
568 return -1;
569 }
570 } else if (v > 0) {
571 if (v >= max) {
572 return -1;
573 }
574 } else if (min) {
575 return -1;
576 }
577
578 if (*t) {
579 /* Check for leap month suffix (RSCALE only) */
580 if (by == &parser->rt->by[ICAL_BY_MONTH] && strcmp(t, "L") == 0) {
581 /* The "L" suffix in a BYMONTH recur-rule-part
582 is encoded by setting a high-order bit */
583 v |= LEAP_MONTH;
584 } else {
585 return -1;
586 }
587 }
588
589 by->data[i++] = (short)v;
590 }
591
592 if (!icalrecur_resize_by(by, i)) {
593 return -1;
594 }
595
596 /* Sort time bylists.
597 * Date bylists do not require sorting because they are implemented
598 * differently (with a bitmask), and are not directly used to find
599 * the next occurrence.
600 */
601 if (by == &parser->rt->by[ICAL_BY_HOUR] ||
602 by == &parser->rt->by[ICAL_BY_MINUTE] ||
603 by == &parser->rt->by[ICAL_BY_SECOND]) {
604 sort_byrules(by);
605 }
606 /* BYSETPOS is sorted specially */
607 else if (by == &parser->rt->by[ICAL_BY_SET_POS]) {
608 sort_bysetpos(by);
609 }
610
611 return 0;
612}
613
614/*
615 * Days in the BYDAY rule are expected by the code to be sorted, and while
616 * this may be the common case, the RFC doesn't actually mandate it. This
617 * function sorts the days taking into account the first day of week.
618 */
619static void sort_bydayrules(struct icalrecur_parser *parser)
620{
621 icalrecurrence_by_data *by = &parser->rt->by[ICAL_BY_DAY];
622 short *array = by->data;
623
624 int week_start, i, j;
625
626 week_start = (int)parser->rt->week_start;
627
628 for (i = 0; i < by->size; i++) {
629 for (j = 0; j < i; j++) {
630 int one = (int)icalrecurrencetype_day_day_of_week(array[j]) - week_start;
631 if (one < 0) {
632 one += 7;
633 }
634 int two = (int)icalrecurrencetype_day_day_of_week(array[i]) - week_start;
635 if (two < 0) {
636 two += 7;
637 }
638
639 if (one > two) {
640 short tmp = array[j];
641
642 array[j] = array[i];
643 array[i] = tmp;
644 }
645 }
646 }
647}
648
649static int icalrecur_add_bydayrules(struct icalrecur_parser *parser,
650 const char *vals)
651{
652 char *t, *n;
653 icalrecurrence_by_data *by = &parser->rt->by[ICAL_BY_DAY];
654
655 char *vals_copy;
656 int idx = 0;
657
658 if (!icalrecur_resize_by(by, ICAL_BY_DAY_SIZE)) {
659 return -1;
660 }
661
662 vals_copy = icalmemory_strdup(vals);
663 n = vals_copy;
664
665 while (n != 0) {
666 int sign = 1;
667 signed char weekno;
669
670 if (idx >= by->size) {
671 icalmemory_free_buffer(vals_copy);
672 return -1;
673 }
674
675 t = n;
676
677 n = strchr(t, ',');
678
679 if (n != 0) {
680 *n = 0;
681 n++;
682 }
683
684 // empty string is not allowed here
685 if (!t[0]) {
686 icalmemory_free_buffer(vals_copy);
687 return -1;
688 }
689
690 /* Get Optional weekno */
691 char *t_end;
692 const long tmpl = strtol(t, &t_end, 10);
693 weekno = (signed char)tmpl;
694
695 // overflow?
696 /* cppcheck-suppress knownConditionTrueFalse */
697 if (weekno != tmpl) {
698 icalmemory_free_buffer(vals_copy);
699 return -1;
700 }
701
702 // WeekNo 0 doesn't exist
703 if ((weekno == 0) && (t != t_end)) {
704 icalmemory_free_buffer(vals_copy);
705 return -1;
706 }
707 t = t_end;
708
709 if (weekno < 0) {
710 weekno = -weekno;
711 sign = -1;
712 }
713
714 /* Outlook/Exchange generate "BYDAY=MO, FR" and "BYDAY=2 TH".
715 * Cope with that.
716 */
717 if (*t == ' ') {
718 t++;
719 }
720
722
723 /* Sanity check value */
724 if (wd == ICAL_NO_WEEKDAY || weekno >= ICAL_BY_WEEKNO_SIZE) {
725 icalmemory_free_buffer(vals_copy);
726 return -1;
727 }
728
729 by->data[idx++] = icalrecurrencetype_encode_day(wd, sign * weekno);
730 }
731
732 icalmemory_free_buffer(vals_copy);
733
734 if (!icalrecur_resize_by(by, idx)) {
735 return -1;
736 }
737
738 sort_bydayrules(parser);
739
740 return 0;
741}
742
744{
745 struct icalrecurrencetype *rule;
746
747 rule = (struct icalrecurrencetype *)icalmemory_new_buffer(sizeof(*rule));
748
749 if (!rule) {
750 return NULL;
751 }
752
753 memset(rule, 0, sizeof(*rule));
754 rule->refcount = 1;
755 icalrecurrencetype_clear(rule);
756
757 return rule;
758}
759
760static void icalrecurrencetype_free(struct icalrecurrencetype *recur, int free_self)
761{
763#define SAFEFREE(p) \
764 if (p) { \
765 icalmemory_free_buffer(p); \
766 (p) = 0; \
767 }
769
770 SAFEFREE(recur->rscale);
771 for (int i = 0; i < ICAL_BY_NUM_PARTS; i++) {
772 SAFEFREE(recur->by[i].data);
773 }
774
775#undef SAFEFREE
776
777 if (free_self) {
779 }
780}
781
783{
784 icalerror_check_arg_rv((recur != NULL), "recur");
785 icalerror_check_arg_rv((recur->refcount > 0), "recur->refcount > 0");
786
787 recur->refcount++;
788}
789
791{
792 icalerror_check_arg_rv((recur != NULL), "recur");
793 icalerror_check_arg_rv((recur->refcount > 0), "recur->refcount > 0");
794
795 recur->refcount--;
796
797 if (recur->refcount != 0) {
798 return;
799 }
800
801 icalrecurrencetype_free(recur, 1);
802}
803
804static void *icalrecur_memdup(void *p, size_t size, int *error)
805{
806 if ((p == NULL) || (size == 0)) {
807 return p;
808 }
809
810 void *newp = icalmemory_new_buffer(size);
811 if (newp) {
812 memcpy(newp, p, size);
813 } else {
814 *error = 1;
815 }
816
817 return newp;
818}
819
820static icalrecurrence_by_data icalrecur_by_dup(icalrecurrence_by_data *by, int *error)
821{
822 icalrecurrence_by_data newby = {0, 0};
823
824 newby.data = icalrecur_memdup(by->data, (size_t)by->size * sizeof(by->data[0]), error);
825 if (newby.data) {
826 newby.size = by->size;
827 }
828
829 return newby;
830}
831
833{
834 struct icalrecurrencetype *res;
835 int error = 0;
836
837 icalerror_check_arg_rz((recur != NULL), "recur");
838
840 if (!res) {
841 return NULL;
842 }
843
844 memcpy(res, recur, sizeof(*res));
845
846 res->refcount = 1;
847
848 if (res->rscale) {
849 res->rscale = icalmemory_strdup(res->rscale);
850 if (!res->rscale) {
851 error = 1;
852 }
853 }
854
855 for (int i = 0; i < ICAL_BY_NUM_PARTS; i++) {
856 icalrecurrence_by_data *src_by = &recur->by[i];
857 icalrecurrence_by_data *dst_by = &res->by[i];
858 *dst_by = icalrecur_by_dup(src_by, &error);
859 }
860
861 if (error) {
862 icalrecurrencetype_free(res, 1);
863 return NULL;
864 }
865
866 return res;
867}
868
870{
871 struct icalrecur_parser parser = {0};
873
874 icalerror_check_arg_re(str != 0, "str", 0);
875
876 parser.rt = icalrecurrencetype_new();
877 if (!parser.rt) {
878 return NULL;
879 }
880
881 /* Set up the parser struct */
882 parser.rule = str;
883 parser.copy = icalmemory_strdup(parser.rule);
884 parser.this_clause = parser.copy;
885
886 if (parser.copy == 0) {
888 icalrecurrencetype_unref(parser.rt);
889 return NULL;
890 }
891
892 /* Loop through all of the clauses */
893 for (icalrecur_first_clause(&parser);
894 parser.this_clause != 0; icalrecur_next_clause(&parser)) {
895 char *name, *value;
896 int r = 0;
897
898 icalrecur_clause_name_and_value(&parser, &name, &value);
899
900 if (name == 0) {
901 if (strlen(parser.this_clause) > 0) {
902 r = -1;
903 } else {
904 /* Hit an empty name/value pair,
905 but we're also at the end of the string.
906 This was probably a trailing semicolon with no data
907 (e.g. "FREQ=WEEKLY;INTERVAL=1;BYDAY=MO;")
908 */
909 break;
910 }
911 } else if (strcasecmp(name, "FREQ") == 0) {
912 if (parser.rt->freq != ICAL_NO_RECURRENCE) {
913 /* Don't allow multiple FREQs */
914 r = -1;
915 } else {
916 parser.rt->freq = icalrecur_string_to_freq(value);
917 if (parser.rt->freq == ICAL_NO_RECURRENCE) {
918 r = -1;
919 }
920 }
921 } else if (strcasecmp(name, "RSCALE") == 0) {
922 if (parser.rt->rscale != NULL) {
923 /* Don't allow multiple RSCALEs */
924 r = -1;
925 } else {
926 parser.rt->rscale = icalmemory_strdup(value);
927 }
928 } else if (strcasecmp(name, "SKIP") == 0) {
929 if (parser.rt->skip != ICAL_SKIP_OMIT) {
930 /* Don't allow multiple SKIPs */
931 r = -1;
932 } else {
933 parser.rt->skip = icalrecur_string_to_skip(value);
934 if (parser.rt->skip == ICAL_SKIP_UNDEFINED) {
935 r = -1;
936 }
937 }
938 } else if (strcasecmp(name, "COUNT") == 0) {
939 if (parser.rt->count > 0 || !icaltime_is_null_time(parser.rt->until)) {
940 /* Don't allow multiple COUNTs, or both COUNT and UNTIL */
941 r = -1;
942 } else {
943 parser.rt->count = 0;
944 char *v_end;
945 const long v = strtol(value, &v_end, 10);
946 if (value != v_end) {
947 parser.rt->count = v;
948 /* don't allow count to be less than 1 */
949 }
950 if (parser.rt->count < 1) {
951 r = -1;
952 }
953 }
954 } else if (strcasecmp(name, "UNTIL") == 0) {
955 if (parser.rt->count > 0 || !icaltime_is_null_time(parser.rt->until)) {
956 /* Don't allow multiple COUNTs, or both COUNT and UNTIL */
957 r = -1;
958 } else {
959 parser.rt->until = icaltime_from_string(value);
960 if (icaltime_is_null_time(parser.rt->until)) {
961 r = -1;
962 }
963 }
964 } else if (strcasecmp(name, "INTERVAL") == 0) {
965 if (parser.rt->interval > 1) {
966 /* Don't allow multiple INTERVALs */
967 r = -1;
968 } else {
969 parser.rt->interval = 0;
970 char *v_temp;
971 const long tmp = strtol(value, &v_temp, 10);
972 if (value != v_temp) {
973 parser.rt->interval = (short)tmp;
974
975 // overflow?
976 /* cppcheck-suppress knownConditionTrueFalse */
977 if (parser.rt->interval != tmp) {
978 parser.rt->interval = 0;
979 }
980 }
981 /* don't allow an interval to be less than 1
982 (RFC specifies an interval must be a positive integer) */
983 if (parser.rt->interval < 1) {
984 r = -1;
985 }
986 }
987 } else if (strcasecmp(name, "WKST") == 0) {
988 if (parser.rt->week_start != ICAL_MONDAY_WEEKDAY) {
989 /* Don't allow multiple WKSTs */
990 r = -1;
991 } else {
992 parser.rt->week_start = icalrecur_string_to_weekday(value);
993 if (parser.rt->week_start == ICAL_NO_WEEKDAY) {
994 r = -1;
995 } else {
996 sort_bydayrules(&parser);
997 }
998 }
999 } else if (strncasecmp(name, "BY", 2) == 0) {
1000 r = -1;
1001
1002 for (byrule = 0; byrule < ICAL_BY_NUM_PARTS; ++byrule) {
1003 if (strcasecmp(name + 2, recur_map[byrule].str + 2) == 0) {
1004 if (byrule == ICAL_BY_DAY) {
1005 r = icalrecur_add_bydayrules(&parser, value);
1006 } else {
1007 icalrecurrence_by_data *by = &parser.rt->by[byrule];
1008 r = icalrecur_add_byrules(&parser, by,
1009 recur_map[byrule].min,
1010 recur_map[byrule].size,
1011 value);
1012 }
1013 break;
1014 }
1015 }
1016 } else {
1017 r = -1;
1018 }
1019
1020 if (r) {
1021 /* Note: silently ignore when we have a leap month, yet don't have RSCALE support.
1022 The magic value "-2" indicates when that happens.
1023 */
1024 if (r != -2) {
1026 }
1027 icalrecurrencetype_clear(parser.rt);
1028 break;
1029 }
1030 }
1031
1032 for (byrule = 0; byrule < ICAL_BY_NUM_PARTS; ++byrule) {
1033 icalrecurrence_by_data *by = &parser.rt->by[byrule];
1034
1035 if (by->size > 0 &&
1036 expand_map[parser.rt->freq].map[byrule] == ILLEGAL) {
1037 ical_invalid_rrule_handling rruleHandlingSetting =
1039
1040 if (rruleHandlingSetting == ICAL_RRULE_TREAT_AS_ERROR) {
1042 icalrecurrencetype_clear(parser.rt);
1043 break;
1044 } else {
1045 icalrecur_free_by(by);
1046 }
1047 }
1048 }
1049
1050 icalmemory_free_buffer(parser.copy);
1051
1052 if (parser.rt->freq == ICAL_NO_RECURRENCE) {
1053 icalrecurrencetype_unref(parser.rt);
1054 parser.rt = NULL;
1055 }
1056
1057 return parser.rt;
1058}
1059
1061{
1062 char *buf;
1063
1064 buf = icalrecurrencetype_as_string_r(recur);
1066 return buf;
1067}
1068
1070{
1071 char *str;
1072 char *str_p;
1073 size_t buf_sz = 200;
1074 char temp[20] = {0};
1075 int i, j;
1076
1077 if (recur == 0 || recur->freq == ICAL_NO_RECURRENCE) {
1078 return 0;
1079 }
1080
1081 str = (char *)icalmemory_new_buffer(buf_sz);
1082 str_p = str;
1083
1084 if (recur->rscale != 0) {
1085 icalmemory_append_string(&str, &str_p, &buf_sz, "RSCALE=");
1086 icalmemory_append_string(&str, &str_p, &buf_sz, recur->rscale);
1087
1088 /* Omit is the default, so no need to write that out */
1089 if (recur->skip != ICAL_SKIP_OMIT) {
1090 const char *skipstr = icalrecur_skip_to_string(recur->skip);
1091 icalmemory_append_string(&str, &str_p, &buf_sz, ";SKIP=");
1092 icalmemory_append_string(&str, &str_p, &buf_sz, skipstr);
1093 }
1094 icalmemory_append_char(&str, &str_p, &buf_sz, ';');
1095 }
1096
1097 icalmemory_append_string(&str, &str_p, &buf_sz, "FREQ=");
1098 icalmemory_append_string(&str, &str_p, &buf_sz,
1100
1101 /* 1 is the default, so no need to write that out */
1102 if (recur->interval != 1) {
1103 snprintf(temp, sizeof(temp), "%d", recur->interval);
1104 icalmemory_append_string(&str, &str_p, &buf_sz, ";INTERVAL=");
1105 icalmemory_append_string(&str, &str_p, &buf_sz, temp);
1106 }
1107
1108 /* Monday is the default, so no need to write that out */
1109 if (recur->week_start != ICAL_MONDAY_WEEKDAY &&
1110 recur->week_start != ICAL_NO_WEEKDAY) {
1111 int dow = (int)icalrecurrencetype_day_day_of_week(recur->week_start);
1112 const char *daystr = icalrecur_weekday_to_string((enum icalrecurrencetype_weekday)dow);
1113 icalmemory_append_string(&str, &str_p, &buf_sz, ";WKST=");
1114 icalmemory_append_string(&str, &str_p, &buf_sz, daystr);
1115 }
1116
1117 for (j = 0; j < ICAL_BY_NUM_PARTS; j++) {
1118 const icalrecurrence_by_data *by = &recur->by[j];
1119
1120 /* Skip unused arrays */
1121 if (by->size > 0) {
1122 icalmemory_append_char(&str, &str_p, &buf_sz, ';');
1123 icalmemory_append_string(&str, &str_p, &buf_sz, recur_map[j].str);
1124 icalmemory_append_char(&str, &str_p, &buf_sz, '=');
1125
1126 int limit = recur_map[j].size - 1;
1127 for (i = 0; i < limit && i < by->size; i++) {
1128 if (j == ICAL_BY_DAY) {
1129 int pos = icalrecurrencetype_day_position(by->data[i]);
1130 int dow = (int)icalrecurrencetype_day_day_of_week(by->data[i]);
1131 const char *daystr = icalrecur_weekday_to_string((enum icalrecurrencetype_weekday)dow);
1132
1133 if (pos == 0) {
1134 icalmemory_append_string(&str, &str_p, &buf_sz, daystr);
1135 } else {
1136 snprintf(temp, sizeof(temp), "%d%s", pos, daystr);
1137 icalmemory_append_string(&str, &str_p, &buf_sz, temp);
1138 }
1139
1140 } else if (j == ICAL_BY_MONTH &&
1141 icalrecurrencetype_month_is_leap(by->data[i])) {
1142 snprintf(temp, sizeof(temp), "%dL",
1143 icalrecurrencetype_month_month(by->data[i]));
1144 icalmemory_append_string(&str, &str_p, &buf_sz, temp);
1145 } else {
1146 snprintf(temp, sizeof(temp), "%d", by->data[i]);
1147 icalmemory_append_string(&str, &str_p, &buf_sz, temp);
1148 }
1149
1150 if ((i + 1) < limit && by->size > i + 1) {
1151 icalmemory_append_char(&str, &str_p, &buf_sz, ',');
1152 }
1153 }
1154 }
1155 }
1156
1157 if (recur->until.year != 0) {
1158 temp[0] = 0;
1159 if (recur->until.is_date) {
1160 print_date_to_string(temp, &recur->until);
1161 } else {
1162 print_datetime_to_string(temp, &recur->until);
1163 }
1164
1165 icalmemory_append_string(&str, &str_p, &buf_sz, ";UNTIL=");
1166 icalmemory_append_string(&str, &str_p, &buf_sz, temp);
1167 }
1168
1169 else if (recur->count != 0) {
1170 snprintf(temp, sizeof(temp), "%d", recur->count);
1171 icalmemory_append_string(&str, &str_p, &buf_sz, ";COUNT=");
1172 icalmemory_append_string(&str, &str_p, &buf_sz, temp);
1173 }
1174
1175 return str;
1176}
1177
1178/************************* occurrence iteration routines ******************/
1179
1181/* Number of bits in an unsigned long */
1182#define BITS_PER_LONG ((unsigned short)(8 * sizeof(unsigned long)))
1183
1184/* Number of longs in mask of n bits */
1185#define LONGS_PER_BITS(n) (((n) + BITS_PER_LONG - 1) / BITS_PER_LONG)
1186
1187#define ICAL_YEARDAYS_MASK_SIZE (ICAL_BY_YEARDAY_SIZE + 7)
1188#define ICAL_YEARDAYS_MASK_OFFSET 4
1190
1191typedef struct icalrecurrence_iterator_by_data {
1192 icalrecurrence_by_data by;
1193 short index;
1194 short orig_data;
1195
1196 // Static buffer for BY values that need to be modified by the iterator, so we don't modify the rule.
1197 // We have one value for each BY rule.
1198 short buffer_value;
1199} icalrecurrence_iterator_by_data;
1200
1201struct icalrecur_iterator_impl {
1202 struct icaltimetype dtstart; /* copy of DTSTART: to fill in defaults */
1203 struct icalrecurrencetype *rule; /* reference to RRULE */
1204
1205 struct icaltimetype rstart; /* DTSTART in RSCALE */
1206 struct icaltimetype istart; /* Gregorian start time for iterator */
1207 struct icaltimetype iend; /* Gregorian end time for iterator */
1208 struct icaltimetype last; /* last time returned from iterator */
1209 int32_t occurrence_no; /* number of steps made on the iterator */
1210
1211 int32_t set_pos; /* our position in the recurrence set */
1212 int32_t recurrence_set_size; /* the size of the recurrence set */
1213 short sp_idxp, sp_idxn; /* positive and negative BYSETPOS indices */
1214 short sp_pmax; /* the last index of the BYSETPOS array with a positive value */
1215
1216#if defined(HAVE_LIBICU)
1217 UCalendar *greg; /* Gregorian calendar */
1218 UCalendar *rscale; /* RSCALE calendar */
1219#endif
1220
1221 struct icaltimetype period_start; /* Start date of monthly/yearly period */
1222
1223 /* days[] is a bitmask of year days. A bit value of 1 marks an occurrence.
1224 The size of the bitmask is 7 + max days in year to accommodate full first
1225 and last weeks of the year: up to 3 days in previous year and
1226 up to 4 days in following year. As a result, the days are offset by 4:
1227 bit 0 is day -3 (3rd last day of previous year) and bit 4 is day 1
1228 of the current year. Days in the following year use higher day numbers,
1229 e.g. day 367 is day 1 or 2 of following year depending on whether the
1230 current year is a leap year.
1231
1232 days_index is the day of year of the next occurrence,
1233 with a range of -3 to 4 + days in year.
1234 */
1235 unsigned long days[LONGS_PER_BITS(ICAL_YEARDAYS_MASK_SIZE)];
1236 short days_index;
1237
1239 icalrecurrence_iterator_by_data bydata[ICAL_BY_NUM_PARTS];
1240};
1241
1242static void daysmask_clearall(unsigned long mask[])
1243{
1244 memset(mask, 0,
1245 sizeof(unsigned long) * LONGS_PER_BITS(ICAL_YEARDAYS_MASK_SIZE));
1246}
1247
1248static
1249#if defined(UNDEFINED_SANITIZER) && defined(__clang__)
1250 __attribute__((no_sanitize("integer")))
1251#endif
1252 unsigned long makeMask(unsigned long mask, int leftshift)
1253{
1254 return mask << leftshift;
1255}
1256
1257/* Days of year that have a bit in the year days bitmask */
1258static bool daysmask_in_range(int n)
1259{
1260 return n >= -ICAL_YEARDAYS_MASK_OFFSET && n < ICAL_YEARDAYS_MASK_SIZE; //NOLINT(readability-implicit-bool-conversion)
1261}
1262
1263static void daysmask_set_range(unsigned long days[], int fromDayIncl, int untilDayExcl, int v)
1264{
1265 if (fromDayIncl < -ICAL_YEARDAYS_MASK_OFFSET) {
1266 fromDayIncl = -ICAL_YEARDAYS_MASK_OFFSET;
1267 }
1268 if (untilDayExcl > ICAL_YEARDAYS_MASK_SIZE) {
1269 untilDayExcl = ICAL_YEARDAYS_MASK_SIZE;
1270 }
1271 if (fromDayIncl >= untilDayExcl) {
1272 return;
1273 }
1274
1275 int fromBitIdx = fromDayIncl + ICAL_YEARDAYS_MASK_OFFSET;
1276 int untilBitIdx = untilDayExcl + ICAL_YEARDAYS_MASK_OFFSET;
1277
1278 for (int word_idx = fromBitIdx / BITS_PER_LONG;
1279 word_idx < (int)((untilBitIdx + BITS_PER_LONG - 1) / BITS_PER_LONG);
1280 word_idx++) {
1281 int lowerBitIdxIncl = (fromBitIdx <= (int)(word_idx * BITS_PER_LONG))
1282 ? 0
1283 : (fromBitIdx - (int)(word_idx * BITS_PER_LONG));
1284 int upperBitIdxExcl = (untilBitIdx >= (int)((word_idx + 1) * BITS_PER_LONG))
1285 ? (int)BITS_PER_LONG
1286 : (int)(untilBitIdx - (int)(word_idx * BITS_PER_LONG));
1287
1288 unsigned long mask = (unsigned long)-1;
1289 if (lowerBitIdxIncl > 0) {
1290 mask &= makeMask(((unsigned long)-1), lowerBitIdxIncl);
1291 }
1292 if ((upperBitIdxExcl > 0) && (upperBitIdxExcl < (int)BITS_PER_LONG)) {
1293 mask &= ((unsigned long)-1) >> (BITS_PER_LONG - upperBitIdxExcl);
1294 }
1295
1296 if (v) {
1297 days[word_idx] |= mask;
1298 } else {
1299 days[word_idx] &= ~mask;
1300 }
1301 }
1302}
1303
1304/* Returns the previous value of bit n, or v (no change) for a day outside the bitmask */
1305static int daysmask_setbit(unsigned long mask[], int n, int v)
1306{
1307 int prev;
1308
1309 if (!daysmask_in_range(n)) {
1310 return v;
1311 }
1312
1313 n += ICAL_YEARDAYS_MASK_OFFSET;
1314
1315 if (n >= 0) {
1316 prev = (mask[n / BITS_PER_LONG] & (1UL << (n % BITS_PER_LONG))) ? 1 : 0;
1317 } else {
1318 prev = (mask[n / BITS_PER_LONG] & (1UL >> (-n % BITS_PER_LONG))) ? 1 : 0;
1319 }
1320 if (v != prev) {
1321 if (v) {
1322 if (n >= 0) {
1323 mask[n / BITS_PER_LONG] |= (1UL << (n % BITS_PER_LONG));
1324 } else {
1325 mask[n / BITS_PER_LONG] |= (1UL >> (-n % BITS_PER_LONG));
1326 }
1327 } else {
1328 if (n >= 0) {
1329 mask[n / BITS_PER_LONG] &= ~(1UL << (n % BITS_PER_LONG));
1330 } else {
1331 mask[n / BITS_PER_LONG] &= ~(1UL >> (-n % BITS_PER_LONG));
1332 }
1333 }
1334 }
1335
1336 return prev;
1337}
1338
1339static unsigned long daysmask_getbit(const unsigned long mask[], int n)
1340{
1341 if (!daysmask_in_range(n)) {
1342 return 0;
1343 }
1344
1345 n += ICAL_YEARDAYS_MASK_OFFSET;
1346 return (mask[n / BITS_PER_LONG] >> (n % BITS_PER_LONG)) & 1;
1347}
1348
1349/* Marks day of year doy as an occurrence; days outside the bitmask are dropped */
1350static void daysmask_add_day(icalrecur_iterator *impl, int doy)
1351{
1352 if (!daysmask_in_range(doy)) {
1353 return;
1354 }
1355
1356 daysmask_setbit(impl->days, doy, 1);
1357 if (doy < impl->days_index) {
1358 impl->days_index = (short)doy;
1359 }
1360}
1361
1362static bool has_by_data(icalrecur_iterator *impl, icalrecurrencetype_byrule byrule)
1363{
1364 return (impl->bydata[byrule].orig_data == 1);
1365}
1366
1367static void recur_iterator_set_static_single_by_value(icalrecur_iterator *impl,
1368 icalrecurrencetype_byrule byrule, short value)
1369{
1370 icalrecurrence_iterator_by_data *by = &impl->bydata[byrule];
1371 by->by.size = 1;
1372 by->by.data = &by->buffer_value;
1373 by->by.data[0] = value;
1374}
1375
1376static void setup_defaults(icalrecur_iterator *impl,
1377 icalrecurrencetype_byrule byrule, int deftime)
1378{
1379 icalrecurrencetype_frequency freq = impl->rule->freq;
1380
1381 if (impl->dtstart.is_date && recur_map[byrule].isTime) {
1382 // The BYSECOND, BYMINUTE and BYHOUR rule parts MUST NOT be specified
1383 // when the associated "DTSTART" property has a DATE value type.
1384 // These rule parts MUST be ignored in RECUR value that violate the
1385 // above requirement (e.g., generated by applications that pre-date
1386 // this revision of iCalendar).
1387 recur_iterator_set_static_single_by_value(impl, byrule, 0);
1388 } else if (expand_map[freq].map[byrule] == EXPAND) {
1389 /* Re-write the BY rule arrays with data from the DTSTART time so
1390 we don't have to explicitly deal with DTSTART */
1391 if (impl->bydata[byrule].by.size == 0) {
1392 recur_iterator_set_static_single_by_value(impl, byrule, (short)deftime);
1393 }
1394 }
1395}
1396
1400static int weeks_in_year(int year, icalrecurrencetype_weekday week_start)
1401{
1402 /* Long years start on the 4th day of the week, or leap years on the 3rd
1403 (Thu or Wed for ISO weeks, which begin on Monday) */
1405 int pos = (dow - (int)week_start + 7) % 7;
1406 int is_long = (pos == 3 || (pos == 2 && icaltime_is_leap_year(year)));
1407
1408 return (52 + is_long);
1409}
1410
1412static int __greg_month_diff(icaltimetype a, icaltimetype b)
1413{
1414 return (12 * (b.year - a.year) + (b.month - a.month));
1415}
1416
1417static void __get_start_time(icalrecur_iterator *impl, icaltimetype date,
1418 int *hour, int *minute, int *second)
1419{
1420 icalrecurrencetype_frequency freq = impl->rule->freq;
1421
1422 if (freq == ICAL_HOURLY_RECURRENCE) {
1423 *hour = date.hour;
1424 } else if (has_by_data(impl, ICAL_BY_HOUR)) {
1425 *hour = impl->bydata[ICAL_BY_HOUR].by.data[0];
1426 } else {
1427 *hour = impl->rstart.hour;
1428 }
1429
1430 if (freq == ICAL_MINUTELY_RECURRENCE) {
1431 *minute = date.minute;
1432 } else if (has_by_data(impl, ICAL_BY_MINUTE)) {
1433 *minute = impl->bydata[ICAL_BY_MINUTE].by.data[0];
1434 } else {
1435 *minute = impl->rstart.minute;
1436 }
1437
1438 if (freq == ICAL_SECONDLY_RECURRENCE) {
1439 *second = date.second;
1440 } else if (has_by_data(impl, ICAL_BY_SECOND)) {
1441 *second = impl->bydata[ICAL_BY_SECOND].by.data[0];
1442 } else {
1443 *second = impl->rstart.second;
1444 }
1445}
1446
1447static int __day_diff(icalrecur_iterator *impl, icaltimetype a, icaltimetype b);
1448
1449#if defined(HAVE_LIBICU)
1450/*
1451 * Callbacks for recurrence rules with RSCALE support (using ICU)
1452 *
1453 * References:
1454 * - tools.ietf.org/html/rfc7529
1455 * - en.wikipedia.org/wiki/Intercalation_%28timekeeping%29
1456 * - icu-project.org/apiref/icu4c/ucal_8h.html
1457 * - cldr.unicode.org/development/development-process/design-proposals/chinese-calendar-support
1458 * - cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types
1459 *
1460 * ICU Notes:
1461 * - Months are 0-based
1462 * - Leap months in Chinese and Hebrew calendars are handled differently
1463 */
1464
1466{
1467 UErrorCode status = U_ZERO_ERROR;
1468 UEnumeration *en;
1469 icalarray *calendars;
1470 const char *cal;
1471
1472 calendars = icalarray_new(sizeof(const char **), 20);
1473
1474 en = ucal_getKeywordValuesForLocale("calendar", "", false, &status);
1475 while ((cal = uenum_next(en, NULL, &status))) {
1476 cal = icalmemory_tmp_copy(cal);
1477 icalarray_append(calendars, (const void *)&cal);
1478 }
1479 uenum_close(en);
1480
1481 return calendars;
1482}
1483
1484static void set_second(icalrecur_iterator *impl, int second)
1485{
1486 ucal_set(impl->rscale, UCAL_SECOND, (int32_t)second);
1487}
1488
1489static void set_minute(icalrecur_iterator *impl, int minute)
1490{
1491 ucal_set(impl->rscale, UCAL_MINUTE, (int32_t)minute);
1492}
1493
1494static void set_hour(icalrecur_iterator *impl, int hour)
1495{
1496 ucal_set(impl->rscale, UCAL_HOUR_OF_DAY, (int32_t)hour);
1497}
1498
1499static void __set_month(icalrecur_iterator *impl, int month)
1500{
1501 bool is_leap_month = icalrecurrencetype_month_is_leap(month);
1502
1503 month = icalrecurrencetype_month_month(month) - 1; /* UCal is 0-based */
1504
1505 ucal_set(impl->rscale, UCAL_MONTH, (int32_t)month);
1506 if (is_leap_month) {
1507 ucal_set(impl->rscale, UCAL_IS_LEAP_MONTH, 1);
1508 }
1509}
1510
1511static int set_month(icalrecur_iterator *impl, int month)
1512{
1513 UErrorCode status = U_ZERO_ERROR;
1514 int actual_month;
1515
1516 __set_month(impl, month);
1517
1518 ucal_set(impl->rscale, UCAL_DAY_OF_MONTH, (int32_t)1);
1519
1520 actual_month = 1 + /* UCal is 0-based */
1521 (int)ucal_get(impl->rscale, UCAL_MONTH, &status);
1522
1523 if (ucal_get(impl->rscale, UCAL_IS_LEAP_MONTH, &status)) {
1524 actual_month |= LEAP_MONTH;
1525 }
1526
1527 if (actual_month != month) {
1528 switch (impl->rule->skip) {
1529 default:
1530 /* Should never get here! */
1531
1532 case ICAL_SKIP_OMIT:
1533 /* Invalid month */
1534 return 0;
1535
1536 case ICAL_SKIP_BACKWARD:
1537 /* Skip back to next valid month */
1538 ucal_add(impl->rscale, UCAL_MONTH, (int32_t)-1, &status);
1539 break;
1540
1541 case ICAL_SKIP_FORWARD:
1542 /* UCal skips forward to valid month by default */
1543 break;
1544 }
1545 }
1546
1547 return (1 + /* UCal is 0-based */
1548 (int)ucal_get(impl->rscale, UCAL_MONTH, &status));
1549}
1550
1551static int get_months_in_year(icalrecur_iterator *impl, int year)
1552{
1553 UErrorCode status = U_ZERO_ERROR;
1554
1555 if (year) {
1556 ucal_set(impl->rscale, UCAL_YEAR, (int32_t)year);
1557 }
1558
1559 return (1 + /* UCal is 0-based */
1560 (int)ucal_getLimit(impl->rscale, UCAL_MONTH,
1561 UCAL_ACTUAL_MAXIMUM, &status));
1562}
1563
1564static int get_days_in_year(icalrecur_iterator *impl, int year)
1565{
1566 UErrorCode status = U_ZERO_ERROR;
1567
1568 if (year) {
1569 ucal_set(impl->rscale, UCAL_YEAR, (int32_t)year);
1570 }
1571
1572 return (int)ucal_getLimit(impl->rscale, UCAL_DAY_OF_YEAR,
1573 UCAL_ACTUAL_MAXIMUM, &status);
1574}
1575
1576static void set_day_of_year(icalrecur_iterator *impl, int doy)
1577{
1578 if (doy < 1) {
1579 doy += get_days_in_year(impl, 0);
1580 }
1581
1582 ucal_set(impl->rscale, UCAL_DAY_OF_YEAR, (int32_t)doy);
1583}
1584
1585static int get_start_of_week(icalrecur_iterator *impl)
1586{
1587 UErrorCode status = U_ZERO_ERROR;
1588 int doy, dow;
1589
1590 doy = (int)ucal_get(impl->rscale, UCAL_DAY_OF_YEAR, &status);
1591 dow = (int)ucal_get(impl->rscale, UCAL_DAY_OF_WEEK, &status);
1592 dow -= (int)impl->rule->week_start;
1593 if (dow < 0) {
1594 dow += 7;
1595 }
1596
1597 return (doy - dow);
1598}
1599
1600static int get_day_of_week(icalrecur_iterator *impl)
1601{
1602 UErrorCode status = U_ZERO_ERROR;
1603
1604 return (int)ucal_get(impl->rscale, UCAL_DAY_OF_WEEK, &status);
1605}
1606
1607static int get_week_number(icalrecur_iterator *impl, struct icaltimetype tt)
1608{
1609 UErrorCode status = U_ZERO_ERROR;
1610 UDate last_millis;
1611 int month, weekno;
1612
1613 /* Save existing rscale date */
1614 last_millis = ucal_getMillis(impl->rscale, &status);
1615
1616 month = icalrecurrencetype_month_month(tt.month) - 1; /* UCal is 0-based */
1617 ucal_setDate(impl->rscale,
1618 (int32_t)tt.year, (int32_t)month, (int32_t)tt.day, &status);
1620 ucal_set(impl->rscale, UCAL_IS_LEAP_MONTH, 1);
1621 }
1622
1623 weekno = (int)ucal_get(impl->rscale, UCAL_WEEK_OF_YEAR, &status);
1624
1625 /* Restore saved rscale date */
1626 ucal_setMillis(impl->rscale, last_millis, &status);
1627
1628 return weekno;
1629}
1630
1631static int get_days_in_month(icalrecur_iterator *impl, int month, int year)
1632{
1633 UErrorCode status = U_ZERO_ERROR;
1634
1635 ucal_set(impl->rscale, UCAL_YEAR, (int32_t)year);
1636
1637 if (!month) {
1638 month = impl->rstart.month;
1639 }
1640 __set_month(impl, month);
1641
1642 return (int)ucal_getLimit(impl->rscale,
1643 UCAL_DAY_OF_MONTH, UCAL_ACTUAL_MAXIMUM, &status);
1644}
1645
1646static void prepare_rscale_adjusted(icalrecur_iterator *impl,
1647 int year, int month, int day, UErrorCode *status)
1648{
1649 ucal_set(impl->rscale, UCAL_YEAR, (int32_t)year);
1650
1651 if (!month) {
1652 month = impl->rstart.month;
1653 }
1654 __set_month(impl, month);
1655
1656 if (!day) {
1657 day = impl->rstart.day;
1658 } else if (day < 0) {
1659 day += 1 + (int)ucal_getLimit(impl->rscale, UCAL_DAY_OF_MONTH,
1660 UCAL_ACTUAL_MAXIMUM, status);
1661 }
1662 ucal_set(impl->rscale, UCAL_DAY_OF_MONTH, (int32_t)day);
1663}
1664
1665static int get_day_of_year(icalrecur_iterator *impl,
1666 int year, int month, int day)
1667{
1668 UErrorCode status = U_ZERO_ERROR;
1669 prepare_rscale_adjusted(impl, year, month, day, &status);
1670 return (int)ucal_get(impl->rscale, UCAL_DAY_OF_YEAR, &status);
1671}
1672
1673static int get_day_of_week_adjusted(icalrecur_iterator *impl,
1674 int year, int month, int day)
1675{
1676 UErrorCode status = U_ZERO_ERROR;
1677 prepare_rscale_adjusted(impl, year, month, day, &status);
1678 return (int)ucal_get(impl->rscale, UCAL_DAY_OF_WEEK, &status);
1679}
1680
1681static struct icaltimetype occurrence_as_icaltime(icalrecur_iterator *impl,
1682 int normalize)
1683{
1684 struct icaltimetype tt = impl->dtstart;
1685 UErrorCode status = U_ZERO_ERROR;
1686 UCalendar *cal = impl->rscale;
1687 int is_leap_month = 0;
1688
1689 if (normalize && (impl->rscale != impl->greg)) {
1690 /* Convert to Gregorian date */
1691 UDate millis = ucal_getMillis(impl->rscale, &status);
1692
1693 ucal_setMillis(impl->greg, millis, &status);
1694 cal = impl->greg;
1695 } else {
1696 is_leap_month =
1697 (int)ucal_get(impl->rscale, UCAL_IS_LEAP_MONTH, &status);
1698 }
1699
1700 tt.year = (int)ucal_get(cal, UCAL_YEAR, &status);
1701 tt.day = (int)ucal_get(cal, UCAL_DATE, &status);
1702 tt.month = 1 + /* UCal is 0-based */
1703 (int)ucal_get(cal, UCAL_MONTH, &status);
1704 if (is_leap_month) {
1705 tt.month |= LEAP_MONTH;
1706 }
1707
1708 if (!tt.is_date) {
1709 tt.hour = (int)ucal_get(cal, UCAL_HOUR_OF_DAY, &status);
1710 tt.minute = (int)ucal_get(cal, UCAL_MINUTE, &status);
1711 tt.second = (int)ucal_get(cal, UCAL_SECOND, &status);
1712 }
1713
1714 return tt;
1715}
1716
1717static struct icaltimetype __icaltime_from_day_of_year(icalrecur_iterator *impl,
1718 int day, int year, int *weekno)
1719{
1720 ucal_set(impl->rscale, UCAL_YEAR, (int32_t)year);
1721 if (day < 0) {
1722 day += get_days_in_year(impl, 0) + 1;
1723 }
1724
1725 ucal_set(impl->rscale, UCAL_DAY_OF_YEAR, (int32_t)day);
1726
1727 if (weekno) {
1728 UErrorCode status = U_ZERO_ERROR;
1729
1730 *weekno = (int)ucal_get(impl->rscale, UCAL_WEEK_OF_YEAR, &status);
1731 }
1732
1733 return occurrence_as_icaltime(impl, 0);
1734}
1735
1736static void increment_year(icalrecur_iterator *impl, int inc)
1737{
1738 UErrorCode status = U_ZERO_ERROR;
1739
1740 ucal_add(impl->rscale, UCAL_YEAR, (int32_t)inc, &status);
1741}
1742
1743static void __increment_month(icalrecur_iterator *impl, int inc)
1744{
1745 UErrorCode status = U_ZERO_ERROR;
1746
1747 ucal_add(impl->rscale, UCAL_MONTH, (int32_t)inc, &status);
1748}
1749
1750static void increment_monthday(icalrecur_iterator *impl, int inc)
1751{
1752 UErrorCode status = U_ZERO_ERROR;
1753
1754 ucal_add(impl->rscale, UCAL_DAY_OF_MONTH, (int32_t)inc, &status);
1755}
1756
1757static void increment_hour(icalrecur_iterator *impl, int inc)
1758{
1759 UErrorCode status = U_ZERO_ERROR;
1760
1761 ucal_add(impl->rscale, UCAL_HOUR_OF_DAY, (int32_t)inc, &status);
1762}
1763
1764static void increment_minute(icalrecur_iterator *impl, int inc)
1765{
1766 UErrorCode status = U_ZERO_ERROR;
1767
1768 ucal_add(impl->rscale, UCAL_MINUTE, (int32_t)inc, &status);
1769}
1770
1771static void increment_second(icalrecur_iterator *impl, int inc)
1772{
1773 UErrorCode status = U_ZERO_ERROR;
1774
1775 ucal_add(impl->rscale, UCAL_SECOND, (int32_t)inc, &status);
1776}
1777
1778static bool validate_byrule(icalrecur_iterator *impl,
1779 icalrecurrencetype_byrule byrule, UCalendarDateFields field,
1780 short (*decode_val)(short *, bool),
1781 bool decode_flags)
1782{
1783 if (has_by_data(impl, byrule)) {
1784 UErrorCode status = U_ZERO_ERROR;
1785 const icalrecurrence_by_data *by_ptr = &impl->bydata[byrule].by;
1786 short max =
1787 (short)ucal_getLimit(impl->rscale, field, UCAL_MAXIMUM, &status);
1788 short idx;
1789
1790 for (idx = 0; idx < by_ptr->size; idx++) {
1791 short val = decode_val ? decode_val(&by_ptr->data[idx], decode_flags) : by_ptr->data[idx];
1792
1793 if (abs(val) > max) {
1794 return false;
1795 }
1796 }
1797 }
1798
1799 return true;
1800}
1801
1802static short decode_month(short *month, bool is_hebrew)
1803{
1804 if (is_hebrew && *month > 5) { /* 5L == 0x1005 */
1805 /* Hebrew calendar:
1806 Translate RSCALE months to ICU (numbered 1-13, where 6 is leap).
1807 Hence, 5L maps to 6 and 6-12 map to 7-13. */
1809 }
1810
1811 return icalrecurrencetype_month_month(*month) - 1; /* UCal is 0-based */
1812}
1813
1814/* cppcheck-suppress constParameterCallback */
1815static short decode_day(short *day, bool flags) //NOLINT(readability-non-const-parameter)
1816{
1817 _unused(flags);
1818
1820}
1821
1822static bool initialize_rscale(icalrecur_iterator *impl)
1823{
1824 struct icalrecurrencetype *rule = impl->rule;
1825 struct icaltimetype dtstart = impl->dtstart;
1826 char locale[ULOC_KEYWORD_AND_VALUES_CAPACITY] = {0};
1827 UErrorCode status = U_ZERO_ERROR;
1828 UChar *tzid = (UChar *)UCAL_UNKNOWN_ZONE_ID;
1829 bool is_hebrew = false;
1830 char *src = NULL;
1831
1832 /* DAILY and longer rules generate local times with the time of day of
1833 DTSTART or the BYHOUR, BYMINUTE and BYSECOND values (RFC 5545 section
1834 3.3.10). Calculate them without a time zone: in the zone of DTSTART,
1835 ICU moves a time in a DST gap forward and keeps the moved time for
1836 the following occurrences. */
1837 if (rule->freq < ICAL_DAILY_RECURRENCE) {
1838 /* Convert the UTF8 timezoneid of dstart to ICU UChar. */
1839 src = (char *)icaltimezone_get_location((icaltimezone *)dtstart.zone);
1840 if (!src) {
1841 const char *prefix = icaltimezone_tzid_prefix();
1842 src = (char *)icaltimezone_get_tzid((icaltimezone *)dtstart.zone);
1843 /* coverity[use_after_free] */
1844 if (src && !strncmp(src, prefix, strlen(prefix))) {
1845 /* Skip past our prefix */
1846 src += strlen(prefix);
1847 }
1848 }
1849 }
1850 if (src) {
1851 size_t len = (strlen(src) + 1) * U_SIZEOF_UCHAR;
1852 tzid = icalmemory_tmp_buffer(len);
1853 tzid = u_strFromUTF8Lenient(tzid, (int32_t)len, NULL, src, -1, &status);
1854 if (U_FAILURE(status)) {
1856 return false;
1857 }
1858 }
1859
1860 /* Create locale for Gregorian calendar */
1861 (void)uloc_setKeywordValue("calendar", "gregorian",
1862 locale, sizeof(locale), &status);
1863
1864 /* Create Gregorian calendar and set to DTSTART */
1865 impl->greg = ucal_open(tzid, -1, locale, UCAL_DEFAULT, &status);
1866 if (impl->greg) {
1867 ucal_setDateTime(impl->greg,
1868 (int32_t)dtstart.year,
1869 (int32_t)(dtstart.month - 1), /* UCal is 0-based */
1870 (int32_t)dtstart.day,
1871 (int32_t)dtstart.hour,
1872 (int32_t)dtstart.minute,
1873 (int32_t)dtstart.second, &status);
1874 }
1875 if (!impl->greg || U_FAILURE(status)) {
1877 return false;
1878 }
1879
1880 if (!rule->rscale) {
1881 /* Use Gregorian as RSCALE */
1882 impl->rscale = impl->greg;
1883 } else {
1884 UEnumeration *en;
1885 const char *cal;
1886 char *r;
1887
1888 /* Lowercase the specified calendar */
1889 for (r = rule->rscale; *r; r++) {
1890 *r = tolower((int)*r);
1891 }
1892
1893 /* Check if specified calendar is supported */
1894 en = ucal_getKeywordValuesForLocale("calendar", "", false, &status);
1895 while ((cal = uenum_next(en, NULL, &status))) {
1896 if (!strcmp(cal, rule->rscale)) {
1897 is_hebrew = (strcmp(rule->rscale, "hebrew") == 0);
1898 break;
1899 }
1900 }
1901 uenum_close(en);
1902 if (!cal) {
1904 return false;
1905 }
1906
1907 /* Create locale for RSCALE calendar */
1908 (void)uloc_setKeywordValue("calendar", rule->rscale,
1909 locale, sizeof(locale), &status);
1910
1911 /* Create RSCALE calendar and set to DTSTART */
1912 impl->rscale = ucal_open(tzid, -1, locale, UCAL_DEFAULT, &status);
1913 if (impl->rscale) {
1914 UDate millis = ucal_getMillis(impl->greg, &status);
1915
1916 ucal_setMillis(impl->rscale, millis, &status);
1917 }
1918 if (!impl->rscale || U_FAILURE(status)) {
1920 return false;
1921 }
1922 }
1923
1924 /* Validate BY_* array values whose legal maximums differ based on RSCALE */
1925 if (!validate_byrule(impl, ICAL_BY_MONTH, UCAL_MONTH,
1926 &decode_month, is_hebrew) ||
1927 !validate_byrule(impl, ICAL_BY_DAY, UCAL_WEEK_OF_YEAR, &decode_day, false) ||
1928 !validate_byrule(impl, ICAL_BY_MONTH_DAY, UCAL_DAY_OF_MONTH, NULL, false) ||
1929 !validate_byrule(impl, ICAL_BY_YEAR_DAY, UCAL_DAY_OF_YEAR, NULL, false) ||
1930 !validate_byrule(impl, ICAL_BY_WEEK_NO, UCAL_WEEK_OF_YEAR, NULL, false) ||
1931 !validate_byrule(impl, ICAL_BY_SET_POS, UCAL_DAY_OF_YEAR, NULL, false)) {
1933 return false;
1934 }
1935
1936 /* Set iCalendar defaults */
1937 ucal_setAttribute(impl->rscale, UCAL_MINIMAL_DAYS_IN_FIRST_WEEK, 4);
1938 ucal_setAttribute(impl->rscale, UCAL_FIRST_DAY_OF_WEEK, (int32_t)rule->week_start);
1939
1940 /* Get rstart (DTSTART in RSCALE) */
1941 impl->rstart = occurrence_as_icaltime(impl, 0);
1942
1943 return true;
1944}
1945
1947static void set_start(icalrecur_iterator *impl, icaltimetype date)
1948{
1949 UErrorCode status = U_ZERO_ERROR;
1950
1951 impl->last.is_date = impl->rstart.is_date;
1952 impl->last.zone = impl->rstart.zone;
1953
1954 if (impl->rstart.is_date) {
1955 ucal_setDate(impl->greg,
1956 (int32_t)date.year,
1957 (int32_t)(date.month - 1), /* UCal is 0-based */
1958 (int32_t)date.day, &status);
1959 } else {
1960 int hour, minute, second;
1961
1962 __get_start_time(impl, date, &hour, &minute, &second);
1963
1964 ucal_setDateTime(impl->greg,
1965 (int32_t)date.year,
1966 (int32_t)(date.month - 1), /* UCal is 0-based */
1967 (int32_t)date.day,
1968 (int32_t)hour,
1969 (int32_t)minute,
1970 (int32_t)second,
1971 &status);
1972 }
1973
1974 if (impl->rscale != impl->greg) {
1975 UDate millis = ucal_getMillis(impl->greg, &status);
1976 ucal_setMillis(impl->rscale, millis, &status);
1977 }
1978}
1979
1980static void set_datetime(icalrecur_iterator *impl, icaltimetype date)
1981{
1982 UErrorCode status = U_ZERO_ERROR;
1983
1984 impl->last.is_date = impl->rstart.is_date;
1985 impl->last.zone = impl->rstart.zone;
1986
1987 if (impl->rstart.is_date) {
1988 ucal_setDate(impl->greg,
1989 (int32_t)date.year,
1990 (int32_t)(date.month - 1), /* UCal is 0-based */
1991 (int32_t)date.day, &status);
1992 } else {
1993 ucal_setDateTime(impl->greg,
1994 (int32_t)date.year,
1995 (int32_t)(date.month - 1), /* UCal is 0-based */
1996 (int32_t)date.day,
1997 (int32_t)date.hour,
1998 (int32_t)date.minute,
1999 (int32_t)date.second,
2000 &status);
2001 }
2002
2003 if (impl->rscale != impl->greg) {
2004 UDate millis = ucal_getMillis(impl->greg, &status);
2005 ucal_setMillis(impl->rscale, millis, &status);
2006 }
2007}
2008
2010static int month_diff(icalrecur_iterator *impl, icaltimetype a, icaltimetype b)
2011{
2012 int diff;
2013
2014 if (impl->rscale == impl->greg) {
2015 /* Use simple Gregorian math */
2016 diff = __greg_month_diff(a, b);
2017 } else if (a.year == b.year) {
2018 diff = b.month - a.month;
2019 } else {
2020 /* Count months in each year to account for leap months */
2021 UErrorCode status = U_ZERO_ERROR;
2022 UDate millis;
2023 int year = a.year;
2024
2025 /* Save current date */
2026 millis = ucal_getMillis(impl->rscale, &status);
2027
2028 set_day_of_year(impl, 1);
2029 diff = get_months_in_year(impl, year) - a.month;
2030 while (++year < b.year) {
2031 diff += get_months_in_year(impl, year);
2032 }
2033 diff += b.month;
2034
2035 /* Restore date */
2036 ucal_setMillis(impl->rscale, millis, &status);
2037 }
2038
2039 return diff;
2040}
2041
2043static int day_diff(icalrecur_iterator *impl, icaltimetype a, icaltimetype b)
2044{
2045 UErrorCode status = U_ZERO_ERROR;
2046 UDate millis;
2047 int diff;
2048
2049 /* Save current date */
2050 millis = ucal_getMillis(impl->rscale, &status);
2051
2052 set_day_of_year(impl, 1);
2053
2054 diff = __day_diff(impl, a, b);
2055
2056 /* Restore date */
2057 ucal_setMillis(impl->rscale, millis, &status);
2058
2059 return diff;
2060}
2061
2062static void reset_period_start(icalrecur_iterator *impl)
2063{
2064 struct icaltimetype start = impl->period_start;
2065
2066 (void)get_day_of_year(impl, start.year, start.month, start.day);
2067}
2068
2069#else /* !HAVE_LIBICU */
2070
2071/*
2072 * Callbacks for recurrence rules without RSCALE (Gregorian only)
2073 */
2074
2076{
2077 icalarray *calendars = icalarray_new(sizeof(const char **), 1);
2078 const char *cal = "GREGORIAN";
2079
2080 icalarray_append(calendars, &cal);
2081
2082 return calendars;
2083}
2084
2085static void set_second(icalrecur_iterator *impl, int second)
2086{
2087 impl->last.second = second;
2088}
2089
2090static void set_minute(icalrecur_iterator *impl, int minute)
2091{
2092 impl->last.minute = minute;
2093}
2094
2095static void set_hour(icalrecur_iterator *impl, int hour)
2096{
2097 impl->last.hour = hour;
2098}
2099
2100static int set_month(icalrecur_iterator *impl, int month)
2101{
2102 return (impl->last.month = month);
2103}
2104
2106#define get_months_in_year(impl, year) (12)
2108
2109static int get_days_in_year(icalrecur_iterator *impl, int year)
2110{
2111 _unused(impl);
2112
2114}
2115
2116static void set_day_of_year(icalrecur_iterator *impl, int doy)
2117{
2118 struct icaltimetype next;
2119
2120 if (doy < 1) {
2121 doy += get_days_in_year(impl, impl->last.year);
2122 }
2123
2124 next = icaltime_from_day_of_year(doy, impl->last.year);
2125
2126 impl->last.day = next.day;
2127 impl->last.month = next.month;
2128 impl->last.year = next.year;
2129}
2130
2131static int get_start_of_week(const icalrecur_iterator *impl)
2132{
2133 return icaltime_start_doy_week(impl->last, (int)impl->rule->week_start);
2134}
2135
2136static int get_day_of_week(const icalrecur_iterator *impl)
2137{
2138 return icaltime_day_of_week(impl->last);
2139}
2140
2143static int get_week_number(icalrecur_iterator *impl, struct icaltimetype tt)
2144{
2145 int dow, week;
2146
2147 _unused(impl);
2148
2149 /* Normalize day of week so that week_start day is 1 */
2150 dow = icaltime_day_of_week(tt) - (int)(impl->rule->week_start - 1);
2151 if (dow <= 0) {
2152 dow += 7;
2153 }
2154
2155 week = (icaltime_day_of_year(tt) - dow + 10) / 7;
2156 if (week < 1) {
2157 /* Last week of preceding year */
2158 week = weeks_in_year(tt.year - 1, impl->rule->week_start);
2159 } else if (week > weeks_in_year(tt.year, impl->rule->week_start)) {
2160 /* First week of following year */
2161 week = 1;
2162 }
2163
2164 return week;
2165}
2166
2167static int get_days_in_month(icalrecur_iterator *impl, int month, int year)
2168{
2169 _unused(impl);
2170
2172}
2173
2174static struct icaltimetype get_dtstart_adjusted(icalrecur_iterator *impl,
2175 int year, int month, int day)
2176{
2177 struct icaltimetype t = impl->dtstart;
2178
2179 t.is_date = 1;
2180 t.year = year;
2181
2182 if (!month) {
2183 month = impl->dtstart.month;
2184 }
2185 t.month = month;
2186
2187 if (!day) {
2188 day = impl->dtstart.day;
2189 } else if (day < 0) {
2191 }
2192 t.day = day;
2193
2194 return t;
2195}
2196
2197static int get_day_of_year(icalrecur_iterator *impl,
2198 int year, int month, int day)
2199{
2200 return icaltime_day_of_year(get_dtstart_adjusted(impl, year, month, day));
2201}
2202
2203static int get_day_of_week_adjusted(icalrecur_iterator *impl,
2204 int year, int month, int day)
2205{
2206 return icaltime_day_of_week(get_dtstart_adjusted(impl, year, month, day));
2207}
2208
2209/* cppcheck-suppress constParameterPointer */
2210static struct icaltimetype occurrence_as_icaltime(icalrecur_iterator *impl,
2211 int normalize)
2212{
2213 return (normalize ? icaltime_normalize(impl->last) : impl->last);
2214}
2215
2216static struct icaltimetype __icaltime_from_day_of_year(icalrecur_iterator *impl,
2217 int day, int year, int *weekno)
2218{
2219 struct icaltimetype tt;
2220
2221 if (day < 0) {
2222 day += get_days_in_year(impl, year) + 1;
2223 }
2224
2226
2227 if (weekno) {
2228 *weekno = get_week_number(impl, tt);
2229 }
2230 return tt;
2231}
2232
2233static void increment_year(icalrecur_iterator *impl, int inc)
2234{
2235 impl->last.year += inc;
2236}
2237
2238static void __increment_month(icalrecur_iterator *impl, int inc)
2239{
2240 int years;
2241
2242 impl->last.month += inc;
2243
2244 /* Months are offset by one */
2245 impl->last.month--;
2246
2247 years = impl->last.month / 12;
2248
2249 impl->last.month = impl->last.month % 12;
2250
2251 if (impl->last.month < 0) {
2252 impl->last.month = impl->last.month + 12;
2253 years--;
2254 }
2255
2256 impl->last.month++;
2257
2258 if (years != 0) {
2259 increment_year(impl, years);
2260 }
2261}
2262
2263static void increment_monthday(icalrecur_iterator *impl, int inc)
2264{
2265 icaltime_adjust(&impl->last, inc, 0, 0, 0);
2266}
2267
2268static void increment_hour(icalrecur_iterator *impl, int inc)
2269{
2270 icaltime_adjust(&impl->last, 0, inc, 0, 0);
2271}
2272
2273static void increment_minute(icalrecur_iterator *impl, int inc)
2274{
2275 icaltime_adjust(&impl->last, 0, 0, inc, 0);
2276}
2277
2278static void increment_second(icalrecur_iterator *impl, int inc)
2279{
2280 icaltime_adjust(&impl->last, 0, 0, 0, inc);
2281}
2282
2283static bool initialize_rscale(icalrecur_iterator *impl)
2284{
2285 if (impl->rule->rscale && strcasecmp(impl->rule->rscale, "GREGORIAN")) {
2287 return false;
2288 }
2289
2290 impl->rstart = impl->dtstart;
2291
2292 return true;
2293}
2294
2296static void set_start(icalrecur_iterator *impl, icaltimetype date)
2297{
2298 impl->last.year = date.year;
2299 impl->last.month = date.month;
2300 impl->last.day = date.day;
2301 impl->last.is_date = impl->dtstart.is_date;
2302 impl->last.zone = impl->dtstart.zone;
2303
2304 if (!impl->dtstart.is_date) {
2305 __get_start_time(impl, date, &impl->last.hour,
2306 &impl->last.minute, &impl->last.second);
2307 }
2308}
2309
2310static void set_datetime(icalrecur_iterator *impl, icaltimetype date)
2311{
2312 impl->last = date;
2313}
2314
2316static int month_diff(icalrecur_iterator *impl, icaltimetype a, icaltimetype b)
2317{
2318 _unused(impl);
2319
2320 return __greg_month_diff(a, b);
2321}
2322
2324static int day_diff(icalrecur_iterator *impl, icaltimetype a, icaltimetype b)
2325{
2326 return __day_diff(impl, a, b);
2327}
2328
2329static void reset_period_start(icalrecur_iterator *impl)
2330{
2331 /* We only want to set the date, not the time */
2332 impl->last.year = impl->period_start.year;
2333 impl->last.month = impl->period_start.month;
2334 impl->last.day = impl->period_start.day;
2335}
2336
2337#endif /* HAVE_LIBICU */
2338
2339static int get_second(icalrecur_iterator *impl)
2340{
2341 return occurrence_as_icaltime(impl, 1).second;
2342}
2343
2344static int get_minute(icalrecur_iterator *impl)
2345{
2346 return occurrence_as_icaltime(impl, 1).minute;
2347}
2348
2349static int get_hour(icalrecur_iterator *impl)
2350{
2351 return occurrence_as_icaltime(impl, 1).hour;
2352}
2353
2354static bool __iterator_set_start(icalrecur_iterator *impl, icaltimetype start);
2355static void increment_month(icalrecur_iterator *impl, int inc);
2356static void expand_month_days(icalrecur_iterator *impl, int year, int month);
2357static void expand_year_days(icalrecur_iterator *impl, int year);
2358static int next_yearday(icalrecur_iterator *impl,
2359 void (*next_period)(icalrecur_iterator *, int));
2360static int prev_yearday(icalrecur_iterator *impl,
2361 void (*next_period)(icalrecur_iterator *, int));
2362
2363static void adjust_to_byday(icalrecur_iterator *impl)
2364{
2365 /* If there is ICAL_BY_DAY data, then we need to move the initial
2366 time to the start of the ICAL_BY_DAY data. That is if the
2367 start time is on a Wednesday, and the rule has
2368 BYDAY=MO,WE,FR, move the initial time back to
2369 monday. Otherwise, jumping to the next week ( jumping 7
2370 days ahead ) will skip over some occurrences in the
2371 second week. */
2372
2373 /* This depends on impl->bydata[ICAL_BY_DAY].by.data being correctly sorted by
2374 * day. This should probably be abstracted to make such assumption
2375 * more explicit. */
2376 int week_start = (int)impl->rule->week_start;
2377 int this_dow = get_day_of_week(impl);
2378 int first_dow = (int)icalrecurrencetype_day_day_of_week(impl->bydata[ICAL_BY_DAY].by.data[0]);
2379
2380 /* Positions within the week that begins on WKST, from 0 to 6, so that
2381 the move stays within the week of the start time */
2382 int this_pos = (this_dow - week_start + 7) % 7;
2383 int first_pos = (first_dow - week_start + 7) % 7;
2384
2385 if (first_pos != this_pos) {
2386 increment_monthday(impl, first_pos - this_pos);
2387 }
2388}
2389
2390icalrecur_iterator *icalrecur_iterator_new(struct icalrecurrencetype *rule,
2391 struct icaltimetype dtstart)
2392{
2393 if (rule == NULL) {
2395 return 0;
2396 }
2397
2398 icalrecur_iterator *impl;
2401
2403
2404 if (freq == ICAL_NO_RECURRENCE) {
2406 return 0;
2407 }
2408
2410#define IN_RANGE(val, min, max) ((val) >= (min) && (val) <= (max))
2412 /* Make sure that DTSTART is a sane value */
2413 if (!icaltime_is_valid_time(dtstart) ||
2414 !IN_RANGE(dtstart.year, 0, MAX_TIME_T_YEAR) ||
2415 !IN_RANGE(dtstart.month, 1, 12) ||
2416 !IN_RANGE(dtstart.day, 1,
2417 icaltime_days_in_month(dtstart.month, dtstart.year)) ||
2418 (!dtstart.is_date && (!IN_RANGE(dtstart.hour, 0, 23) ||
2419 !IN_RANGE(dtstart.minute, 0, 59) ||
2420 !IN_RANGE(dtstart.second, 0, 59)))) {
2422 return 0;
2423 }
2424
2425 /* A DATE value has no time of day to step, so a SECONDLY, MINUTELY or
2426 HOURLY rule would never advance past DTSTART. */
2427 if (dtstart.is_date && freq < ICAL_DAILY_RECURRENCE) {
2429 return 0;
2430 }
2431
2432 if (!(impl = (icalrecur_iterator *)icalmemory_new_buffer(sizeof(icalrecur_iterator)))) {
2434 return 0;
2435 }
2436
2437 memset(impl, 0, sizeof(icalrecur_iterator));
2438
2439 impl->dtstart = dtstart;
2440
2441#if defined(HAVE_LIBICU)
2442 if (rule->rscale) {
2443 // The referenced rule should be treated as immutable, but in case of rscale we need
2444 // to modify it (change rscale to lower, shift months in decode_month()), so we
2445 // clone the whole rule and leave the original one untouched.
2446 rule = icalrecurrencetype_clone(rule);
2447 if (!rule) {
2450 return 0;
2451 }
2452 } else
2453#endif
2454 {
2455 // Without rscale we don't need to modify the rule state. We need to populate some by
2456 // values if they aren't set, but we have dedicated storage for that within the
2457 // iterator (i.e. icalrecurrence_iterator_by_data.buffer_value). So we simply ref
2458 // the rule but don't clone it.
2460 }
2461
2462 impl->rule = rule;
2463
2464 impl->iend = icaltime_null_time();
2465
2466 for (byrule = 0; byrule < ICAL_BY_NUM_PARTS; ++byrule) {
2467 impl->bydata[byrule].by = impl->rule->by[byrule];
2468
2469 /* Note which by rules had data in them when the iterator was
2470 created. We can't use the actual by_x arrays, because the
2471 empty ones will be given default values later in this
2472 routine. The orig_data array will be used later in has_by_data */
2473
2474 impl->bydata[byrule].orig_data =
2475 (short)(impl->rule->by[byrule].size > 0);
2476
2477 /* Check if the recurrence rule is legal */
2478 if (expand_map[freq].map[byrule] == ILLEGAL &&
2479 has_by_data(impl, byrule)) {
2480 ical_invalid_rrule_handling rruleHandlingSetting =
2482 if (rruleHandlingSetting == ICAL_RRULE_IGNORE_INVALID) {
2483 impl->bydata[byrule].orig_data = 0;
2484 } else {
2487 return 0;
2488 }
2489 }
2490 }
2491
2492 if (!initialize_rscale(impl)) {
2494 return 0;
2495 }
2496
2497 /* Set up defaults for BY_* arrays */
2498 setup_defaults(impl, ICAL_BY_SECOND, impl->rstart.second);
2499
2500 setup_defaults(impl, ICAL_BY_MINUTE, impl->rstart.minute);
2501
2502 setup_defaults(impl, ICAL_BY_HOUR, impl->rstart.hour);
2503
2504 setup_defaults(impl, ICAL_BY_MONTH_DAY, impl->rstart.day);
2505
2506 setup_defaults(impl, ICAL_BY_MONTH, impl->rstart.month);
2507
2508 if (has_by_data(impl, ICAL_BY_SET_POS)) {
2509 impl->sp_pmax = 0;
2510 while (impl->sp_pmax < impl->bydata[ICAL_BY_SET_POS].by.size &&
2511 impl->bydata[ICAL_BY_SET_POS].by.data[impl->sp_pmax] > 0) {
2512 impl->sp_pmax++;
2513 }
2514 impl->sp_pmax--;
2515 }
2516
2517 if (!__iterator_set_start(impl, dtstart)) {
2519 return 0;
2520 }
2521
2522 return impl;
2523}
2524
2525void icalrecur_iterator_free(icalrecur_iterator *impl)
2526{
2527 icalerror_check_arg_rv((impl != 0), "impl");
2528
2529#if defined(HAVE_LIBICU)
2530 if (impl->greg) {
2531 if (impl->rscale && (impl->rscale != impl->greg)) {
2532 ucal_close(impl->rscale);
2533 }
2534
2535 ucal_close(impl->greg);
2536 }
2537#endif
2538
2539 icalrecurrencetype_unref(impl->rule);
2541}
2542
2544static int __day_diff(icalrecur_iterator *impl, icaltimetype a, icaltimetype b)
2545{
2546 int diff;
2547
2548 if (a.year == b.year) {
2549 diff = get_day_of_year(impl, b.year, b.month, b.day) -
2550 get_day_of_year(impl, a.year, a.month, a.day);
2551 } else {
2552 /* Swap a and b if a is greater than b */
2553 int flipped = 0;
2554 int year;
2555
2556 if (a.year > b.year) {
2557 icaltimetype temp = a;
2558
2559 a = b;
2560 b = temp;
2561 flipped = 1;
2562 }
2563
2564 /* Count days in each year to account for leap days/months */
2565 year = a.year;
2566
2567 diff = get_days_in_year(impl, year) -
2568 get_day_of_year(impl, a.year, a.month, a.day);
2569 while (++year < b.year) {
2570 diff += get_days_in_year(impl, year);
2571 }
2572 diff += get_day_of_year(impl, b.year, b.month, b.day);
2573
2574 if (flipped) {
2575 /* The difference is negative because a was greater than b */
2576 diff = -diff;
2577 }
2578 }
2579
2580 return diff;
2581}
2582
2586static void increment_month(icalrecur_iterator *impl, int inc)
2587{
2588 __increment_month(impl, inc);
2589
2590 if (has_by_data(impl, ICAL_BY_MONTH)) {
2591 struct icaltimetype this = occurrence_as_icaltime(impl, 0);
2592
2593 while (this.year < MAX_TIME_T_YEAR) {
2594 icalrecurrence_iterator_by_data *bydata = &impl->bydata[ICAL_BY_MONTH];
2595 for (bydata->index = 0;
2596 bydata->index < bydata->by.size; bydata->index++) {
2597 if (this.month == bydata->by.data[bydata->index]) {
2598 return;
2599 }
2600 }
2601
2602 __increment_month(impl, inc);
2603 this = occurrence_as_icaltime(impl, 0);
2604 }
2605 }
2606}
2607
2608static int next_unit(icalrecur_iterator *impl,
2609 int by_unit, icalrecurrencetype_frequency frequency,
2610 int (*next_sub_unit)(icalrecur_iterator *),
2611 void (*set_unit)(icalrecur_iterator *, int),
2612 int (*get_unit)(icalrecur_iterator *),
2613 int period_len,
2614 void (*increment_unit)(icalrecur_iterator *, int))
2615{
2616 int has_by_unit = (by_unit > ICAL_BYRULE_NO_CONTRACTION) &&
2617 (impl->bydata[by_unit].by.size > 0);
2618 int this_frequency = (impl->rule->freq == frequency);
2619
2620 int end_of_data = 0;
2621
2622 icalassert(has_by_unit || this_frequency);
2623
2624 /* cppcheck-suppress nullPointer */
2625 if (next_sub_unit && next_sub_unit(impl) == 0) {
2626 return 0;
2627 }
2628
2629 const size_t max_recurrence_time_count = icallimit_get(ICAL_LIMIT_RECURRENCE_TIME_STANDING_STILL);
2630 if (has_by_unit) {
2631 /* Frequency must be hours, minutes or seconds */
2632 icalrecurrence_iterator_by_data *bydata = &impl->bydata[by_unit];
2633 if (this_frequency) {
2634 bydata->index++;
2635 /* Take the frequency into account and treat the byrule data as limiting */
2636 size_t stalledCnt = 0;
2637 while ((impl->last.year < MAX_TIME_T_YEAR) && (stalledCnt++ < max_recurrence_time_count)) {
2638 int last_unit = get_unit(impl);
2639 /* Find a BY* value that works with the interval length */
2640 while (bydata->index < bydata->by.size) {
2641 int cur_by = bydata->by.data[bydata->index];
2642 if ((cur_by >= last_unit) &&
2643 ((cur_by - last_unit) % impl->rule->interval) == 0) {
2644 set_unit(impl, cur_by);
2645 return 1;
2646 }
2647 bydata->index++;
2648 }
2649 /* If none found, increment to next period (i.e., increment super unit,
2650 * but take into account interval length). */
2651 bydata->index = 0;
2652 int multiplier = 1;
2653 if (last_unit + impl->rule->interval < period_len) {
2654 int diff = period_len - last_unit;
2655 multiplier = (diff / impl->rule->interval + (diff % impl->rule->interval > 0));
2656 }
2657 increment_unit(impl, multiplier * impl->rule->interval);
2658 }
2659 /* The iteration ended without finding a BY* value,
2660 don't leave the index past the end of the BY* data */
2661 bydata->index = 0;
2662 } else {
2663 bydata->index++;
2664
2665 if (bydata->by.size <= bydata->index) {
2666 bydata->index = 0;
2667
2668 end_of_data = 1;
2669 }
2670
2671 if (bydata->index < bydata->by.size) {
2672 set_unit(impl, bydata->by.data[bydata->index]);
2673 } else {
2675 }
2676 }
2677 } else {
2678 /* Compute the next value from the last time and the freq interval */
2679 increment_unit(impl, impl->rule->interval);
2680 end_of_data = 1;
2681 }
2682
2683 return end_of_data;
2684}
2685
2686static int next_second(icalrecur_iterator *impl)
2687{
2688 return next_unit(impl, ICAL_BY_SECOND, ICAL_SECONDLY_RECURRENCE, NULL,
2689 &set_second, &get_second, 60, &increment_second);
2690}
2691
2692static int next_minute(icalrecur_iterator *impl)
2693{
2694 return next_unit(impl, ICAL_BY_MINUTE, ICAL_MINUTELY_RECURRENCE, &next_second,
2695 &set_minute, &get_minute, 60, &increment_minute);
2696}
2697
2698static int next_hour(icalrecur_iterator *impl)
2699{
2700 return next_unit(impl, ICAL_BY_HOUR, ICAL_HOURLY_RECURRENCE, &next_minute,
2701 &set_hour, &get_hour, 24, &increment_hour);
2702}
2703
2704static int next_day(icalrecur_iterator *impl)
2705{
2706 return next_unit(impl, ICAL_BYRULE_NO_CONTRACTION, ICAL_DAILY_RECURRENCE, &next_hour,
2707 NULL, NULL, 0, &increment_monthday);
2708}
2709
2710static int prev_unit(icalrecur_iterator *impl,
2711 int by_unit, icalrecurrencetype_frequency frequency,
2712 int (*prev_sub_unit)(icalrecur_iterator *),
2713 void (*set_unit)(icalrecur_iterator *, int),
2714 int (*get_unit)(icalrecur_iterator *),
2715 void (*increment_unit)(icalrecur_iterator *, int))
2716{
2717 int has_by_unit = (by_unit > ICAL_BYRULE_NO_CONTRACTION) &&
2718 (impl->bydata[by_unit].by.size > 0);
2719 int this_frequency = (impl->rule->freq == frequency);
2720
2721 int end_of_data = 0;
2722
2723 icalassert(has_by_unit || this_frequency);
2724
2725 /* cppcheck-suppress nullPointer */
2726 if (prev_sub_unit && prev_sub_unit(impl) == 0) {
2727 return 0;
2728 }
2729
2730 if (has_by_unit) {
2731 icalrecurrence_iterator_by_data *bydata = &impl->bydata[by_unit];
2732 if (this_frequency) {
2733 bydata->index--;
2734
2735 while (impl->last.year > 0) {
2736 int last_unit = get_unit(impl);
2737 while (bydata->index >= 0) {
2738 int cur_by = bydata->by.data[bydata->index];
2739 if ((cur_by <= last_unit) && (impl->rule->interval > 0) &&
2740 ((last_unit - cur_by) % impl->rule->interval) == 0) {
2741 set_unit(impl, cur_by);
2742 return 1;
2743 }
2744 bydata->index--;
2745 }
2746 bydata->index = bydata->by.size - 1;
2747 int multiplier = 1;
2748 if (last_unit - impl->rule->interval > 0) {
2749 multiplier = (last_unit / impl->rule->interval + (last_unit % impl->rule->interval > 0));
2750 }
2751 increment_unit(impl, -multiplier * impl->rule->interval);
2752 }
2753 } else {
2754 bydata->index--;
2755
2756 if (bydata->index < 0) {
2757 bydata->index =
2758 bydata->by.size - 1;
2759
2760 end_of_data = 1;
2761 }
2762
2763 set_unit(impl, bydata->by.data[bydata->index]);
2764 }
2765
2766 } else {
2767 /* Compute the next value from the last time and the freq interval */
2768 increment_unit(impl, -impl->rule->interval);
2769 end_of_data = 1;
2770 }
2771
2772 return end_of_data;
2773}
2774
2775static int prev_second(icalrecur_iterator *impl)
2776{
2777 return prev_unit(impl, ICAL_BY_SECOND, ICAL_SECONDLY_RECURRENCE, NULL,
2778 &set_second, &get_second, &increment_second);
2779}
2780
2781static int prev_minute(icalrecur_iterator *impl)
2782{
2783 return prev_unit(impl, ICAL_BY_MINUTE, ICAL_MINUTELY_RECURRENCE, &prev_second,
2784 &set_minute, &get_minute, &increment_minute);
2785}
2786
2787static int prev_hour(icalrecur_iterator *impl)
2788{
2789 return prev_unit(impl, ICAL_BY_HOUR, ICAL_HOURLY_RECURRENCE, &prev_minute,
2790 &set_hour, &get_hour, &increment_hour);
2791}
2792
2793static int prev_day(icalrecur_iterator *impl)
2794{
2795 return prev_unit(impl, ICAL_BYRULE_NO_CONTRACTION, ICAL_DAILY_RECURRENCE, &prev_hour,
2796 NULL, NULL, &increment_monthday);
2797}
2798
2800static void expand_bymonth_days(icalrecur_iterator *impl, int year, int month)
2801{
2802 int i;
2803 int days_in_month = get_days_in_month(impl, month, year);
2804
2805 for (i = 0; i < impl->bydata[ICAL_BY_MONTH_DAY].by.size; i++) {
2806 short doy = ICAL_BY_YEARDAY_SIZE, mday = impl->bydata[ICAL_BY_MONTH_DAY].by.data[i];
2807 int this_month = month;
2808
2809 if (abs(mday) > days_in_month) {
2810 int days_in_year = get_days_in_year(impl, year);
2811
2812 switch (impl->rule->skip) {
2813 default:
2814 /* Should never get here! */
2815
2816 case ICAL_SKIP_OMIT:
2817 continue;
2818
2819 case ICAL_SKIP_FORWARD:
2820 if (mday > 0) {
2821 this_month++; /* Next month */
2822 }
2823
2824 if (this_month > get_months_in_year(impl, year)) {
2825 doy = days_in_year + 1; /* First day of next year */
2826 } else {
2827 mday = 1; /* First day of month */
2828 }
2829 break;
2830
2831 case ICAL_SKIP_BACKWARD:
2832 if (mday < 0) {
2833 this_month--; /* Prev month */
2834 }
2835
2836 if (this_month == 0) {
2837 doy = 0; /* Last day of prev year */
2838 } else {
2839 mday = -1; /* Last day of month */
2840 }
2841 break;
2842 }
2843 }
2844
2845 if (doy == ICAL_BY_YEARDAY_SIZE) {
2846 doy = get_day_of_year(impl, year, this_month, mday);
2847 }
2848
2849 daysmask_add_day(impl, doy);
2850 }
2851}
2852
2854static void expand_by_day(icalrecur_iterator *impl, int year,
2855 int doy_offset, int last_day,
2856 int first_dow, int last_dow,
2857 bool is_limiting)
2858{
2859 /* Try to calculate each of the occurrences. */
2860 unsigned long bydays[LONGS_PER_BITS(ICAL_YEARDAYS_MASK_SIZE)];
2861 int i;
2862
2863 memcpy(bydays, impl->days, sizeof(bydays));
2864
2865 daysmask_set_range(impl->days, doy_offset + 1, doy_offset + last_day + 1, 0);
2866
2867 for (i = 0; i < impl->bydata[ICAL_BY_DAY].by.size; i++) {
2868 /* This is 1 (Sun) to 7 (Sat). */
2869 int dow = (int)icalrecurrencetype_day_day_of_week(impl->bydata[ICAL_BY_DAY].by.data[i]);
2870 int pos = icalrecurrencetype_day_position(impl->bydata[ICAL_BY_DAY].by.data[i]);
2871 int first_matching_day, last_matching_day;
2872 int day, this_weekno;
2873
2874 /* Calculate the first day in the period
2875 with the given weekday, and the last day. */
2876 first_matching_day = ((dow + 7 - first_dow) % 7) + 1;
2877 last_matching_day = last_day - ((last_dow + 7 - dow) % 7);
2878
2879 if (pos == 0) {
2880 /* First instance of the weekday within the period.
2881 (Remaining instances added by loop below. */
2882 day = first_matching_day;
2883
2884 } else if (pos > 0) {
2885 /* nth instance of the weekday within the period. */
2886 day = first_matching_day + (pos - 1) * 7;
2887
2888 if (day > last_matching_day) {
2889 continue;
2890 }
2891
2892 } else { /* pos < 0 */
2893 /* -nth instance of the weekday within the period. */
2894 day = last_matching_day + (pos + 1) * 7;
2895
2896 if (day < first_matching_day) {
2897 continue;
2898 }
2899 }
2900
2901 if (doy_offset < 0) {
2902 this_weekno = 1;
2903 } else {
2904 (void)__icaltime_from_day_of_year(impl, day + doy_offset, year,
2905 &this_weekno);
2906 }
2907
2908 /* Add instance(s) of the weekday within the period */
2909 do {
2910 int valid = 0;
2911
2912 if (has_by_data(impl, ICAL_BY_WEEK_NO)) {
2913 /* Make sure our day falls in one of the BYWEEKNO */
2914 int nweeks = weeks_in_year(year, impl->rule->week_start);
2915 int j;
2916
2917 for (j = 0; j < impl->bydata[ICAL_BY_WEEK_NO].by.size; j++) {
2918 int weekno = impl->bydata[ICAL_BY_WEEK_NO].by.data[j];
2919
2920 if (weekno < 0) {
2921 weekno += nweeks + 1;
2922 }
2923
2924 if (weekno == this_weekno) {
2925 valid = 1;
2926 break;
2927 }
2928 }
2929 } else {
2930 valid = 1;
2931 }
2932
2933 if (valid) {
2934 const unsigned long daysmask = daysmask_getbit(bydays, day + doy_offset);
2935 int new_val = is_limiting //NOLINT(readability-implicit-bool-conversion)
2936 /* "Filter" the year days bitmask with the bydays bitmask */
2937 ? (int)daysmask
2938 /* Add each BYDAY to the year days bitmask */
2939 : 1;
2940
2941 if (!daysmask_setbit(impl->days, day + doy_offset, new_val) && new_val) {
2942 if (day + doy_offset < impl->days_index) {
2943 impl->days_index = day + doy_offset;
2944 }
2945 }
2946 }
2947
2948 } while (!pos && ((day += 7) <= last_day) && ++this_weekno);
2949 }
2950}
2951
2953static void limit_by_day(icalrecur_iterator *impl, int year)
2954{
2955 unsigned long bydays[LONGS_PER_BITS(ICAL_YEARDAYS_MASK_SIZE)];
2956 int doy;
2957
2958 memcpy(bydays, impl->days, sizeof(bydays));
2959 daysmask_clearall(impl->days);
2960 impl->days_index = ICAL_YEARDAYS_MASK_SIZE;
2961
2962 /* BYMONTHDAY and BYYEARDAY can also select day 0 or the first day of the
2963 following year through SKIP. Filter those dates in their actual period,
2964 rather than expanding weekdays only in the original month or year. */
2965 for (doy = 0; doy < ICAL_YEARDAYS_MASK_SIZE; doy++) {
2966 struct icaltimetype date;
2967 int dow, i;
2968
2969 if (!daysmask_getbit(bydays, doy)) {
2970 continue;
2971 }
2972
2973 date = __icaltime_from_day_of_year(impl, doy, year, NULL);
2974 dow = get_day_of_week_adjusted(impl, date.year, date.month, date.day);
2975
2976 for (i = 0; i < impl->bydata[ICAL_BY_DAY].by.size; i++) {
2977 short byday = impl->bydata[ICAL_BY_DAY].by.data[i];
2978 int pos = icalrecurrencetype_day_position(byday);
2979
2980 if ((int)icalrecurrencetype_day_day_of_week(byday) != dow) {
2981 continue;
2982 }
2983
2984 if (pos) {
2985 int day, last_day;
2986
2987 if (impl->rule->freq == ICAL_MONTHLY_RECURRENCE || has_by_data(impl, ICAL_BY_MONTH)) {
2988 day = date.day;
2989 last_day = get_days_in_month(impl, date.month, date.year);
2990 } else {
2991 day = get_day_of_year(impl, date.year, date.month, date.day);
2992 last_day = get_days_in_year(impl, date.year);
2993 }
2994
2995 if (pos != (pos > 0 ? (day - 1) / 7 + 1 : -((last_day - day) / 7 + 1))) {
2996 continue;
2997 }
2998 }
2999
3000 daysmask_add_day(impl, doy);
3001 break;
3002 }
3003 }
3004
3005 /* Date helpers can move the calendar across a month or year boundary.
3006 Restore the period, including when no date survived the filter. */
3007 reset_period_start(impl);
3008}
3009
3013static void expand_month_days(icalrecur_iterator *impl, int year, int month)
3014{
3015 int doy_offset, days_in_month, first_dow;
3016
3017 daysmask_clearall(impl->days);
3018
3019 /* We may end up skipping fwd/bwd a month during expansion.
3020 Mark our current start date so next_month() can increment from here */
3021 impl->period_start = occurrence_as_icaltime(impl, 0);
3022
3023 doy_offset = get_day_of_year(impl, year, month, 1) - 1;
3024 first_dow = get_day_of_week_adjusted(impl, year, month, 1);
3025 days_in_month = get_days_in_month(impl, month, year);
3026
3027 /* Add each BYMONTHDAY to the year days bitmask */
3028 expand_bymonth_days(impl, year, month);
3029
3030 if (has_by_data(impl, ICAL_BY_DAY)) {
3031 /* Apply each BYDAY to the year days bitmask */
3032 int last_dow;
3033
3034 if (has_by_data(impl, ICAL_BY_MONTH_DAY) && impl->rule->skip != ICAL_SKIP_OMIT) {
3035 limit_by_day(impl, year);
3036 return;
3037 }
3038
3039 impl->days_index = ICAL_YEARDAYS_MASK_SIZE;
3040
3041 last_dow = get_day_of_week_adjusted(impl, year, month, days_in_month);
3042
3043 expand_by_day(impl, year, doy_offset, days_in_month,
3044 first_dow, last_dow,
3045 has_by_data(impl, ICAL_BY_MONTH_DAY));
3046 }
3047}
3048
3049static void __next_month(icalrecur_iterator *impl, int inc)
3050{
3051 struct icaltimetype this;
3052
3053 /* Increment to and expand the next month */
3054 increment_month(impl, inc);
3055 this = occurrence_as_icaltime(impl, 0);
3056 expand_month_days(impl, this.year, this.month);
3057}
3058
3059static int next_month(icalrecur_iterator *impl)
3060{
3061 return next_yearday(impl, &__next_month);
3062}
3063
3064static int prev_month(icalrecur_iterator *impl)
3065{
3066 return prev_yearday(impl, &__next_month);
3067}
3068
3069static int next_weekday_by_week(icalrecur_iterator *impl)
3070{
3071 int end_of_data = 0;
3072
3073 if (next_hour(impl) == 0) {
3074 return 0;
3075 }
3076
3077 if (!has_by_data(impl, ICAL_BY_DAY)) {
3078 return 1;
3079 }
3080
3081 /* If we get here, we need to step to the next day */
3082
3083 for (;;) {
3084 impl->bydata[ICAL_BY_DAY].index++; /* Look at next elem in BYDAY array */
3085
3086 /* Are we at the end of the BYDAY array? */
3087 if (impl->bydata[ICAL_BY_DAY].index >= impl->bydata[ICAL_BY_DAY].by.size) {
3088 impl->bydata[ICAL_BY_DAY].index = 0; /* Reset to 0 */
3089 end_of_data = 1; /* Signal that we're at the end */
3090 }
3091
3092 /* Add the day of week offset to the start of this week, and use
3093 that to get the next day */
3094 /* ignore position of dow ("4FR"), only use dow ("FR") */
3096 impl->bydata[ICAL_BY_DAY].by.data[impl->bydata[ICAL_BY_DAY].index]);
3097 dow -= (int)impl->rule->week_start; /* Set Sunday to be 0 */
3098 if (dow < 0) {
3099 dow += 7;
3100 }
3101
3102 int start_of_week = get_start_of_week(impl);
3103
3104 if (dow + start_of_week < 1) {
3105 /* The selected date is in the previous year. */
3106 if (!end_of_data) {
3107 continue;
3108 }
3109
3110 increment_year(impl, -1);
3111 }
3112
3113 set_day_of_year(impl, start_of_week + dow);
3114
3115 return end_of_data;
3116 }
3117}
3118
3119static bool next_week(icalrecur_iterator *impl)
3120{
3121 /* Increment to the next week day,
3122 if there is data at a level less than a week */
3123 if (next_weekday_by_week(impl) == 0) {
3124 return false; /* Have not reached end of week yet */
3125 }
3126
3127 /* If we get here, we have incremented through the entire week, and
3128 can increment to the next week */
3129
3130 /* Jump to the next week */
3131 increment_monthday(impl, 7 * impl->rule->interval);
3132
3133 return true;
3134}
3135
3136static int prev_weekday_by_week(icalrecur_iterator *impl)
3137{
3138 int end_of_data = 0;
3139 int start_of_week, dow;
3140
3141 if (prev_hour(impl) == 0) {
3142 return 0;
3143 }
3144
3145 if (!has_by_data(impl, ICAL_BY_DAY)) {
3146 return 1;
3147 }
3148
3149 /* If we get here, we need to step to the previous day */
3150
3151 impl->bydata[ICAL_BY_DAY].index--; /* Look at previous elem in BYDAY array */
3152
3153 /* Are we at the end of the BYDAY array? */
3154 if (impl->bydata[ICAL_BY_DAY].index < 0) {
3155 impl->bydata[ICAL_BY_DAY].index = impl->bydata[ICAL_BY_DAY].by.size - 1;
3156 end_of_data = 1; /* Signal that we're at the end */
3157 }
3158
3159 /* Add the day of week offset to the start of this week, and use
3160 that to get the next day */
3161 /* ignore position of dow ("4FR"), only use dow ("FR") */
3162 dow = (int)icalrecurrencetype_day_day_of_week(impl->bydata[ICAL_BY_DAY].by.data[impl->bydata[ICAL_BY_DAY].index]);
3163 dow -= (int)impl->rule->week_start; /* Set Sunday to be 0 */
3164 if (dow < 0) {
3165 dow += 7;
3166 }
3167
3168 start_of_week = get_start_of_week(impl);
3169
3170 if (dow + start_of_week < 1) {
3171 /* The selected date is in the previous year. */
3172 increment_year(impl, -1);
3173 }
3174
3175 set_day_of_year(impl, start_of_week + dow);
3176
3177 return end_of_data;
3178}
3179
3180static int prev_week(icalrecur_iterator *impl)
3181{
3182 /* Decrement to the previous week day,
3183 if there is data at a level less than a week */
3184 if (prev_weekday_by_week(impl) == 0) {
3185 return 0; /* Have not reached start of week yet */
3186 }
3187
3188 /* If we get here, we have decremented through the entire week, and
3189 can decrement to the previous week */
3190
3191 /* Jump to the previous week */
3192 increment_monthday(impl, 7 * -impl->rule->interval);
3193
3194 return 1;
3195}
3196
3197/* For INTERVAL=YEARLY, set up the year days bitmask in the iterator to
3198 list all of the days of the current year that are specified in this
3199 rule. */
3200static void expand_year_days(icalrecur_iterator *impl, int year)
3201{
3202 int i;
3203 short days_in_year = (short)get_days_in_year(impl, year);
3204 short doy;
3205
3206 daysmask_clearall(impl->days);
3207
3208 /* We may end up skipping fwd/bwd a year during expansion.
3209 Mark our current start date so next_year() can increment from here */
3210 impl->period_start = occurrence_as_icaltime(impl, 0);
3211
3212 if (has_by_data(impl, ICAL_BY_YEAR_DAY)) {
3213 /* We only support BYYEARDAY + BYDAY */
3214 if (has_by_data(impl, ICAL_BY_WEEK_NO) ||
3215 has_by_data(impl, ICAL_BY_MONTH) || has_by_data(impl, ICAL_BY_MONTH_DAY)) {
3217 return;
3218 }
3219
3220 /* Add each BYYEARDAY to the year days bitmask */
3221 for (i = 0; i < impl->bydata[ICAL_BY_YEAR_DAY].by.size; i++) {
3222 doy = impl->bydata[ICAL_BY_YEAR_DAY].by.data[i];
3223
3224 if (abs(doy) > days_in_year) {
3225 switch (impl->rule->skip) {
3226 default:
3227 /* Should never get here! */
3228
3229 case ICAL_SKIP_OMIT:
3230 /* Invalid day */
3231 continue;
3232
3233 case ICAL_SKIP_FORWARD:
3234 if (doy < 0) {
3235 doy = 1; /* First day of this year */
3236 } else {
3237 doy = days_in_year + 1; /* First day of next year */
3238 }
3239 break;
3240
3241 case ICAL_SKIP_BACKWARD:
3242 if (doy < 0) {
3243 doy = 0; /* Last day of prev year */
3244 } else {
3245 doy = days_in_year; /* Last day of this year */
3246 }
3247 break;
3248 }
3249 } else if (doy < 0) {
3250 doy += days_in_year + 1;
3251 }
3252
3253 daysmask_add_day(impl, doy);
3254 }
3255 } else if (has_by_data(impl, ICAL_BY_WEEK_NO)) {
3256 int weekno;
3257
3258 /* We only support BYWEEKNO + BYDAY */
3259 if (has_by_data(impl, ICAL_BY_YEAR_DAY) ||
3260 has_by_data(impl, ICAL_BY_MONTH_DAY) ||
3261 (has_by_data(impl, ICAL_BY_MONTH) && !has_by_data(impl, ICAL_BY_DAY))) {
3263 return;
3264 }
3265
3266 /* BYWEEKNO + BYDAY handled below */
3267 if (!has_by_data(impl, ICAL_BY_DAY)) {
3268 int nweeks = weeks_in_year(year, impl->rule->week_start);
3269
3270 int start_doy = 1;
3271 /* See which week contains Jan 1 */
3272 (void)__icaltime_from_day_of_year(impl, 1, year, &weekno);
3273 if (weekno > 1) {
3274 /* Jan 1 is in last week of previous year - jump ahead */
3275 start_doy += 7;
3276 }
3277 /* Get the first day of the first week,
3278 * accounting for the week start */
3279 set_day_of_year(impl, 1);
3280 start_doy += get_start_of_week(impl) - 1;
3281 /* Adjust to the next instance of DTSTART's week day */
3282 start_doy += (get_day_of_week_adjusted(impl, impl->dtstart.year,
3283 impl->dtstart.month, impl->dtstart.day) -
3284 (int)impl->rule->week_start + 7) %
3285 7;
3286 /* Reset impl to this year */
3287 (void)get_days_in_year(impl, year);
3288
3289 /* Add day of week in each BYWEEKNO to the year days bitmask */
3290 for (i = 0; i < impl->bydata[ICAL_BY_WEEK_NO].by.size; i++) {
3291 weekno = impl->bydata[ICAL_BY_WEEK_NO].by.data[i];
3292
3293 if (weekno < 0) {
3294 weekno += nweeks + 1;
3295 } else if (weekno > nweeks) {
3296 continue;
3297 }
3298
3299 doy = start_doy + 7 * (weekno - 1);
3300
3301 daysmask_add_day(impl, doy);
3302 }
3303 }
3304 } else {
3305 /* Add each BYMONTHDAY in each BYMONTH to the year days bitmask */
3306 for (i = 0; i < impl->bydata[ICAL_BY_MONTH].by.size; i++) {
3307 int month = set_month(impl, impl->bydata[ICAL_BY_MONTH].by.data[i]);
3308
3309 if (month > 0 && month < ICAL_BY_MONTH_SIZE) {
3310 expand_bymonth_days(impl, year, month);
3311 }
3312 }
3313 }
3314
3315 if (has_by_data(impl, ICAL_BY_DAY)) {
3316 /* Apply each BYDAY to the year days bitmask */
3317 bool limiting =
3318 has_by_data(impl, ICAL_BY_YEAR_DAY) || has_by_data(impl, ICAL_BY_MONTH_DAY); //NOLINT(readability-implicit-bool-conversion)
3319 int first_dow, last_dow;
3320
3321 if (limiting && impl->rule->skip != ICAL_SKIP_OMIT) {
3322 limit_by_day(impl, year);
3323 return;
3324 }
3325
3326 impl->days_index = ICAL_YEARDAYS_MASK_SIZE;
3327
3328 if (has_by_data(impl, ICAL_BY_MONTH)) {
3329 /* Numeric BYDAY are within each month */
3330
3331 for (i = 0; i < impl->bydata[ICAL_BY_MONTH].by.size; i++) {
3332 short month = impl->bydata[ICAL_BY_MONTH].by.data[i];
3333 if (month > 0 && month < ICAL_BY_MONTH_SIZE) {
3334 int doy_offset, days_in_month;
3335
3336 /* Get offset within year & day of week of first day of month */
3337 doy_offset =
3338 get_day_of_year(impl, year, month, 1) - 1;
3339 first_dow = get_day_of_week_adjusted(impl, year, month, 1);
3340
3341 /* Get day of week of last day of month */
3342 days_in_month = get_days_in_month(impl, month, year);
3343 last_dow = get_day_of_week_adjusted(impl, year,
3344 month, days_in_month);
3345
3346 expand_by_day(impl, year, doy_offset, days_in_month,
3347 first_dow, last_dow, limiting);
3348 }
3349 }
3350 } else {
3351 /* Numeric BYDAY are within the year */
3352 short doy_offset = 0, last_day;
3353
3354 if (has_by_data(impl, ICAL_BY_WEEK_NO)) {
3355 int weekno;
3356
3357 /* See which week contains Jan 1 */
3358 (void)__icaltime_from_day_of_year(impl, 1, year, &weekno);
3359 if (weekno > 1) {
3360 /* Jan 1 is in last week of previous year - jump ahead */
3361 doy_offset += 7;
3362 }
3363
3364 /* Set start and end of ISO week-numbering year */
3365 set_day_of_year(impl, 1);
3366 doy_offset += get_start_of_week(impl) - 1;
3367 last_day = 7 * weeks_in_year(year, impl->rule->week_start);
3368
3369 first_dow = (int)impl->rule->week_start;
3370 last_dow = (first_dow + 6) % 7;
3371 } else {
3372 /* Get day of week of first day of year */
3373 first_dow = get_day_of_week_adjusted(impl, year, 1, 1);
3374
3375 /* Get day of week of last day of year */
3376 set_day_of_year(impl, days_in_year);
3377 last_dow = get_day_of_week(impl);
3378
3379 last_day = days_in_year;
3380 }
3381
3382 expand_by_day(impl, year, doy_offset, last_day, first_dow, last_dow, limiting);
3383 }
3384 }
3385}
3386
3387static void __next_year(icalrecur_iterator *impl, int inc)
3388{
3389 struct icaltimetype this;
3390
3391 /* Increment to and expand the next year */
3392 increment_year(impl, inc);
3393 this = occurrence_as_icaltime(impl, 0);
3394 expand_year_days(impl, this.year);
3395}
3396
3397static int next_year(icalrecur_iterator *impl)
3398{
3399 return next_yearday(impl, &__next_year);
3400}
3401
3402static int prev_year(icalrecur_iterator *impl)
3403{
3404 return prev_yearday(impl, &__next_year);
3405}
3406
3407static short daymask_find_next_bit(const unsigned long *days, short start_index)
3408{
3409 short days_index = start_index;
3410 unsigned long v;
3411 short startBitIndex;
3412 unsigned short wordIdx;
3413
3414 if (days_index >= ICAL_YEARDAYS_MASK_SIZE) {
3415 return ICAL_YEARDAYS_MASK_SIZE;
3416 }
3417 if (days_index < -ICAL_YEARDAYS_MASK_OFFSET) {
3418 days_index = -ICAL_YEARDAYS_MASK_OFFSET;
3419 }
3420
3421 // Prepare the first word, where searching might not start at the beginning
3422 startBitIndex = days_index + ICAL_YEARDAYS_MASK_OFFSET;
3423 wordIdx = (unsigned short)(startBitIndex / BITS_PER_LONG);
3424 v = days[wordIdx];
3425 if (startBitIndex >= 0) {
3426 v >>= startBitIndex % BITS_PER_LONG;
3427 } else {
3428 v <<= -startBitIndex % BITS_PER_LONG;
3429 }
3430
3431 if (!v) {
3432 // so the first word didn't contain any bits of interest.
3433 days_index += BITS_PER_LONG - startBitIndex % BITS_PER_LONG;
3434
3435 // Are there more empty words following? Skip them.
3436 unsigned short maxWordIdx = (unsigned short)(LONGS_PER_BITS(ICAL_YEARDAYS_MASK_SIZE)) - 1;
3437 while (days_index < ICAL_YEARDAYS_MASK_SIZE && wordIdx < maxWordIdx) {
3438 wordIdx++;
3439 v = days[wordIdx];
3440
3441 if (v) {
3442 break;
3443 }
3444
3445 days_index += BITS_PER_LONG;
3446 }
3447 }
3448
3449 if (v) {
3450 // We found a word containing the next bit but don't know the exact
3451 // position yet. Do a b-search to find it.
3452
3453 unsigned long mask;
3454 int maskSize = (int)(BITS_PER_LONG / 2);
3455 mask = (((unsigned long)1) << maskSize) - 1;
3456
3457 while (maskSize) {
3458 if ((v & mask) == 0) {
3459 v >>= maskSize;
3460 days_index += maskSize;
3461 }
3462 maskSize /= 2;
3463 mask >>= maskSize;
3464 }
3465 }
3466
3467 return days_index;
3468}
3469
3470static short daymask_find_prev_bit(const unsigned long *days, short start_index)
3471{
3472 short days_index = start_index;
3473 unsigned long v;
3474 short startBitIndex;
3475 int wordIdx;
3476
3477 if (days_index <= -ICAL_YEARDAYS_MASK_OFFSET) {
3478 return -ICAL_YEARDAYS_MASK_OFFSET;
3479 }
3480 if (days_index >= ICAL_YEARDAYS_MASK_SIZE) {
3481 days_index = ICAL_YEARDAYS_MASK_SIZE - 1;
3482 }
3483
3484 // Prepare the first word, where searching might not start at the beginning
3485 startBitIndex = days_index + ICAL_YEARDAYS_MASK_OFFSET;
3486 wordIdx = (int)(startBitIndex / BITS_PER_LONG);
3487 v = days[wordIdx];
3488 v = makeMask(v, BITS_PER_LONG - (startBitIndex % BITS_PER_LONG) - 1);
3489
3490 if (!v) {
3491 // so the first word didn't contain any bits of interest.
3492 days_index -= (startBitIndex % BITS_PER_LONG) + 1;
3493
3494 // Are there more empty words leading? Skip them.
3495 while (days_index > -ICAL_YEARDAYS_MASK_OFFSET) {
3496 wordIdx--;
3497 v = days[wordIdx];
3498
3499 if (v) {
3500 break;
3501 }
3502
3503 days_index -= BITS_PER_LONG;
3504 }
3505 }
3506
3507 if (v) {
3508 // We found a word containing the next bit but don't know the exact
3509 // position yet. Do a b-search to find it.
3510
3511 unsigned long mask;
3512 int maskSize = (int)(BITS_PER_LONG / 2);
3513 mask = ((((unsigned long)1) << maskSize) - 1) << maskSize;
3514
3515 while (maskSize) {
3516 if ((v & mask) == 0) {
3517 v <<= maskSize;
3518 days_index -= maskSize;
3519 }
3520 maskSize /= 2;
3521 mask = makeMask(mask, maskSize);
3522 }
3523 }
3524
3525 return days_index;
3526}
3527
3528static int next_yearday(icalrecur_iterator *impl,
3529 void (*next_period)(icalrecur_iterator *, int))
3530{
3531 if (next_hour(impl) == 0) {
3532 return 0;
3533 }
3534
3535 /* We may have skipped fwd/bwd a month/year with previous occurrence.
3536 Reset the period start date so we can increment properly */
3537 reset_period_start(impl);
3538
3539 /* Find next year day that is set */
3540 impl->days_index = daymask_find_next_bit(impl->days, impl->days_index + 1);
3541
3542 int ret = 0;
3543
3544 if (impl->days_index >= ICAL_YEARDAYS_MASK_SIZE) {
3545 ret = 1;
3546 if (next_period) {
3547 for (;;) {
3548 /* Increment to and expand the next period */
3549 next_period(impl, impl->rule->interval);
3550
3551 if (impl->days_index < ICAL_YEARDAYS_MASK_SIZE) {
3552 break; /* break when a matching day is found */
3553 }
3554 }
3555 } else {
3556 /* When next_period is NULL,
3557 we only indicate that we have
3558 reached the end of the period */
3559 return 1;
3560 }
3561 }
3562
3563 if (impl->days_index < 1) {
3564 /* Day is in previous year */
3565 increment_year(impl, -1);
3566 }
3567
3568 set_day_of_year(impl, impl->days_index);
3569
3570 return ret;
3571}
3572
3573static int prev_yearday(icalrecur_iterator *impl,
3574 void (*next_period)(icalrecur_iterator *, int))
3575{
3576 if (prev_hour(impl) == 0) {
3577 return 0;
3578 }
3579
3580 /* We may have skipped fwd/bwd a month/year with previous occurrence.
3581 Reset the period start date so we can decrement properly */
3582 reset_period_start(impl);
3583
3584 /* Find previous year day that is set */
3585 impl->days_index = daymask_find_prev_bit(impl->days, impl->days_index - 1);
3586
3587 int ret = 0;
3588
3589 while (impl->days_index <= -ICAL_YEARDAYS_MASK_OFFSET) {
3590 if (next_period) {
3591 ret = 1;
3592 /* Decrement to and expand the previous period */
3593 next_period(impl, -impl->rule->interval);
3594
3595 impl->days_index = ICAL_YEARDAYS_MASK_SIZE;
3596 impl->days_index = daymask_find_prev_bit(impl->days, impl->days_index - 1);
3597 } else {
3598 /* When next_period is NULL,
3599 we only indicate that we have
3600 reached the end of the period */
3601 return 1;
3602 }
3603 }
3604
3605 if (impl->days_index < 1) {
3606 /* Day is in previous year */
3607 increment_year(impl, -1);
3608 }
3609
3610 set_day_of_year(impl, impl->days_index);
3611
3612 return ret;
3613}
3614
3615static int days_in_current_month(icalrecur_iterator *impl)
3616{
3617 return get_days_in_month(impl, impl->last.month, impl->last.year);
3618}
3619
3620static int days_in_current_year(icalrecur_iterator *impl)
3621{
3622 return get_days_in_year(impl, impl->last.year);
3623}
3624
3625static inline int has_contract_restriction(icalrecur_iterator *impl,
3627{
3628 return impl->bydata[byrule].by.size > 0 &&
3629 expand_map[impl->rule->freq].map[byrule] == CONTRACT;
3630}
3631
3632static bool check_contract_restriction(icalrecur_iterator *impl,
3633 icalrecurrencetype_byrule byrule, int v,
3634 int (*get_total)(icalrecur_iterator *))
3635{
3636 if (has_contract_restriction(impl, byrule)) {
3637 int total = 0;
3638 bool pass = false;
3639 for (int itr = 0; itr < impl->bydata[byrule].by.size; itr++) {
3640 short byval = impl->bydata[byrule].by.data[itr];
3641 if ((byval < 0) && (total == 0)) {
3642 if (get_total) {
3643 // load total value lazily only when needed
3644 total = get_total(impl);
3645 } else {
3646 // limiting by negative values is only allowed for
3647 // BYMONTHDAY, BYYEARDAY (BYDAY is handled separately)
3649 continue;
3650 }
3651 }
3652
3653 if (v == ((byval >= 0) ? byval : (total + 1 + byval))) {
3654 pass = true;
3655 break;
3656 }
3657 }
3658
3659 return pass;
3660 }
3661
3662 /* This is not a contracting byrule, or it has no data, so the test passes */
3663 return true;
3664}
3665
3666static bool check_contracting_rules(icalrecur_iterator *impl)
3667{
3668 struct icaltimetype last = occurrence_as_icaltime(impl, 0);
3669 int month = last.month;
3670
3671 /* For monthly SKIP, BYMONTH limits the originating period before an
3672 invalid day can move into a neighboring month (RFC 7529 section 4.1). */
3673 if (impl->rule->freq == ICAL_MONTHLY_RECURRENCE && impl->rule->skip != ICAL_SKIP_OMIT &&
3674 (!has_by_data(impl, ICAL_BY_DAY) || has_by_data(impl, ICAL_BY_MONTH_DAY)) &&
3675 (last.year != impl->period_start.year || last.month != impl->period_start.month)) {
3676 month = impl->period_start.month;
3677 }
3678
3680// Check `has_contract_restriction` before calling `check_contract_restriction` to avoid
3681// evaluating potentially expensive `v` if not needed.
3682#define CHECK_CONTRACT_RESTRICTION(by, v, get_total) \
3683 (!has_contract_restriction(impl, (by)) || check_contract_restriction(impl, (by), (v), (get_total)))
3684
3685 if (
3686 CHECK_CONTRACT_RESTRICTION(ICAL_BY_SECOND, last.second, NULL) &&
3687 CHECK_CONTRACT_RESTRICTION(ICAL_BY_MINUTE, last.minute, NULL) &&
3688 CHECK_CONTRACT_RESTRICTION(ICAL_BY_HOUR, last.hour, NULL) &&
3689 CHECK_CONTRACT_RESTRICTION(ICAL_BY_MONTH_DAY, last.day, days_in_current_month) &&
3690 CHECK_CONTRACT_RESTRICTION(ICAL_BY_MONTH, month, NULL) &&
3691 CHECK_CONTRACT_RESTRICTION(ICAL_BY_WEEK_NO, get_week_number(impl, last), NULL) &&
3692 CHECK_CONTRACT_RESTRICTION(
3693 ICAL_BY_DAY, get_day_of_week_adjusted(impl, last.year, last.month, last.day), NULL) &&
3694 CHECK_CONTRACT_RESTRICTION(
3695 ICAL_BY_YEAR_DAY, get_day_of_year(impl, last.year, last.month, last.day), days_in_current_year)) {
3696 return true;
3697 }
3698
3699#undef CHECK_CONTRACT_RESTRICTION
3701
3702 return false;
3703}
3704
3705/* Initialize data relating to BYSETPOS, in particular:
3706 * set_pos, sp_idxp, sp_idxn, and recurrence_set_size.
3707 * This must be called at the start of each new period
3708 *
3709 * next == 1 indicates we are advancing the iterator,
3710 * and so are at the start of a new period, while
3711 * next == 0 indicates we are at the end of one
3712 */
3713static void setup_setpos(icalrecur_iterator *impl, int next)
3714{
3715 /* Save data that may be modified */
3716 int days_index = impl->days_index;
3717 int bydata_indices[ICAL_BY_NUM_PARTS];
3718 for (int byrule = 0; byrule < ICAL_BY_NUM_PARTS; byrule++) {
3719 bydata_indices[byrule] = impl->bydata[byrule].index;
3720 }
3721 struct icaltimetype last = impl->last;
3722
3723 impl->recurrence_set_size = 1;
3724 int period_change = 1;
3725 do {
3726 switch (impl->rule->freq) {
3728 break;
3730 /* call next_second instead of next_minute
3731 * to avoid going to the next minute */
3732 period_change = (next ? next_second : prev_second)(impl);
3733 break;
3735 period_change = (next ? next_minute : prev_minute)(impl);
3736 break;
3738 period_change = (next ? next_hour : prev_hour)(impl);
3739 break;
3741 period_change = (next ? next_weekday_by_week : prev_weekday_by_week)(impl);
3742 break;
3744 /* call next_yearday instead of next_month
3745 * to avoid expanding month days */
3746 period_change = (next ? next_yearday : prev_yearday)(impl, NULL);
3747 break;
3749 period_change = (next ? next_yearday : prev_yearday)(impl, NULL);
3750 break;
3751 default:
3753 return;
3754 }
3755 if (period_change == 0 && check_contracting_rules(impl)) {
3756 impl->recurrence_set_size++;
3757 }
3758 } while (period_change == 0);
3759
3760 if (next) {
3761 impl->set_pos = 1;
3762 impl->sp_idxp = 0;
3763 impl->sp_idxn = impl->bydata[ICAL_BY_SET_POS].by.size - 1;
3764 } else {
3765 impl->set_pos = impl->recurrence_set_size;
3766 impl->sp_idxp = impl->sp_pmax;
3767 impl->sp_idxn = impl->sp_pmax + 1;
3768 }
3769
3770 /* Restore what was modified
3771 * Because we do not expand month/year days,
3772 * the days bitfield is not modified */
3773 set_datetime(impl, last);
3774 impl->last = last;
3775 impl->days_index = days_index;
3776 for (int byrule = 0; byrule < ICAL_BY_NUM_PARTS; byrule++) {
3777 impl->bydata[byrule].index = bydata_indices[byrule];
3778 }
3779}
3780
3781/* If s1 occurs before s2 in the recurrence set, return -1
3782 * If s1 occurs after, return 1
3783 * If they are equal, return 0
3784 */
3785static inline int setpos_cmp(int s1, int s2, int next)
3786{
3787 if (s1 < s2) {
3788 return (next ? -1 : 1);
3789 } else if (s2 < s1) {
3790 return (next ? 1 : -1);
3791 }
3792 return 0;
3793}
3794
3795/* Check whether impl->set_pos is a valid recurrence set position
3796 *
3797 * next == 1 indicates that we should increase and decrease
3798 * sp_idxp and sp_idxn, respectively, while
3799 * next == 0 indicates that we should decrease and increase them
3800 */
3801static bool check_setpos(icalrecur_iterator *impl, int next)
3802{
3803 if (!has_by_data(impl, ICAL_BY_SET_POS)) {
3804 return true;
3805 }
3806 icalrecurrence_by_data *by = &impl->bydata[ICAL_BY_SET_POS].by;
3807 int32_t set_pos;
3808
3809 /* If we have positive BYSETPOS data */
3810 if (impl->sp_pmax >= 0) {
3811 set_pos = by->data[impl->sp_idxp];
3812 /* Increment positive index while set_pos is before impl->set_pos */
3813 while (setpos_cmp(set_pos, impl->set_pos, next) < 0) {
3814 if (next && impl->sp_idxp < impl->sp_pmax) {
3815 impl->sp_idxp++;
3816 } else if (!next && impl->sp_idxp > 0) {
3817 impl->sp_idxp--;
3818 } else {
3819 break;
3820 }
3821 set_pos = by->data[impl->sp_idxp];
3822 }
3823 if (impl->set_pos == set_pos) {
3824 return true;
3825 }
3826 }
3827
3828 if (impl->sp_pmax < by->size - 1) {
3829 set_pos = by->data[impl->sp_idxn] + impl->recurrence_set_size + 1;
3830 while (setpos_cmp(set_pos, impl->set_pos, next) < 0) {
3831 if (next && impl->sp_idxn > impl->sp_pmax + 1) {
3832 impl->sp_idxn--;
3833 } else if (!next && impl->sp_idxn < by->size - 1) {
3834 impl->sp_idxn++;
3835 } else {
3836 break;
3837 }
3838 set_pos = by->data[impl->sp_idxn] + impl->recurrence_set_size + 1;
3839 }
3840 if (impl->set_pos == set_pos) {
3841 return true;
3842 }
3843 }
3844 return false;
3845}
3846
3847struct icaltimetype icalrecur_iterator_next(icalrecur_iterator *impl)
3848{
3849 /* Quit if we reached COUNT or if last time is after the UNTIL time */
3850 if (!impl ||
3851 (impl->rule->count != 0 && impl->occurrence_no >= impl->rule->count) ||
3852 (!icaltime_is_null_time(impl->rule->until) &&
3853 icaltime_compare(impl->last, impl->rule->until) > 0)) {
3854 return icaltime_null_time();
3855 }
3856
3857 /* If initial time is valid, return it */
3858 if ((impl->occurrence_no == 0) &&
3859 (icaltime_compare(impl->last, impl->istart) >= 0) &&
3860 check_setpos(impl, 1) &&
3861 check_contracting_rules(impl)) {
3862 impl->occurrence_no++;
3863 return impl->last;
3864 }
3865
3866 int period_change = 1;
3867 /* store previous instance, including iterator structures
3868 * (e.g., bydata) */
3869 icalrecur_iterator impl_last = *impl;
3870
3871 /* Iterate until we get the next valid time */
3872 size_t stalledCnt = 0;
3873 const size_t max_recurrence_time_count = icallimit_get(ICAL_LIMIT_RECURRENCE_TIME_STANDING_STILL);
3874 int lastTimeCompare = 0;
3875 bool hasSetPos = has_by_data(impl, ICAL_BY_SET_POS);
3876 int checkContractingRules = (int)check_contracting_rules(impl);
3877 size_t cntRecurrences = 0;
3878 const size_t max_recurrences = icallimit_get(ICAL_LIMIT_RECURRENCE_SEARCH);
3879 do {
3880 switch (impl->rule->freq) {
3882 /* period_change is always true for secondly recurrence */
3883 next_second(impl);
3884 break;
3885
3887 period_change = next_minute(impl);
3888 break;
3889
3891 period_change = next_hour(impl);
3892 break;
3893
3895 period_change = next_day(impl);
3896 break;
3897
3899 period_change = (int)next_week(impl);
3900 break;
3901
3903 period_change = next_month(impl);
3904 break;
3905
3907 period_change = next_year(impl);
3908 break;
3909
3910 default:
3912 return icaltime_null_time();
3913 }
3914
3915 impl->last = occurrence_as_icaltime(impl, 1);
3916
3917 /* Ignore times that are after the MAX year,
3918 or the UNTIL time, or the end time */
3919 if (impl->last.year > MAX_TIME_T_YEAR ||
3920 (!icaltime_is_null_time(impl->rule->until) &&
3921 icaltime_compare(impl->last, impl->rule->until) > 0) ||
3922 (!icaltime_is_null_time(impl->iend) &&
3923 icaltime_compare(impl->last, impl->iend) >= 0)) {
3924 /* reset to valid instance */
3925 *impl = impl_last;
3926 set_datetime(impl, impl_last.last);
3927 return icaltime_null_time();
3928 }
3929
3930 if (hasSetPos) {
3931 int new_ccr = (int)check_contracting_rules(impl);
3932 if (new_ccr == 1) {
3933 if (checkContractingRules == 0 || period_change) {
3934 setup_setpos(impl, 1);
3935 } else {
3936 impl->set_pos++;
3937 }
3938 }
3939 checkContractingRules = new_ccr;
3940 }
3941
3942 // is time standing still? if so, break out of here
3943 lastTimeCompare = icaltime_compare(impl->last, impl_last.last);
3944 if (lastTimeCompare == 0) {
3945 if (stalledCnt++ == max_recurrence_time_count) {
3946 break;
3947 }
3948 } else {
3949 stalledCnt = 0;
3950 }
3951 } while ((cntRecurrences++ < max_recurrences) &&
3952 ((lastTimeCompare == 0) ||
3953 icaltime_compare(impl->last, impl->istart) < 0 ||
3954 (!check_contracting_rules(impl)) ||
3955 (hasSetPos && !check_setpos(impl, 1))));
3956
3957 impl->occurrence_no++;
3958
3959 return impl->last;
3960}
3961
3962struct icaltimetype icalrecur_iterator_prev(icalrecur_iterator *impl)
3963{
3964 /* Quit if last time is before the DTSTART time */
3965 if (!impl || icaltime_compare(impl->last, impl->dtstart) < 0) {
3966 return icaltime_null_time();
3967 }
3968
3969 int period_change = 1;
3970 icalrecur_iterator impl_last = *impl;
3971 bool hasSetPos = has_by_data(impl, ICAL_BY_SET_POS);
3972 int checkContractingRules = (int)check_contracting_rules(impl);
3973
3974 /* Iterate until we get the next valid time */
3975 do {
3976 switch (impl->rule->freq) {
3978 prev_second(impl);
3979 break;
3980
3982 period_change = prev_minute(impl);
3983 break;
3984
3986 period_change = prev_hour(impl);
3987 break;
3988
3990 period_change = prev_day(impl);
3991 break;
3992
3994 period_change = prev_week(impl);
3995 break;
3996
3998 period_change = prev_month(impl);
3999 break;
4000
4002 period_change = prev_year(impl);
4003 break;
4004
4005 default:
4007 return icaltime_null_time();
4008 }
4009
4010 impl->last = occurrence_as_icaltime(impl, 1);
4011
4012 /* Ignore times that are before the DTSTART time */
4013 if (icaltime_compare(impl->last, impl->dtstart) < 0 ||
4014 (!icaltime_is_null_time(impl->istart) &&
4015 icaltime_compare(impl->last, impl->istart) < 0)) {
4016 *impl = impl_last;
4017 set_datetime(impl, impl_last.last);
4018 return icaltime_null_time();
4019 }
4020
4021 if (hasSetPos) {
4022 int new_ccr = (int)check_contracting_rules(impl);
4023 if (new_ccr == 1) {
4024 if (checkContractingRules == 0 || period_change) {
4025 setup_setpos(impl, 0);
4026 } else {
4027 impl->set_pos--;
4028 }
4029 }
4030 checkContractingRules = new_ccr;
4031 }
4032
4033 } while (impl->last.year > MAX_TIME_T_YEAR ||
4034 (!icaltime_is_null_time(impl->rule->until) &&
4035 icaltime_compare(impl->last, impl->rule->until) > 0) ||
4036 (!icaltime_is_null_time(impl->iend) &&
4037 icaltime_compare(impl->last, impl->iend) > 0) ||
4038 icaltime_compare(impl->last, impl_last.last) == 0 ||
4039 (hasSetPos && !check_setpos(impl, 0)) ||
4040 !check_contracting_rules(impl));
4041
4042 impl->occurrence_no--;
4043
4044 return impl->last;
4045}
4046
4049static void set_bydata_start(icalrecurrence_iterator_by_data *bydata, int tfield)
4050{
4051 int bdi;
4052 for (bdi = 0;
4053 bdi < bydata->by.size; bdi++) {
4054 if (bydata->by.data[bdi] == tfield) {
4055 bydata->index = bdi;
4056 return;
4057 }
4058 }
4059}
4060
4061static bool __iterator_set_start(icalrecur_iterator *impl, icaltimetype start)
4062{
4063 icalrecurrencetype_frequency freq = impl->rule->freq;
4064 short interval = impl->rule->interval;
4065 int diff;
4066
4067 impl->istart = start;
4068 impl->occurrence_no = 0;
4069 impl->days_index = ICAL_YEARDAYS_MASK_SIZE;
4070
4071 /* Set Gregorian start date */
4072 set_start(impl, start);
4073
4074 switch (freq) {
4076 /* For YEARLY rule, begin by setting up the year days array.
4077 The YEARLY rules work by expanding one year at a time. */
4078
4079 if ((interval > 1) &&
4080 (diff = (impl->istart.year - impl->rstart.year) % interval)) {
4081 /* Specified start year doesn't match interval -
4082 bump start to first day of next year that matches interval */
4083 set_day_of_year(impl, 1);
4084 increment_year(impl, interval - diff);
4085 }
4086
4087 /* Get (adjusted) start date as RSCALE date */
4088 start = occurrence_as_icaltime(impl, 0);
4089
4090 if (has_by_data(impl, ICAL_BY_WEEK_NO)) {
4091 int start_weekno = get_week_number(impl, start);
4092 if (start_weekno > 5 &&
4093 start.month == 1) {
4094 /* if we are in the last week of the previous year,
4095 * expand year days for the previous year
4096 */
4097 increment_year(impl, -1);
4098 expand_year_days(impl, start.year - 1);
4099 int days_in_year = get_days_in_year(impl, start.year - 1);
4100 impl->days_index = daymask_find_next_bit(impl->days, days_in_year + 1);
4101 if (impl->days_index >= ICAL_YEARDAYS_MASK_SIZE) {
4102 increment_year(impl, 1);
4103 }
4104 } else if (start_weekno < 45 &&
4105 start.month == 12) {
4106 /* if we are in the first week of the next year,
4107 * expand year days for the next year
4108 */
4109 increment_year(impl, 1);
4110 expand_year_days(impl, start.year + 1);
4111 impl->days_index = daymask_find_next_bit(impl->days, -ICAL_YEARDAYS_MASK_OFFSET);
4112 if (impl->days_index >= ICAL_YEARDAYS_MASK_SIZE) {
4113 increment_year(impl, -1);
4114 }
4115 }
4116 }
4117
4118 /* Expand days array for (adjusted) start year -
4119 fail after hitting the year MAX_TIME_T_YEAR if no expanded days match */
4120 while (start.year < MAX_TIME_T_YEAR && impl->days_index >= ICAL_YEARDAYS_MASK_SIZE) {
4121 expand_year_days(impl, start.year);
4122
4124 switch (err) {
4125 case ICAL_NO_ERROR:
4126 break;
4128 return false;
4129 default:
4131 return false;
4132 }
4133
4134 if (impl->days_index >= ICAL_YEARDAYS_MASK_SIZE) {
4135 increment_year(impl, interval);
4136 start = occurrence_as_icaltime(impl, 0);
4137 }
4138 }
4139
4140 /* Copy the first day into last */
4141 set_day_of_year(impl, impl->days_index);
4142 if (impl->days_index < 1) {
4143 increment_year(impl, -1);
4144 }
4145
4146 break;
4147
4149 /* For MONTHLY rule, begin by setting up the year days array.
4150 The MONTHLY rules work by expanding one month at a time. */
4151
4152 if ((interval > 1) &&
4153 (diff = month_diff(impl, impl->rstart, impl->istart) % interval)) {
4154 /* Specified month doesn't match interval -
4155 bump start to first day of next month that matches interval */
4156 increment_monthday(impl, -impl->istart.day + 1);
4157 __increment_month(impl, interval - diff);
4158 }
4159
4160 /* Get (adjusted) start date as RSCALE date */
4161 start = occurrence_as_icaltime(impl, 0);
4162
4163 /* Expand days array for (adjusted) start month -
4164 fail after hitting the year 20000 if no expanded days match */
4165 while (start.year < 20000) {
4166 expand_month_days(impl, start.year, start.month);
4167 if (impl->days_index < ICAL_YEARDAYS_MASK_SIZE) {
4168 break; /* break when a matching day is found */
4169 }
4170 increment_month(impl, impl->rule->interval);
4171 start = occurrence_as_icaltime(impl, 0);
4172 }
4173
4174 /* Copy the first day into last */
4175 set_day_of_year(impl, impl->days_index);
4176
4177 break;
4178
4180 if (impl->bydata[ICAL_BY_DAY].by.size <= 0) {
4181 /* Weekly recurrences with no ICAL_BY_DAY data should occur on the
4182 same day of the week as the start time . */
4183 recur_iterator_set_static_single_by_value(impl, ICAL_BY_DAY, (short)get_day_of_week(impl));
4184 } else {
4185 adjust_to_byday(impl);
4186
4187 /* If start == DTSTART, adjust rstart */
4188 if (icaltime_compare(start, impl->dtstart) == 0) {
4189 impl->rstart = occurrence_as_icaltime(impl, 0);
4190 }
4191
4192 /* Get (adjusted) start date as RSCALE date */
4193 start = occurrence_as_icaltime(impl, 0);
4194
4195 if ((interval > 1) &&
4196 (diff = (day_diff(impl, impl->rstart, start) + 6) / 7) % interval) {
4197 /* Specified week doesn't match interval -
4198 bump start to next week that matches interval */
4199 increment_monthday(impl, 7 * (interval - diff));
4200 }
4201 }
4202 break;
4203
4205 if ((interval > 1) &&
4206 (diff = day_diff(impl, impl->rstart, impl->istart) % interval)) {
4207 /* Specified day doesn't match interval -
4208 bump start to next day that matches interval */
4209 increment_monthday(impl, interval - diff);
4210 }
4211 break;
4212
4214 if ((interval > 1) &&
4215 (diff = abs(impl->istart.hour - impl->rstart.hour) % interval)) {
4216 /* Specified hour doesn't match interval -
4217 bump start to next hour that matches interval */
4218 increment_hour(impl, interval - diff);
4219 }
4220 set_bydata_start(&impl->bydata[ICAL_BY_HOUR], impl->istart.hour);
4221 break;
4222
4224 if ((interval > 1) &&
4225 (diff = abs(impl->istart.minute - impl->rstart.minute) % interval)) {
4226 /* Specified minute doesn't match interval -
4227 bump start to next minute that matches interval */
4228 increment_minute(impl, interval - diff);
4229 }
4230 set_bydata_start(&impl->bydata[ICAL_BY_MINUTE], impl->istart.minute);
4231 break;
4232
4234 if ((interval > 1) &&
4235 (diff = abs(impl->istart.second - impl->rstart.second) % interval)) {
4236 /* Specified second doesn't match interval -
4237 bump start to next second that matches interval */
4238 increment_second(impl, interval - diff);
4239 }
4240 set_bydata_start(&impl->bydata[ICAL_BY_SECOND], impl->istart.second);
4241 break;
4242
4243 default:
4244 break;
4245 }
4246
4247 /* Get start date as Gregorian date */
4248 impl->last = occurrence_as_icaltime(impl, 1);
4249 if (has_by_data(impl, ICAL_BY_SET_POS)) {
4250 setup_setpos(impl, 1);
4251 }
4252
4253 /* Fail if first instance exceeds MAX_TIME_T_YEAR */
4254 if (impl->last.year > MAX_TIME_T_YEAR) {
4256 return false;
4257 }
4258
4259 return true;
4260}
4261
4262bool icalrecur_iterator_set_start(icalrecur_iterator *impl,
4263 struct icaltimetype start)
4264{
4265 /* We can't adjust start date if we need to count occurrences */
4266 if (impl->rule->count > 0) {
4268 return false;
4269 }
4270
4271 /* Convert start to same time zone as DTSTART */
4272 start = icaltime_convert_to_zone(start, (icaltimezone *)impl->dtstart.zone);
4273
4274 if (icaltime_compare(start, impl->dtstart) < 0) {
4275 /* If start is before DTSTART, use DTSTART */
4276 start = impl->dtstart;
4277 } else if (!icaltime_is_null_time(impl->rule->until) &&
4278 icaltime_compare(start, impl->rule->until) > 0) {
4279 /* If start is after UNTIL, we're done */
4280 impl->last = start;
4281 return true;
4282 }
4283
4284 return __iterator_set_start(impl, start);
4285}
4286
4287bool icalrecur_iterator_set_end(icalrecur_iterator *impl,
4288 struct icaltimetype end)
4289{
4290 /* Convert end to same time zone as DTSTART */
4291 end = icaltime_convert_to_zone(end, (icaltimezone *)impl->dtstart.zone);
4292
4293 impl->iend = end;
4294
4295 return true;
4296}
4297
4298bool icalrecur_iterator_set_range(icalrecur_iterator *impl,
4299 struct icaltimetype from,
4300 struct icaltimetype to)
4301{
4302 if (impl->rule->count > 0 || icaltime_is_null_time(from)) {
4303 /* Can't set a range without 'from' or if we need to count occurrences */
4305 return false;
4306 }
4307
4308 if (!icaltime_is_null_time(to) && icaltime_compare(to, from) < 0) {
4309 /* Setting up for the reverse iterator */
4310 const icaltimezone *zone = impl->dtstart.zone;
4311
4312 /* Convert 'from' to same time zone as DTSTART */
4314
4315 if (!icaltime_is_null_time(impl->rule->until) &&
4316 icaltime_compare(from, impl->rule->until) > 0) {
4317 /* If 'from' is after UNTIL, use UNTIL */
4318 from = impl->rule->until;
4319 } else if (icaltime_compare(from, impl->dtstart) < 0) {
4320 /* If 'from' is before START, we're done */
4321 impl->last = from;
4322 return true;
4323 }
4324
4325 if (!__iterator_set_start(impl, from)) {
4326 return false;
4327 }
4328
4329 /* __iterator_set_start() may back us up earlier than 'from'
4330 Iterate forward until we are later than 'from'.
4331 */
4332 while (icaltime_compare(impl->last, from) < 0) {
4334 /* The recurrence ends before 'from' */
4335 break;
4336 }
4337 }
4338
4339 /* Convert 'to' to same time zone as DTSTART */
4341
4342 if (icaltime_compare(to, impl->dtstart) < 0) {
4343 /* If 'to' is before DTSTART, use DTSTART */
4344 to = impl->dtstart;
4345 }
4346
4347 impl->istart = to;
4348 impl->iend = from;
4349 impl->days_index = 0;
4350 } else {
4351 if (!icalrecur_iterator_set_start(impl, from)) {
4352 return false;
4353 }
4354
4356 }
4357
4358 return true;
4359}
4360
4361/************************** Type Routines **********************/
4362
4363static void icalrecurrencetype_clear(struct icalrecurrencetype *recur)
4364{
4365 int refcount = recur->refcount;
4366
4367 icalrecurrencetype_free(recur, 0);
4368
4369 memset(recur, 0, sizeof(*recur));
4370
4371 recur->refcount = refcount;
4372
4374 recur->freq = ICAL_NO_RECURRENCE;
4375 recur->interval = 1;
4376 recur->until = icaltime_null_time();
4377 recur->count = 0;
4378 recur->rscale = NULL;
4379 recur->skip = ICAL_SKIP_OMIT;
4380}
4381
4386
4388{
4389 int wd, pos;
4390
4392
4393 pos = (abs(day) - wd) / 8 * ((day < 0) ? -1 : 1);
4394
4395 return pos;
4396}
4397
4399{
4400 short s_weekday = (short)weekday;
4401 short a_position = (short)(8 * abs(position));
4402 return (s_weekday + a_position) * ((position < 0) ? -1 : 1);
4403}
4404
4406{
4407 return (month & LEAP_MONTH) != 0;
4408}
4409
4411{
4412 return (month & ~LEAP_MONTH);
4413}
4414
4416{
4417 return (short)month | (is_leap ? LEAP_MONTH : 0); //NOLINT(readability-implicit-bool-conversion)
4418}
4419
4420bool icalrecur_expand_recurrence(const char *rule,
4421 icaltime_t start, int count, icaltime_t *array)
4422{
4423 struct icalrecurrencetype *recur;
4424 icalrecur_iterator *ritr;
4425 struct icaltimetype icstart;
4426
4427 memset(array, 0, (size_t)count * sizeof(icaltime_t));
4428
4429 icstart = icaltime_from_timet_with_zone(start, false, 0);
4430
4432 if (!recur) {
4433 return false;
4434 }
4435
4436 ritr = icalrecur_iterator_new(recur, icstart);
4437 if (ritr) {
4438 int i = 0;
4439 for (struct icaltimetype next = icalrecur_iterator_next(ritr);
4440 !icaltime_is_null_time(next) && i < count;
4441 next = icalrecur_iterator_next(ritr)) {
4442 icaltime_t tt = icaltime_as_timet(next);
4443
4444 if (tt >= start) {
4445 array[i++] = tt;
4446 }
4447 }
4449 }
4450
4452
4453 return true;
4454}
4455
4457{
4458 ical_invalid_rrule_handling myHandling;
4459
4460#if ICAL_SYNC_MODE == ICAL_SYNC_MODE_PTHREAD
4461 if (pthread_mutex_lock(&invalid_rrule_mutex) != 0) {
4463 }
4464#endif
4465
4466 myHandling = invalidRruleHandling;
4467
4468#if ICAL_SYNC_MODE == ICAL_SYNC_MODE_PTHREAD
4469 if (pthread_mutex_unlock(&invalid_rrule_mutex) != 0) {
4471 }
4472#endif
4473
4474 return myHandling;
4475}
4476
4478{
4479#if ICAL_SYNC_MODE == ICAL_SYNC_MODE_PTHREAD
4480 if (pthread_mutex_lock(&invalid_rrule_mutex) != 0) {
4482 }
4483#endif
4484
4485 invalidRruleHandling = newSetting;
4486
4487#if ICAL_SYNC_MODE == ICAL_SYNC_MODE_PTHREAD
4488 if (pthread_mutex_unlock(&invalid_rrule_mutex) != 0) {
4490 }
4491#endif
4492}
void icalarray_append(icalarray *array, const void *element)
Appends an element to an array.
Definition icalarray.c:119
icalarray * icalarray_new(size_t element_size, size_t increment_size)
Definition icalarray.c:36
void icalerror_set_errno(icalerrorenum x)
Sets the icalerrno to a given error.
Definition icalerror.c:90
void icalerror_clear_errno(void)
Resets icalerrno to ICAL_NO_ERROR.
Definition icalerror.c:85
Error handling for libical.
icalerrorenum
Represents the different types of errors that can be triggered in libical.
Definition icalerror.h:42
@ ICAL_NEWFAILED_ERROR
Definition icalerror.h:50
@ ICAL_INTERNAL_ERROR
Definition icalerror.h:65
@ ICAL_NO_ERROR
Definition icalerror.h:44
@ ICAL_MALFORMEDDATA_ERROR
Definition icalerror.h:59
@ ICAL_THREADING_ERROR
Definition icalerror.h:56
@ ICAL_UNIMPLEMENTED_ERROR
Definition icalerror.h:74
@ ICAL_USAGE_ERROR
Definition icalerror.h:71
#define icalerrno
Access the current icalerrno value.
Definition icalerror.h:133
size_t icallimit_get(icallimits_kind kind)
Definition icallimits.c:29
Defines the interface for getting/setting internal library limits.
@ ICAL_LIMIT_RECURRENCE_SEARCH
Definition icallimits.h:38
@ ICAL_LIMIT_RECURRENCE_TIME_STANDING_STILL
Definition icallimits.h:40
void icalmemory_free_buffer(void *buf)
Releases a buffer.
Definition icalmemory.c:355
char * icalmemory_strdup(const char *s)
Creates a duplicate of a string.
Definition icalmemory.c:242
void icalmemory_append_string(char **buf, char **pos, size_t *buf_size, const char *string)
Appends a string to a buffer.
Definition icalmemory.c:365
void * icalmemory_resize_buffer(void *buf, size_t size)
Resizes a buffer created with icalmemory_new_buffer().
Definition icalmemory.c:336
void * icalmemory_new_buffer(size_t size)
Creates new buffer with the specified size.
Definition icalmemory.c:315
char * icalmemory_tmp_copy(const char *str)
Creates a copy of the given string, stored on the ring buffer, and returns it.
Definition icalmemory.c:222
void icalmemory_append_char(char **buf, char **pos, size_t *buf_size, char ch)
Appends a character to a buffer.
Definition icalmemory.c:406
void icalmemory_add_tmp_buffer(void *buf)
Adds an externally allocated buffer to the ring.
Definition icalmemory.c:158
void * icalmemory_tmp_buffer(size_t size)
Creates a new temporary buffer on the ring and returns it.
Definition icalmemory.c:182
Common memory management routines.
bool icalrecur_iterator_set_start(icalrecur_iterator *impl, struct icaltimetype start)
Definition icalrecur.c:4262
struct icalrecurrencetype * icalrecurrencetype_new_from_string(const char *str)
Definition icalrecur.c:869
struct icaltimetype icalrecur_iterator_prev(icalrecur_iterator *impl)
Definition icalrecur.c:3962
void icalrecurrencetype_ref(struct icalrecurrencetype *recur)
Definition icalrecur.c:782
icalrecurrencetype_skip icalrecur_string_to_skip(const char *str)
Definition icalrecur.c:234
bool icalrecur_iterator_set_end(icalrecur_iterator *impl, struct icaltimetype end)
Definition icalrecur.c:4287
short icalrecurrencetype_encode_month(int month, bool is_leap)
Definition icalrecur.c:4415
short icalrecurrencetype_encode_day(enum icalrecurrencetype_weekday weekday, int position)
Definition icalrecur.c:4398
bool icalrecurrencetype_month_is_leap(short month)
Definition icalrecur.c:4405
const char * icalrecur_weekday_to_string(icalrecurrencetype_weekday kind)
Definition icalrecur.c:271
const char * icalrecur_skip_to_string(icalrecurrencetype_skip kind)
Definition icalrecur.c:246
bool icalrecur_resize_by(icalrecurrence_by_data *by, short size)
Definition icalrecur.c:306
struct icalrecurrencetype * icalrecurrencetype_clone(struct icalrecurrencetype *recur)
Definition icalrecur.c:832
const char * icalrecur_freq_to_string(icalrecurrencetype_frequency kind)
Definition icalrecur.c:213
void ical_set_invalid_rrule_handling_setting(ical_invalid_rrule_handling newSetting)
Definition icalrecur.c:4477
void icalrecur_iterator_free(icalrecur_iterator *impl)
Definition icalrecur.c:2525
icalrecurrencetype_frequency icalrecur_string_to_freq(const char *str)
Definition icalrecur.c:201
struct icalrecurrencetype * icalrecurrencetype_new(void)
Definition icalrecur.c:743
bool icalrecur_iterator_set_range(icalrecur_iterator *impl, struct icaltimetype from, struct icaltimetype to)
Definition icalrecur.c:4298
icalarray * icalrecurrencetype_rscale_supported_calendars(void)
Definition icalrecur.c:2075
enum icalrecurrencetype_weekday icalrecurrencetype_day_day_of_week(short day)
Definition icalrecur.c:4382
ical_invalid_rrule_handling ical_get_invalid_rrule_handling_setting(void)
Definition icalrecur.c:4456
int icalrecurrencetype_day_position(short day)
Definition icalrecur.c:4387
bool icalrecur_expand_recurrence(const char *rule, icaltime_t start, int count, icaltime_t *array)
Definition icalrecur.c:4420
char * icalrecurrencetype_as_string(struct icalrecurrencetype *recur)
Definition icalrecur.c:1060
void icalrecurrencetype_unref(struct icalrecurrencetype *recur)
Definition icalrecur.c:790
icalrecur_iterator * icalrecur_iterator_new(struct icalrecurrencetype *rule, struct icaltimetype dtstart)
Definition icalrecur.c:2390
struct icaltimetype icalrecur_iterator_next(icalrecur_iterator *impl)
Definition icalrecur.c:3847
icalrecurrencetype_weekday icalrecur_string_to_weekday(const char *str)
Definition icalrecur.c:284
int icalrecurrencetype_month_month(short month)
Definition icalrecur.c:4410
char * icalrecurrencetype_as_string_r(struct icalrecurrencetype *recur)
Definition icalrecur.c:1069
Routines for dealing with recurring time.
icalrecurrencetype_weekday
Definition icalrecur.h:100
@ ICAL_TUESDAY_WEEKDAY
Definition icalrecur.h:104
@ ICAL_NO_WEEKDAY
Definition icalrecur.h:101
@ ICAL_WEDNESDAY_WEEKDAY
Definition icalrecur.h:105
@ ICAL_FRIDAY_WEEKDAY
Definition icalrecur.h:107
@ ICAL_THURSDAY_WEEKDAY
Definition icalrecur.h:106
@ ICAL_MONDAY_WEEKDAY
Definition icalrecur.h:103
@ ICAL_SATURDAY_WEEKDAY
Definition icalrecur.h:108
@ ICAL_SUNDAY_WEEKDAY
Definition icalrecur.h:102
icalrecurrencetype_frequency
Definition icalrecur.h:85
@ ICAL_NO_RECURRENCE
Definition icalrecur.h:93
@ ICAL_HOURLY_RECURRENCE
Definition icalrecur.h:88
@ ICAL_SECONDLY_RECURRENCE
Definition icalrecur.h:86
@ ICAL_YEARLY_RECURRENCE
Definition icalrecur.h:92
@ ICAL_DAILY_RECURRENCE
Definition icalrecur.h:89
@ ICAL_MINUTELY_RECURRENCE
Definition icalrecur.h:87
@ ICAL_WEEKLY_RECURRENCE
Definition icalrecur.h:90
@ ICAL_MONTHLY_RECURRENCE
Definition icalrecur.h:91
icalrecurrencetype_skip
Definition icalrecur.h:115
@ ICAL_SKIP_OMIT
Definition icalrecur.h:118
@ ICAL_SKIP_UNDEFINED
Definition icalrecur.h:119
@ ICAL_SKIP_FORWARD
Definition icalrecur.h:117
@ ICAL_SKIP_BACKWARD
Definition icalrecur.h:116
icalrecurrencetype_byrule
Definition icalrecur.h:126
@ ICAL_BY_SET_POS
Definition icalrecur.h:136
@ ICAL_BY_HOUR
Definition icalrecur.h:133
@ ICAL_BY_MINUTE
Definition icalrecur.h:134
@ ICAL_BY_MONTH
Definition icalrecur.h:128
@ ICAL_BY_SECOND
Definition icalrecur.h:135
@ ICAL_BY_YEAR_DAY
Definition icalrecur.h:130
@ ICAL_BY_MONTH_DAY
Definition icalrecur.h:131
@ ICAL_BY_DAY
Definition icalrecur.h:132
@ ICAL_BY_WEEK_NO
Definition icalrecur.h:129
@ ICAL_BYRULE_NO_CONTRACTION
Definition icalrecur.h:127
@ ICAL_BY_NUM_PARTS
Definition icalrecur.h:138
ical_invalid_rrule_handling
Definition icalrecur.h:617
@ ICAL_RRULE_TREAT_AS_ERROR
Definition icalrecur.h:619
@ ICAL_RRULE_IGNORE_INVALID
Definition icalrecur.h:621
struct icaltimetype icaltime_from_timet_with_zone(const icaltime_t tm, const bool is_date, const icaltimezone *zone)
Constructor.
Definition icaltime.c:214
struct icaltimetype icaltime_from_string(const char *str)
Definition icaltime.c:379
int icaltime_day_of_year(const struct icaltimetype t)
Definition icaltime.c:540
int icaltime_start_doy_week(const struct icaltimetype t, int fdow)
Definition icaltime.c:519
bool icaltime_is_leap_year(const int year)
Definition icaltime.c:458
int icaltime_day_of_week(const struct icaltimetype t)
Definition icaltime.c:504
struct icaltimetype icaltime_from_day_of_year(const int _doy, const int _year)
Definition icaltime.c:549
bool icaltime_is_valid_time(const struct icaltimetype t)
Definition icaltime.c:612
int icaltime_days_in_month(const int month, const int year)
Definition icaltime.c:478
struct icaltimetype icaltime_convert_to_zone(const struct icaltimetype tt, icaltimezone *zone)
Definition icaltime.c:860
int icaltime_days_in_year(const int year)
Definition icaltime.c:467
bool icaltime_is_null_time(const struct icaltimetype t)
Definition icaltime.c:644
struct icaltimetype icaltime_normalize(const struct icaltimetype tt)
Definition icaltime.c:371
icaltime_t icaltime_as_timet(const struct icaltimetype tt)
Definition icaltime.c:264
int icaltime_compare(const struct icaltimetype a_in, const struct icaltimetype b_in)
Definition icaltime.c:653
void icaltime_adjust(struct icaltimetype *tt, const int days, const int hours, const int minutes, const int seconds)
Definition icaltime.c:769
struct icaltimetype icaltime_null_time(void)
Definition icaltime.c:584
const char * icaltimezone_get_location(const icaltimezone *zone)
const char * icaltimezone_get_tzid(icaltimezone *zone)
const char * icaltimezone_tzid_prefix(void)
Timezone handling routines.
struct _icaltimezone icaltimezone
Defines the data structure representing iCalendar parameter values.
icalrecurrencetype_frequency freq
Definition icalrecur.h:255
icalrecurrencetype_skip skip
Definition icalrecur.h:292
icalrecurrencetype_weekday week_start
Definition icalrecur.h:267
struct icaltimetype until
Definition icalrecur.h:258
icalrecurrence_by_data by[ICAL_BY_NUM_PARTS]
Definition icalrecur.h:286
const icaltimezone * zone
Definition icaltime.h:102