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