Debian Codegraph @

src/shared/calendarspec.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6
7 #include "alloc-util.h"
8 #include "calendarspec.h"
9 #include "errno-util.h"
10 #include "log.h"
11 #include "memstream-util.h"
12 #include "parse-util.h"
13 #include "sort-util.h"
14 #include "string-util.h"
15 #include "strv.h"
16 #include "time-util.h"
17
18 #define BITS_WEEKDAYS 127
19 #define MIN_YEAR 1970
20 #define MAX_YEAR 2199
21
22 /* An arbitrary limit on the length of the chains of components. We don't want to
23 * build a very long linked list, which would be slow to iterate over and might cause
24 * our stack to overflow. It's unlikely that legitimate uses require more than a few
25 * linked components anyway. */
26 #define CALENDARSPEC_COMPONENTS_MAX 240
27
28 /* Let's make sure that the microsecond component is safe to be stored in an 'int' */
29 assert_cc(INT_MAX >= USEC_PER_SEC);
30
31 static CalendarComponent* chain_free(CalendarComponent *c) {
32 while (c) {
33 CalendarComponent *n = c->next;
34 free_and_replace(c, n);
35 }
36 return NULL;
37 }
38
39 DEFINE_TRIVIAL_CLEANUP_FUNC(CalendarComponent*, chain_free);
40
41 CalendarSpec* calendar_spec_free(CalendarSpec *c) {
42 POINTER_MAY_BE_NULL(c);
43
44 if (!c)
45 return NULL;
46
47 chain_free(c->year);
48 chain_free(c->month);
49 chain_free(c->day);
50 chain_free(c->hour);
51 chain_free(c->minute);
52 chain_free(c->microsecond);
53 free(c->timezone);
54
55 return mfree(c);
56 }
57
58 static int component_compare(CalendarComponent * const *a, CalendarComponent * const *b) {
59 int r;
60
61 assert(a);
62 assert(b);
63
64 r = CMP((*a)->start, (*b)->start);
65 if (r != 0)
66 return r;
67
68 r = CMP((*a)->stop, (*b)->stop);
69 if (r != 0)
70 return r;
71
72 return CMP((*a)->repeat, (*b)->repeat);
73 }
74
75 static void normalize_chain(CalendarComponent **c) {
76 assert(c);
77
78 size_t n = 0;
79 for (CalendarComponent *i = *c; i; i = i->next) {
80 n++;
81
82 /* While we're counting the chain, also normalize 'stop'
83 * so the length of the range is a multiple of 'repeat'. */
84 if (i->stop > i->start && i->repeat > 0)
85 i->stop -= (i->stop - i->start) % i->repeat;
86
87 /* If a repeat value is specified, but it cannot even be triggered once, let's suppress it.
88 *
89 * Similarly, if the stop value is the same as the start value, then let's just make this a
90 * non-repeating chain element. */
91 if ((i->stop > i->start && i->repeat > 0 && i->start + i->repeat > i->stop) ||
92 i->start == i->stop) {
93 i->repeat = 0;
94 i->stop = -1;
95 }
96 }
97
98 if (n <= 1)
99 return;
100
101 CalendarComponent **b, **j;
102 b = j = newa(CalendarComponent*, n);
103 for (CalendarComponent *i = *c; i; i = i->next)
104 *(j++) = i;
105
106 typesafe_qsort(b, n, component_compare);
107
108 b[n-1]->next = NULL;
109 CalendarComponent *next = b[n-1];
110
111 /* Drop non-unique entries */
112 for (size_t k = n-1; k > 0; k--) {
113 if (component_compare(&b[k-1], &next) == 0) {
114 free(b[k-1]);
115 continue;
116 }
117
118 b[k-1]->next = next;
119 next = b[k-1];
120 }
121
122 *c = next;
123 }
124
125 static void fix_year(CalendarComponent *c) {
126 /* Turns 12 → 2012, 89 → 1989 */
127
128 while (c) {
129 if (c->start >= 0 && c->start < 70)
130 c->start += 2000;
131
132 if (c->stop >= 0 && c->stop < 70)
133 c->stop += 2000;
134
135 if (c->start >= 70 && c->start < 100)
136 c->start += 1900;
137
138 if (c->stop >= 70 && c->stop < 100)
139 c->stop += 1900;
140
141 c = c->next;
142 }
143 }
144
145 static void calendar_spec_normalize(CalendarSpec *c) {
146 assert(c);
147
148 if (streq_ptr(c->timezone, "UTC")) {
149 c->utc = true;
150 c->timezone = mfree(c->timezone);
151 }
152
153 if (c->weekdays_bits <= 0 || c->weekdays_bits >= BITS_WEEKDAYS)
154 c->weekdays_bits = -1;
155
156 if (c->end_of_month && !c->day)
157 c->end_of_month = false;
158
159 fix_year(c->year);
160
161 normalize_chain(&c->year);
162 normalize_chain(&c->month);
163 normalize_chain(&c->day);
164 normalize_chain(&c->hour);
165 normalize_chain(&c->minute);
166 normalize_chain(&c->microsecond);
167 }
168
169 static bool chain_valid(CalendarComponent *c, int from, int to, bool end_of_month) {
170 assert(to >= from);
171
172 if (!c)
173 return true;
174
175 /* Forbid dates more than 28 days from the end of the month */
176 if (end_of_month)
177 to -= 3;
178
179 if (c->start < from || c->start > to)
180 return false;
181
182 /* Avoid overly large values that could cause overflow */
183 if (c->repeat > to - from)
184 return false;
185
186 /*
187 * c->repeat must be short enough so at least one repetition may
188 * occur before the end of the interval. For dates scheduled
189 * relative to the end of the month, c->start and c->stop
190 * correspond to the Nth last day of the month.
191 */
192 if (c->stop >= 0) {
193 if (c->stop < from || c ->stop > to)
194 return false;
195
196 if (c->start + c->repeat > c->stop)
197 return false;
198 } else {
199 if (end_of_month && c->start - c->repeat < from)
200 return false;
201
202 if (!end_of_month && c->start + c->repeat > to)
203 return false;
204 }
205
206 if (c->next)
207 return chain_valid(c->next, from, to, end_of_month);
208
209 return true;
210 }
211
212 _pure_ bool calendar_spec_valid(CalendarSpec *c) {
213 assert(c);
214
215 if (c->weekdays_bits > BITS_WEEKDAYS)
216 return false;
217
218 if (!chain_valid(c->year, MIN_YEAR, MAX_YEAR, false))
219 return false;
220
221 if (!chain_valid(c->month, 1, 12, false))
222 return false;
223
224 if (!chain_valid(c->day, 1, 31, c->end_of_month))
225 return false;
226
227 if (!chain_valid(c->hour, 0, 23, false))
228 return false;
229
230 if (!chain_valid(c->minute, 0, 59, false))
231 return false;
232
233 if (!chain_valid(c->microsecond, 0, 60*USEC_PER_SEC-1, false))
234 return false;
235
236 return true;
237 }
238
239 static void format_weekdays(FILE *f, const CalendarSpec *c) {
240 static const char *const days[] = {
241 "Mon",
242 "Tue",
243 "Wed",
244 "Thu",
245 "Fri",
246 "Sat",
247 "Sun",
248 };
249
250 int l, x;
251 bool need_comma = false;
252
253 assert(f);
254 assert(c);
255 assert(c->weekdays_bits > 0 && c->weekdays_bits <= BITS_WEEKDAYS);
256
257 for (x = 0, l = -1; x < (int) ELEMENTSOF(days); x++) {
258
259 if (c->weekdays_bits & (1 << x)) {
260
261 if (l < 0) {
262 if (need_comma)
263 fputc(',', f);
264 else
265 need_comma = true;
266
267 fputs(days[x], f);
268 l = x;
269 }
270
271 } else if (l >= 0) {
272
273 if (x > l + 1) {
274 fputs(x > l + 2 ? ".." : ",", f);
275 fputs(days[x-1], f);
276 }
277
278 l = -1;
279 }
280 }
281
282 if (l >= 0 && x > l + 1) {
283 fputs(x > l + 2 ? ".." : ",", f);
284 fputs(days[x-1], f);
285 }
286 }
287
288 static bool chain_is_star(const CalendarComponent *c, bool usec) {
289 /* Return true if the whole chain can be replaced by '*'.
290 * This happens when the chain is empty or one of the components covers all. */
291 if (!c)
292 return true;
293 if (usec)
294 for (; c; c = c->next)
295 if (c->start == 0 && c->stop < 0 && c->repeat == USEC_PER_SEC)
296 return true;
297 return false;
298 }
299
300 static void _format_chain(FILE *f, int space, const CalendarComponent *c, bool start, bool usec) {
301 int d = usec ? (int) USEC_PER_SEC : 1;
302
303 assert(f);
304
305 if (start && chain_is_star(c, usec)) {
306 fputc('*', f);
307 return;
308 }
309
310 assert(c->start >= 0);
311
312 fprintf(f, "%0*i", space, c->start / d);
313 if (c->start % d > 0)
314 fprintf(f, ".%06i", c->start % d);
315
316 if (c->stop > 0)
317 fprintf(f, "..%0*i", space, c->stop / d);
318 if (c->stop % d > 0)
319 fprintf(f, ".%06i", c->stop % d);
320
321 if (c->repeat > 0 && !(c->stop > 0 && c->repeat == d))
322 fprintf(f, "/%i", c->repeat / d);
323 if (c->repeat % d > 0)
324 fprintf(f, ".%06i", c->repeat % d);
325
326 if (c->next) {
327 fputc(',', f);
328 _format_chain(f, space, c->next, false, usec);
329 }
330 }
331
332 static void format_chain(FILE *f, int space, const CalendarComponent *c, bool usec) {
333 _format_chain(f, space, c, /* start= */ true, usec);
334 }
335
336 int calendar_spec_to_string(const CalendarSpec *c, char **ret) {
337 _cleanup_(memstream_done) MemStream m = {};
338 FILE *f;
339
340 assert(c);
341 assert(ret);
342
343 f = memstream_init(&m);
344 if (!f)
345 return -ENOMEM;
346
347 if (c->weekdays_bits > 0 && c->weekdays_bits <= BITS_WEEKDAYS) {
348 format_weekdays(f, c);
349 fputc(' ', f);
350 }
351
352 format_chain(f, 4, c->year, false);
353 fputc('-', f);
354 format_chain(f, 2, c->month, false);
355 fputc(c->end_of_month ? '~' : '-', f);
356 format_chain(f, 2, c->day, false);
357 fputc(' ', f);
358 format_chain(f, 2, c->hour, false);
359 fputc(':', f);
360 format_chain(f, 2, c->minute, false);
361 fputc(':', f);
362 format_chain(f, 2, c->microsecond, true);
363
364 if (c->utc)
365 fputs(" UTC", f);
366 else if (c->timezone) {
367 fputc(' ', f);
368 fputs(c->timezone, f);
369 } else if (IN_SET(c->dst, 0, 1)) {
370
371 /* If daylight saving is explicitly on or off, let's show the used timezone. */
372
373 tzset();
374
375 const char *z = get_tzname(c->dst);
376 if (z) {
377 fputc(' ', f);
378 fputs(z, f);
379 }
380 }
381
382 return memstream_finalize(&m, ret, NULL);
383 }
384
385 static int parse_weekdays(const char **p, CalendarSpec *c) {
386 static const struct {
387 const char *name;
388 const int nr;
389 } day_nr[] = {
390 { "Monday", 0 },
391 { "Mon", 0 },
392 { "Tuesday", 1 },
393 { "Tue", 1 },
394 { "Wednesday", 2 },
395 { "Wed", 2 },
396 { "Thursday", 3 },
397 { "Thu", 3 },
398 { "Friday", 4 },
399 { "Fri", 4 },
400 { "Saturday", 5 },
401 { "Sat", 5 },
402 { "Sunday", 6 },
403 { "Sun", 6 },
404 };
405
406 int l = -1;
407 bool first = true;
408
409 assert(p);
410 assert(*p);
411 assert(c);
412
413 for (;;) {
414 size_t i;
415
416 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
417 size_t skip;
418
419 if (!startswith_no_case(*p, day_nr[i].name))
420 continue;
421
422 skip = strlen(day_nr[i].name);
423
424 if (!IN_SET((*p)[skip], 0, '-', '.', ',', ' '))
425 return -EINVAL;
426
427 c->weekdays_bits |= 1 << day_nr[i].nr;
428
429 if (l >= 0) {
430 if (l > day_nr[i].nr)
431 return -EINVAL;
432
433 for (int j = l + 1; j < day_nr[i].nr; j++)
434 c->weekdays_bits |= 1 << j;
435 }
436
437 *p += skip;
438 break;
439 }
440
441 /* Couldn't find this prefix, so let's assume the
442 weekday was not specified and let's continue with
443 the date */
444 if (i >= ELEMENTSOF(day_nr))
445 return first ? 0 : -EINVAL;
446
447 /* We reached the end of the string */
448 if (**p == 0)
449 return 0;
450
451 /* We reached the end of the weekday spec part */
452 if (**p == ' ') {
453 *p += strspn(*p, " ");
454 return 0;
455 }
456
457 if (**p == '.') {
458 if (l >= 0)
459 return -EINVAL;
460
461 if ((*p)[1] != '.')
462 return -EINVAL;
463
464 l = day_nr[i].nr;
465 *p += 2;
466
467 /* Support ranges with "-" for backwards compatibility */
468 } else if (**p == '-') {
469 if (l >= 0)
470 return -EINVAL;
471
472 l = day_nr[i].nr;
473 *p += 1;
474
475 } else if (**p == ',') {
476 l = -1;
477 *p += 1;
478 }
479
480 /* Allow a trailing comma but not an open range */
481 if (IN_SET(**p, 0, ' ')) {
482 *p += strspn(*p, " ");
483 return l < 0 ? 0 : -EINVAL;
484 }
485
486 first = false;
487 }
488 }
489
490 static int parse_one_number(const char *p, const char **e, unsigned long *ret) {
491 char *ee = NULL;
492 unsigned long value;
493
494 assert(p);
495 assert(e);
496 assert(ret);
497
498 errno = 0;
499 value = strtoul(p, &ee, 10);
500 if (errno > 0)
501 return -errno;
502 if (ee == p)
503 return -EINVAL;
504
505 *ret = value;
506 *e = ee;
507 return 0;
508 }
509
510 static int parse_component_decimal(const char **p, bool usec, int *res) {
511 unsigned long value;
512 const char *e = NULL;
513 int r;
514
515 assert(p);
516 assert(res);
517
518 if (!ascii_isdigit(**p))
519 return -EINVAL;
520
521 r = parse_one_number(*p, &e, &value);
522 if (r < 0)
523 return r;
524
525 if (usec) {
526 if (value * USEC_PER_SEC / USEC_PER_SEC != value)
527 return -ERANGE;
528
529 value *= USEC_PER_SEC;
530
531 /* One "." is a decimal point, but ".." is a range separator */
532 if (e[0] == '.' && e[1] != '.') {
533 unsigned add;
534
535 e++;
536 r = parse_fractional_part_u(&e, 6, &add);
537 if (r < 0)
538 return r;
539
540 if (add + value < value)
541 return -ERANGE;
542 value += add;
543 }
544 }
545
546 if (value > INT_MAX)
547 return -ERANGE;
548
549 *p = e;
550 *res = value;
551
552 return 0;
553 }
554
555 static int const_chain(int value, CalendarComponent **c) {
556 CalendarComponent *cc = NULL;
557
558 assert(c);
559
560 cc = new(CalendarComponent, 1);
561 if (!cc)
562 return -ENOMEM;
563
564 *cc = (CalendarComponent) {
565 .start = value,
566 .stop = -1,
567 .repeat = 0,
568 .next = *c,
569 };
570
571 *c = cc;
572
573 return 0;
574 }
575
576 static int calendarspec_from_time_t(CalendarSpec *c, time_t time) {
577 _cleanup_(chain_freep) CalendarComponent
578 *year = NULL, *month = NULL, *day = NULL,
579 *hour = NULL, *minute = NULL, *us = NULL;
580 struct tm tm;
581 int r;
582
583 assert(c);
584
585 if ((usec_t) time > USEC_INFINITY / USEC_PER_SEC)
586 return -ERANGE;
587
588 r = localtime_or_gmtime_usec((usec_t) time * USEC_PER_SEC, /* utc= */ true, &tm);
589 if (r < 0)
590 return r;
591
592 if (tm.tm_year > INT_MAX - 1900)
593 return -ERANGE;
594
595 r = const_chain(tm.tm_year + 1900, &year);
596 if (r < 0)
597 return r;
598
599 r = const_chain(tm.tm_mon + 1, &month);
600 if (r < 0)
601 return r;
602
603 r = const_chain(tm.tm_mday, &day);
604 if (r < 0)
605 return r;
606
607 r = const_chain(tm.tm_hour, &hour);
608 if (r < 0)
609 return r;
610
611 r = const_chain(tm.tm_min, &minute);
612 if (r < 0)
613 return r;
614
615 r = const_chain(tm.tm_sec * USEC_PER_SEC, &us);
616 if (r < 0)
617 return r;
618
619 c->utc = true;
620 c->year = TAKE_PTR(year);
621 c->month = TAKE_PTR(month);
622 c->day = TAKE_PTR(day);
623 c->hour = TAKE_PTR(hour);
624 c->minute = TAKE_PTR(minute);
625 c->microsecond = TAKE_PTR(us);
626 return 0;
627 }
628
629 static int prepend_component(const char **p, bool usec, unsigned nesting, CalendarComponent **c) {
630 int r, start, stop = -1, repeat = 0;
631 CalendarComponent *cc;
632 const char *e = *ASSERT_PTR(p);
633
634 assert(c);
635
636 if (nesting > CALENDARSPEC_COMPONENTS_MAX)
637 return -ENOBUFS;
638
639 r = parse_component_decimal(&e, usec, &start);
640 if (r < 0)
641 return r;
642
643 if (e[0] == '.' && e[1] == '.') {
644 e += 2;
645 r = parse_component_decimal(&e, usec, &stop);
646 if (r < 0)
647 return r;
648
649 repeat = usec ? USEC_PER_SEC : 1;
650 }
651
652 if (*e == '/') {
653 e++;
654 r = parse_component_decimal(&e, usec, &repeat);
655 if (r < 0)
656 return r;
657
658 if (repeat == 0)
659 return -ERANGE;
660 } else {
661 /* If no repeat value is specified for the μs component, then let's explicitly refuse ranges
662 * below 1s because our default repeat granularity is beyond that. */
663
664 /* Overflow check */
665 if (start > INT_MAX - repeat)
666 return -ERANGE;
667
668 if (usec && stop >= 0 && start + repeat > stop)
669 return -EINVAL;
670 }
671
672 if (!IN_SET(*e, 0, ' ', ',', '-', '~', ':'))
673 return -EINVAL;
674
675 cc = new(CalendarComponent, 1);
676 if (!cc)
677 return -ENOMEM;
678
679 *cc = (CalendarComponent) {
680 .start = start,
681 .stop = stop,
682 .repeat = repeat,
683 .next = *c,
684 };
685
686 *p = e;
687 *c = cc;
688
689 if (*e ==',') {
690 *p += 1;
691 return prepend_component(p, usec, nesting + 1, c);
692 }
693
694 return 0;
695 }
696
697 static int parse_chain(const char **p, bool usec, CalendarComponent **c) {
698 _cleanup_(chain_freep) CalendarComponent *cc = NULL;
699 const char *t;
700 int r;
701
702 assert(p);
703 assert(c);
704
705 t = *p;
706
707 if (t[0] == '*') {
708 if (usec) {
709 r = const_chain(0, c);
710 if (r < 0)
711 return r;
712 (*c)->repeat = USEC_PER_SEC;
713 } else
714 *c = NULL;
715
716 *p = t + 1;
717 return 0;
718 }
719
720 r = prepend_component(&t, usec, 0, &cc);
721 if (r < 0)
722 return r;
723
724 *p = t;
725 *c = TAKE_PTR(cc);
726 return 0;
727 }
728
729 static int parse_date(const char **p, CalendarSpec *c) {
730 _cleanup_(chain_freep) CalendarComponent *first = NULL, *second = NULL, *third = NULL;
731 const char *t;
732 int r;
733
734 assert(p);
735 assert(*p);
736 assert(c);
737
738 t = *p;
739
740 if (*t == 0)
741 return 0;
742
743 /* @TIMESTAMP — UNIX time in seconds since the epoch */
744 if (*t == '@') {
745 unsigned long value;
746 time_t time;
747
748 r = parse_one_number(t + 1, &t, &value);
749 if (r < 0)
750 return r;
751
752 time = value;
753 if ((unsigned long) time != value)
754 return -ERANGE;
755
756 r = calendarspec_from_time_t(c, time);
757 if (r < 0)
758 return r;
759
760 *p = t;
761 return 1; /* finito, don't parse H:M:S after that */
762 }
763
764 r = parse_chain(&t, false, &first);
765 if (r < 0)
766 return r;
767
768 /* Already the end? A ':' as separator? In that case this was a time, not a date */
769 if (IN_SET(*t, 0, ':'))
770 return 0;
771
772 if (*t == '~')
773 c->end_of_month = true;
774 else if (*t != '-')
775 return -EINVAL;
776
777 t++;
778 r = parse_chain(&t, false, &second);
779 if (r < 0)
780 return r;
781
782 /* Got two parts, hence it's month and day */
783 if (IN_SET(*t, 0, ' ')) {
784 *p = t + strspn(t, " ");
785 c->month = TAKE_PTR(first);
786 c->day = TAKE_PTR(second);
787 return 0;
788 } else if (c->end_of_month)
789 return -EINVAL;
790
791 if (*t == '~')
792 c->end_of_month = true;
793 else if (*t != '-')
794 return -EINVAL;
795
796 t++;
797 r = parse_chain(&t, false, &third);
798 if (r < 0)
799 return r;
800
801 if (!IN_SET(*t, 0, ' '))
802 return -EINVAL;
803
804 /* Got three parts, hence it is year, month and day */
805 *p = t + strspn(t, " ");
806 c->year = TAKE_PTR(first);
807 c->month = TAKE_PTR(second);
808 c->day = TAKE_PTR(third);
809 return 0;
810 }
811
812 static int parse_calendar_time(const char **p, CalendarSpec *c) {
813 _cleanup_(chain_freep) CalendarComponent *h = NULL, *m = NULL, *s = NULL;
814 const char *t;
815 int r;
816
817 assert(p);
818 assert(*p);
819 assert(c);
820
821 t = *p;
822
823 /* If no time is specified at all, then this means 00:00:00 */
824 if (*t == 0)
825 goto null_hour;
826
827 r = parse_chain(&t, false, &h);
828 if (r < 0)
829 return r;
830
831 if (*t != ':')
832 return -EINVAL;
833
834 t++;
835 r = parse_chain(&t, false, &m);
836 if (r < 0)
837 return r;
838
839 /* Already at the end? Then it's hours and minutes, and seconds are 0 */
840 if (*t == 0)
841 goto null_second;
842
843 if (*t != ':')
844 return -EINVAL;
845
846 t++;
847 r = parse_chain(&t, true, &s);
848 if (r < 0)
849 return r;
850
851 /* At the end? Then it's hours, minutes and seconds */
852 if (*t == 0)
853 goto finish;
854
855 return -EINVAL;
856
857 null_hour:
858 r = const_chain(0, &h);
859 if (r < 0)
860 return r;
861
862 r = const_chain(0, &m);
863 if (r < 0)
864 return r;
865
866 null_second:
867 r = const_chain(0, &s);
868 if (r < 0)
869 return r;
870
871 finish:
872 *p = t;
873 c->hour = TAKE_PTR(h);
874 c->minute = TAKE_PTR(m);
875 c->microsecond = TAKE_PTR(s);
876
877 return 0;
878 }
879
880 int calendar_spec_from_string(const char *p, CalendarSpec **ret) {
881 const char *utc;
882 _cleanup_(calendar_spec_freep) CalendarSpec *c = NULL;
883 _cleanup_free_ char *p_tmp = NULL;
884 int r;
885
886 assert(p);
887
888 c = new(CalendarSpec, 1);
889 if (!c)
890 return -ENOMEM;
891
892 *c = (CalendarSpec) {
893 .dst = -1,
894 .timezone = NULL,
895 };
896
897 utc = endswith_no_case(p, " UTC");
898 if (utc) {
899 c->utc = true;
900 p = p_tmp = strndup(p, utc - p);
901 if (!p)
902 return -ENOMEM;
903 } else {
904 const char *e = NULL;
905 int j;
906
907 tzset();
908
909 /* Check if the local timezone was specified? */
910 for (j = 0; j <= 1; j++) {
911 const char *z = get_tzname(j);
912 if (!z)
913 continue;
914
915 e = endswith_no_case(p, z);
916 if (!e)
917 continue;
918 if (e == p)
919 continue;
920 if (e[-1] != ' ')
921 continue;
922
923 break;
924 }
925
926 /* Found one of the two timezones specified? */
927 if (IN_SET(j, 0, 1)) {
928 p = p_tmp = strndup(p, e - p - 1);
929 if (!p)
930 return -ENOMEM;
931
932 c->dst = j;
933 } else {
934 const char *last_space;
935
936 last_space = strrchr(p, ' ');
937 if (last_space != NULL && timezone_is_valid(last_space + 1, LOG_DEBUG)) {
938 c->timezone = strdup(last_space + 1);
939 if (!c->timezone)
940 return -ENOMEM;
941
942 p = p_tmp = strndup(p, last_space - p);
943 if (!p)
944 return -ENOMEM;
945 }
946 }
947 }
948
949 if (isempty(p))
950 return -EINVAL;
951
952 if (strcaseeq(p, "minutely")) {
953 r = const_chain(0, &c->microsecond);
954 if (r < 0)
955 return r;
956
957 } else if (strcaseeq(p, "hourly")) {
958 r = const_chain(0, &c->minute);
959 if (r < 0)
960 return r;
961 r = const_chain(0, &c->microsecond);
962 if (r < 0)
963 return r;
964
965 } else if (strcaseeq(p, "daily")) {
966 r = const_chain(0, &c->hour);
967 if (r < 0)
968 return r;
969 r = const_chain(0, &c->minute);
970 if (r < 0)
971 return r;
972 r = const_chain(0, &c->microsecond);
973 if (r < 0)
974 return r;
975
976 } else if (strcaseeq(p, "monthly")) {
977 r = const_chain(1, &c->day);
978 if (r < 0)
979 return r;
980 r = const_chain(0, &c->hour);
981 if (r < 0)
982 return r;
983 r = const_chain(0, &c->minute);
984 if (r < 0)
985 return r;
986 r = const_chain(0, &c->microsecond);
987 if (r < 0)
988 return r;
989
990 } else if (STRCASE_IN_SET(p,
991 "annually",
992 "yearly",
993 "anually") /* backwards compatibility */ ) {
994
995 r = const_chain(1, &c->month);
996 if (r < 0)
997 return r;
998 r = const_chain(1, &c->day);
999 if (r < 0)
1000 return r;
1001 r = const_chain(0, &c->hour);
1002 if (r < 0)
1003 return r;
1004 r = const_chain(0, &c->minute);
1005 if (r < 0)
1006 return r;
1007 r = const_chain(0, &c->microsecond);
1008 if (r < 0)
1009 return r;
1010
1011 } else if (strcaseeq(p, "weekly")) {
1012
1013 c->weekdays_bits = 1;
1014
1015 r = const_chain(0, &c->hour);
1016 if (r < 0)
1017 return r;
1018 r = const_chain(0, &c->minute);
1019 if (r < 0)
1020 return r;
1021 r = const_chain(0, &c->microsecond);
1022 if (r < 0)
1023 return r;
1024
1025 } else if (strcaseeq(p, "quarterly")) {
1026
1027 r = const_chain(1, &c->month);
1028 if (r < 0)
1029 return r;
1030 r = const_chain(4, &c->month);
1031 if (r < 0)
1032 return r;
1033 r = const_chain(7, &c->month);
1034 if (r < 0)
1035 return r;
1036 r = const_chain(10, &c->month);
1037 if (r < 0)
1038 return r;
1039 r = const_chain(1, &c->day);
1040 if (r < 0)
1041 return r;
1042 r = const_chain(0, &c->hour);
1043 if (r < 0)
1044 return r;
1045 r = const_chain(0, &c->minute);
1046 if (r < 0)
1047 return r;
1048 r = const_chain(0, &c->microsecond);
1049 if (r < 0)
1050 return r;
1051
1052 } else if (STRCASE_IN_SET(p,
1053 "biannually",
1054 "bi-annually",
1055 "semiannually",
1056 "semi-annually")) {
1057
1058 r = const_chain(1, &c->month);
1059 if (r < 0)
1060 return r;
1061 r = const_chain(7, &c->month);
1062 if (r < 0)
1063 return r;
1064 r = const_chain(1, &c->day);
1065 if (r < 0)
1066 return r;
1067 r = const_chain(0, &c->hour);
1068 if (r < 0)
1069 return r;
1070 r = const_chain(0, &c->minute);
1071 if (r < 0)
1072 return r;
1073 r = const_chain(0, &c->microsecond);
1074 if (r < 0)
1075 return r;
1076
1077 } else {
1078 r = parse_weekdays(&p, c);
1079 if (r < 0)
1080 return r;
1081
1082 r = parse_date(&p, c);
1083 if (r < 0)
1084 return r;
1085
1086 if (r == 0) {
1087 r = parse_calendar_time(&p, c);
1088 if (r < 0)
1089 return r;
1090 }
1091
1092 if (*p != 0)
1093 return -EINVAL;
1094 }
1095
1096 calendar_spec_normalize(c);
1097
1098 if (!calendar_spec_valid(c))
1099 return -EINVAL;
1100
1101 if (ret)
1102 *ret = TAKE_PTR(c);
1103 return 0;
1104 }
1105
1106 static int find_end_of_month(const struct tm *tm, bool utc, int day) {
1107 struct tm t = *ASSERT_PTR(tm);
1108
1109 t.tm_mon++;
1110 t.tm_mday = 1 - day;
1111
1112 if (mktime_or_timegm_usec(&t, utc, /* ret= */ NULL) < 0 ||
1113 t.tm_mon != tm->tm_mon)
1114 return -1;
1115
1116 return t.tm_mday;
1117 }
1118
1119 static int find_matching_component(
1120 const CalendarSpec *spec,
1121 const CalendarComponent *c,
1122 const struct tm *tm, /* tm is only used for end-of-month calculations */
1123 int *val) {
1124
1125 int d = -1, r;
1126 bool d_set = false;
1127
1128 assert(val);
1129
1130 /* Finds the *earliest* matching time specified by one of the CalendarComponent items in chain c.
1131 * If no matches can be found, returns -ENOENT.
1132 * Otherwise, updates *val to the matching time. 1 is returned if *val was changed, 0 otherwise.
1133 */
1134
1135 if (!c)
1136 return 0;
1137
1138 bool end_of_month = spec->end_of_month && c == spec->day;
1139
1140 while (c) {
1141 int start, stop;
1142
1143 if (end_of_month) {
1144 start = find_end_of_month(tm, spec->utc, c->start);
1145 stop = find_end_of_month(tm, spec->utc, c->stop);
1146
1147 if (stop > 0)
1148 SWAP_TWO(start, stop);
1149 } else {
1150 start = c->start;
1151 stop = c->stop;
1152 }
1153
1154 if (start >= *val) {
1155
1156 if (!d_set || start < d) {
1157 d = start;
1158 d_set = true;
1159 }
1160
1161 } else if (c->repeat > 0) {
1162 int k;
1163
1164 if (ADD_SAFE(&k, start, ROUND_UP(*val - start, c->repeat)) &&
1165 (!d_set || k < d) && (stop < 0 || k <= stop)) {
1166 d = k;
1167 d_set = true;
1168 }
1169 }
1170
1171 c = c->next;
1172 }
1173
1174 if (!d_set)
1175 return -ENOENT;
1176
1177 r = *val != d;
1178 *val = d;
1179 return r;
1180 }
1181
1182 static int tm_within_bounds(struct tm *tm, bool utc) {
1183 int r;
1184
1185 assert(tm);
1186
1187 /*
1188 * Set an upper bound on the year so impossible dates like "*-02-31"
1189 * don't cause find_next() to loop forever. tm_year contains years
1190 * since 1900, so adjust it accordingly.
1191 */
1192 if (tm->tm_year + 1900 > MAX_YEAR)
1193 return -ERANGE;
1194
1195 struct tm t = *tm;
1196 r = mktime_or_timegm_usec(&t, utc, /* ret= */ NULL);
1197 if (r < 0)
1198 return r;
1199
1200 /*
1201 * Did any normalization take place? If so, it was out of bounds before.
1202 * Normalization could skip next elapse, e.g. result of normalizing 3-33
1203 * is 4-2. This skips 4-1. So reset the sub time unit if upper unit was
1204 * out of bounds. Normalization has occurred implies find_matching_component() > 0,
1205 * other sub time units are already reset in find_next().
1206 */
1207 int cmp;
1208 if ((cmp = CMP(t.tm_year, tm->tm_year)) != 0) {
1209 t.tm_mon = 0;
1210 t.tm_mday = 1;
1211 } else if ((cmp = CMP(t.tm_mon, tm->tm_mon)) != 0)
1212 t.tm_mday = 1;
1213 else if ((cmp = CMP(t.tm_mday, tm->tm_mday)) != 0)
1214 t.tm_hour = 0;
1215 else if ((cmp = CMP(t.tm_hour, tm->tm_hour)) != 0)
1216 t.tm_min = 0;
1217 else if ((cmp = CMP(t.tm_min, tm->tm_min)) != 0)
1218 t.tm_sec = 0;
1219 else
1220 cmp = CMP(t.tm_sec, tm->tm_sec);
1221
1222 if (cmp < 0)
1223 return -EDEADLK; /* Refuse to go backward */
1224 if (cmp > 0)
1225 *tm = t;
1226 return cmp == 0;
1227 }
1228
1229 static bool matches_weekday(int weekdays_bits, const struct tm *tm, bool utc) {
1230 struct tm t;
1231 int k;
1232
1233 assert(tm);
1234
1235 if (weekdays_bits < 0 || weekdays_bits >= BITS_WEEKDAYS)
1236 return true;
1237
1238 t = *tm;
1239 if (mktime_or_timegm_usec(&t, utc, /* ret= */ NULL) < 0)
1240 return false;
1241
1242 k = t.tm_wday == 0 ? 6 : t.tm_wday - 1;
1243 return (weekdays_bits & (1 << k));
1244 }
1245
1246 static int tm_compare(const struct tm *t1, const struct tm *t2) {
1247 int r;
1248
1249 assert(t1);
1250 assert(t2);
1251
1252 r = CMP(t1->tm_year, t2->tm_year);
1253 if (r != 0)
1254 return r;
1255
1256 r = CMP(t1->tm_mon, t2->tm_mon);
1257 if (r != 0)
1258 return r;
1259
1260 r = CMP(t1->tm_mday, t2->tm_mday);
1261 if (r != 0)
1262 return r;
1263
1264 r = CMP(t1->tm_hour, t2->tm_hour);
1265 if (r != 0)
1266 return r;
1267
1268 r = CMP(t1->tm_min, t2->tm_min);
1269 if (r != 0)
1270 return r;
1271
1272 return CMP(t1->tm_sec, t2->tm_sec);
1273 }
1274
1275 /* A safety valve: if we get stuck in the calculation, return an error.
1276 * C.f. https://bugzilla.redhat.com/show_bug.cgi?id=1941335. */
1277 #define MAX_CALENDAR_ITERATIONS 1000
1278
1279 static int find_next(const CalendarSpec *spec, struct tm *tm, usec_t *usec) {
1280 struct tm c;
1281 int tm_usec, r;
1282 bool invalidate_dst = false;
1283
1284 /* Returns -ENOENT if the expression is not going to elapse anymore */
1285
1286 assert(spec);
1287 assert(tm);
1288 assert(usec);
1289
1290 c = *tm;
1291 tm_usec = *usec;
1292
1293 for (unsigned iteration = 0; iteration < MAX_CALENDAR_ITERATIONS; iteration++) {
1294 /* Normalize the current date */
1295 (void) mktime_or_timegm_usec(&c, spec->utc, /* ret= */ NULL);
1296 if (!invalidate_dst)
1297 c.tm_isdst = spec->dst;
1298
1299 c.tm_year += 1900;
1300 r = find_matching_component(spec, spec->year, &c, &c.tm_year);
1301 c.tm_year -= 1900;
1302
1303 if (r > 0) {
1304 c.tm_mon = 0;
1305 c.tm_mday = 1;
1306 c.tm_hour = c.tm_min = c.tm_sec = tm_usec = 0;
1307 }
1308 if (r < 0)
1309 return r;
1310 if (tm_within_bounds(&c, spec->utc) <= 0)
1311 return -ENOENT;
1312
1313 c.tm_mon += 1;
1314 r = find_matching_component(spec, spec->month, &c, &c.tm_mon);
1315 c.tm_mon -= 1;
1316
1317 if (r > 0) {
1318 c.tm_mday = 1;
1319 c.tm_hour = c.tm_min = c.tm_sec = tm_usec = 0;
1320 }
1321 if (r < 0 || (r = tm_within_bounds(&c, spec->utc)) < 0) {
1322 c.tm_year++;
1323 c.tm_mon = 0;
1324 c.tm_mday = 1;
1325 c.tm_hour = c.tm_min = c.tm_sec = tm_usec = 0;
1326 continue;
1327 }
1328 if (r == 0)
1329 continue;
1330
1331 r = find_matching_component(spec, spec->day, &c, &c.tm_mday);
1332 if (r > 0)
1333 c.tm_hour = c.tm_min = c.tm_sec = tm_usec = 0;
1334 if (r < 0 || (r = tm_within_bounds(&c, spec->utc)) < 0) {
1335 c.tm_mon++;
1336 c.tm_mday = 1;
1337 c.tm_hour = c.tm_min = c.tm_sec = tm_usec = 0;
1338 continue;
1339 }
1340 if (r == 0)
1341 continue;
1342
1343 if (!matches_weekday(spec->weekdays_bits, &c, spec->utc)) {
1344 c.tm_mday++;
1345 c.tm_hour = c.tm_min = c.tm_sec = tm_usec = 0;
1346 continue;
1347 }
1348
1349 r = find_matching_component(spec, spec->hour, &c, &c.tm_hour);
1350 if (r > 0)
1351 c.tm_min = c.tm_sec = tm_usec = 0;
1352 if (r < 0 || (r = tm_within_bounds(&c, spec->utc)) < 0) {
1353 c.tm_mday++;
1354 c.tm_hour = c.tm_min = c.tm_sec = tm_usec = 0;
1355 continue;
1356 }
1357 if (r == 0)
1358 /* The next hour we set might be missing if there
1359 * are time zone changes. Let's try again starting at
1360 * normalized time. */
1361 continue;
1362
1363 r = find_matching_component(spec, spec->minute, &c, &c.tm_min);
1364 if (r > 0)
1365 c.tm_sec = tm_usec = 0;
1366 if (r < 0 || (r = tm_within_bounds(&c, spec->utc)) < 0) {
1367 c.tm_hour++;
1368 c.tm_min = c.tm_sec = tm_usec = 0;
1369 continue;
1370 }
1371 if (r == 0)
1372 continue;
1373
1374 c.tm_sec = c.tm_sec * USEC_PER_SEC + tm_usec;
1375 r = find_matching_component(spec, spec->microsecond, &c, &c.tm_sec);
1376 tm_usec = c.tm_sec % USEC_PER_SEC;
1377 c.tm_sec /= USEC_PER_SEC;
1378
1379 if (r < 0 || (r = tm_within_bounds(&c, spec->utc)) < 0) {
1380 c.tm_min++;
1381 c.tm_sec = tm_usec = 0;
1382 continue;
1383 }
1384 if (r == 0)
1385 continue;
1386
1387 r = tm_compare(tm, &c);
1388 if (r == 0) {
1389 assert(tm_usec + 1 <= 1000000);
1390 r = CMP(*usec, (usec_t) tm_usec + 1);
1391 }
1392 if (r >= 0) {
1393 /* We're stuck - advance, let mktime determine DST transition and try again. */
1394 invalidate_dst = true;
1395 c.tm_hour++;
1396 continue;
1397 }
1398
1399 *tm = c;
1400 *usec = tm_usec;
1401 return 0;
1402 }
1403
1404 /* It seems we entered an infinite loop. Let's gracefully return an error instead of hanging or
1405 * aborting. This code is also exercised when timers.target is brought up during early boot, so
1406 * aborting here is problematic and hard to diagnose for users. */
1407 _cleanup_free_ char *s = NULL;
1408 (void) calendar_spec_to_string(spec, &s);
1409 return log_warning_errno(SYNTHETIC_ERRNO(EDEADLK),
1410 "Infinite loop in calendar calculation: %s", strna(s));
1411 }
1412
1413 static int calendar_spec_next_usec_impl(const CalendarSpec *spec, usec_t usec, usec_t *ret_next) {
1414 usec_t tm_usec;
1415 struct tm tm;
1416 int r;
1417
1418 assert(spec);
1419
1420 if (usec > USEC_TIMESTAMP_FORMATTABLE_MAX)
1421 return -EINVAL;
1422
1423 usec++;
1424 r = localtime_or_gmtime_usec(usec, spec->utc, &tm);
1425 if (r < 0)
1426 return r;
1427 tm_usec = usec % USEC_PER_SEC;
1428
1429 r = find_next(spec, &tm, &tm_usec);
1430 if (r < 0)
1431 return r;
1432
1433 usec_t t;
1434 r = mktime_or_timegm_usec(&tm, spec->utc, &t);
1435 if (r < 0)
1436 return r;
1437
1438 if (ret_next)
1439 *ret_next = t + tm_usec;
1440
1441 return 0;
1442 }
1443
1444 int calendar_spec_next_usec(const CalendarSpec *spec, usec_t usec, usec_t *ret_next) {
1445 int r;
1446
1447 assert(spec);
1448
1449 if (isempty(spec->timezone))
1450 return calendar_spec_next_usec_impl(spec, usec, ret_next);
1451
1452 SAVE_TIMEZONE;
1453
1454 r = RET_NERRNO(setenv("TZ", spec->timezone, /* overwrite= */ true));
1455 if (r < 0)
1456 return r;
1457
1458 tzset();
1459
1460 return calendar_spec_next_usec_impl(spec, usec, ret_next);
1461 }