1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2012 Lennart Poettering
14 #include <stdio_ext.h>
20 #include "alloc-util.h"
21 #include "calendarspec.h"
24 #include "parse-util.h"
25 #include "process-util.h"
26 #include "string-util.h"
27 #include "time-util.h"
29 #define BITS_WEEKDAYS 127
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
39 static void free_chain(CalendarComponent
*c
) {
49 CalendarSpec
* calendar_spec_free(CalendarSpec
*c
) {
58 free_chain(c
->minute
);
59 free_chain(c
->microsecond
);
65 static int component_compare(const void *_a
, const void *_b
) {
66 CalendarComponent
* const *a
= _a
, * const *b
= _b
;
68 if ((*a
)->start
< (*b
)->start
)
70 if ((*a
)->start
> (*b
)->start
)
73 if ((*a
)->stop
< (*b
)->stop
)
75 if ((*a
)->stop
> (*b
)->stop
)
78 if ((*a
)->repeat
< (*b
)->repeat
)
80 if ((*a
)->repeat
> (*b
)->repeat
)
86 static void normalize_chain(CalendarComponent
**c
) {
87 CalendarComponent
**b
, *i
, **j
, *next
;
92 for (i
= *c
; i
; i
= i
->next
) {
96 * While we're counting the chain, also normalize `stop`
97 * so the length of the range is a multiple of `repeat`
99 if (i
->stop
> i
->start
&& i
->repeat
> 0)
100 i
->stop
-= (i
->stop
- i
->start
) % i
->repeat
;
107 j
= b
= newa(CalendarComponent
*, n
);
108 for (i
= *c
; i
; i
= i
->next
)
111 qsort(b
, n
, sizeof(CalendarComponent
*), component_compare
);
116 /* Drop non-unique entries */
117 for (k
= n
-1; k
> 0; k
--) {
118 if (component_compare(&b
[k
-1], &next
) == 0) {
130 static void fix_year(CalendarComponent
*c
) {
131 /* Turns 12 → 2012, 89 → 1989 */
134 if (c
->start
>= 0 && c
->start
< 70)
137 if (c
->stop
>= 0 && c
->stop
< 70)
140 if (c
->start
>= 70 && c
->start
< 100)
143 if (c
->stop
>= 70 && c
->stop
< 100)
150 int calendar_spec_normalize(CalendarSpec
*c
) {
153 if (streq_ptr(c
->timezone
, "UTC")) {
155 c
->timezone
= mfree(c
->timezone
);
158 if (c
->weekdays_bits
<= 0 || c
->weekdays_bits
>= BITS_WEEKDAYS
)
159 c
->weekdays_bits
= -1;
161 if (c
->end_of_month
&& !c
->day
)
162 c
->end_of_month
= false;
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
);
176 _pure_
static bool chain_valid(CalendarComponent
*c
, int from
, int to
, bool end_of_month
) {
182 /* Forbid dates more than 28 days from the end of the month */
186 if (c
->start
< from
|| c
->start
> to
)
189 /* Avoid overly large values that could cause overflow */
190 if (c
->repeat
> to
- from
)
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.
200 if (c
->stop
< from
|| c
->stop
> to
)
203 if (c
->start
+ c
->repeat
> c
->stop
)
206 if (end_of_month
&& c
->start
- c
->repeat
< from
)
209 if (!end_of_month
&& c
->start
+ c
->repeat
> to
)
214 return chain_valid(c
->next
, from
, to
, end_of_month
);
219 _pure_
bool calendar_spec_valid(CalendarSpec
*c
) {
222 if (c
->weekdays_bits
> BITS_WEEKDAYS
)
225 if (!chain_valid(c
->year
, MIN_YEAR
, MAX_YEAR
, false))
228 if (!chain_valid(c
->month
, 1, 12, false))
231 if (!chain_valid(c
->day
, 1, 31, c
->end_of_month
))
234 if (!chain_valid(c
->hour
, 0, 23, false))
237 if (!chain_valid(c
->minute
, 0, 59, false))
240 if (!chain_valid(c
->microsecond
, 0, 60*USEC_PER_SEC
-1, false))
246 static void format_weekdays(FILE *f
, const CalendarSpec
*c
) {
247 static const char *const days
[] = {
258 bool need_comma
= false;
262 assert(c
->weekdays_bits
> 0 && c
->weekdays_bits
<= BITS_WEEKDAYS
);
264 for (x
= 0, l
= -1; x
< (int) ELEMENTSOF(days
); x
++) {
266 if (c
->weekdays_bits
& (1 << x
)) {
281 fputs(x
> l
+ 2 ? ".." : ",", f
);
289 if (l
>= 0 && x
> l
+ 1) {
290 fputs(x
> l
+ 2 ? ".." : ",", f
);
295 static void format_chain(FILE *f
, int space
, const CalendarComponent
*c
, bool usec
) {
296 int d
= usec
? (int) USEC_PER_SEC
: 1;
305 if (usec
&& c
->start
== 0 && c
->repeat
== USEC_PER_SEC
&& !c
->next
) {
310 assert(c
->start
>= 0);
312 fprintf(f
, "%0*i", space
, c
->start
/ d
);
313 if (c
->start
% d
> 0)
314 fprintf(f
, ".%06i", c
->start
% d
);
317 fprintf(f
, "..%0*i", space
, c
->stop
/ d
);
319 fprintf(f
, ".%06i", c
->stop
% d
);
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
);
328 format_chain(f
, space
, c
->next
, usec
);
332 int calendar_spec_to_string(const CalendarSpec
*c
, char **p
) {
341 f
= open_memstream(&buf
, &sz
);
345 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
347 if (c
->weekdays_bits
> 0 && c
->weekdays_bits
<= BITS_WEEKDAYS
) {
348 format_weekdays(f
, c
);
352 format_chain(f
, 4, c
->year
, false);
354 format_chain(f
, 2, c
->month
, false);
355 fputc(c
->end_of_month
? '~' : '-', f
);
356 format_chain(f
, 2, c
->day
, false);
358 format_chain(f
, 2, c
->hour
, false);
360 format_chain(f
, 2, c
->minute
, false);
362 format_chain(f
, 2, c
->microsecond
, true);
366 else if (c
->timezone
!= NULL
) {
368 fputs(c
->timezone
, f
);
369 } else if (IN_SET(c
->dst
, 0, 1)) {
371 /* If daylight saving is explicitly on or off, let's show the used timezone. */
375 if (!isempty(tzname
[c
->dst
])) {
377 fputs(tzname
[c
->dst
], f
);
381 r
= fflush_and_check(f
);
394 static int parse_weekdays(const char **p
, CalendarSpec
*c
) {
395 static const struct {
425 for (i
= 0; i
< ELEMENTSOF(day_nr
); i
++) {
428 if (!startswith_no_case(*p
, day_nr
[i
].name
))
431 skip
= strlen(day_nr
[i
].name
);
433 if (!IN_SET((*p
)[skip
], 0, '-', '.', ',', ' '))
436 c
->weekdays_bits
|= 1 << day_nr
[i
].nr
;
441 if (l
> day_nr
[i
].nr
)
444 for (j
= l
+ 1; j
< day_nr
[i
].nr
; j
++)
445 c
->weekdays_bits
|= 1 << j
;
452 /* Couldn't find this prefix, so let's assume the
453 weekday was not specified and let's continue with
455 if (i
>= ELEMENTSOF(day_nr
))
456 return first
? 0 : -EINVAL
;
458 /* We reached the end of the string */
462 /* We reached the end of the weekday spec part */
464 *p
+= strspn(*p
, " ");
478 /* Support ranges with "-" for backwards compatibility */
479 } else if (**p
== '-') {
486 } else if (**p
== ',') {
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
;
501 static int parse_one_number(const char *p
, const char **e
, unsigned long *ret
) {
506 value
= strtoul(p
, &ee
, 10);
517 static int parse_component_decimal(const char **p
, bool usec
, int *res
) {
519 const char *e
= NULL
;
525 r
= parse_one_number(*p
, &e
, &value
);
530 if (value
* USEC_PER_SEC
/ USEC_PER_SEC
!= value
)
533 value
*= USEC_PER_SEC
;
535 /* One "." is a decimal point, but ".." is a range separator */
536 if (e
[0] == '.' && e
[1] != '.') {
540 r
= parse_fractional_part_u(&e
, 6, &add
);
544 if (add
+ value
< value
)
559 static int const_chain(int value
, CalendarComponent
**c
) {
560 CalendarComponent
*cc
= NULL
;
564 cc
= new0(CalendarComponent
, 1);
578 static int calendarspec_from_time_t(CalendarSpec
*c
, time_t time
) {
580 CalendarComponent
*year
= NULL
, *month
= NULL
, *day
= NULL
, *hour
= NULL
, *minute
= NULL
, *us
= NULL
;
583 if (!gmtime_r(&time
, &tm
))
586 r
= const_chain(tm
.tm_year
+ 1900, &year
);
590 r
= const_chain(tm
.tm_mon
+ 1, &month
);
594 r
= const_chain(tm
.tm_mday
, &day
);
598 r
= const_chain(tm
.tm_hour
, &hour
);
602 r
= const_chain(tm
.tm_min
, &minute
);
606 r
= const_chain(tm
.tm_sec
* USEC_PER_SEC
, &us
);
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
;
628 if (nesting
> CALENDARSPEC_COMPONENTS_MAX
)
631 r
= parse_component_decimal(&e
, usec
, &start
);
635 if (e
[0] == '.' && e
[1] == '.') {
637 r
= parse_component_decimal(&e
, usec
, &stop
);
641 repeat
= usec
? USEC_PER_SEC
: 1;
646 r
= parse_component_decimal(&e
, usec
, &repeat
);
654 if (!IN_SET(*e
, 0, ' ', ',', '-', '~', ':'))
657 cc
= new0(CalendarComponent
, 1);
671 return prepend_component(p
, usec
, nesting
+ 1, c
);
677 static int parse_chain(const char **p
, bool usec
, CalendarComponent
**c
) {
679 CalendarComponent
*cc
= NULL
;
689 r
= const_chain(0, c
);
692 (*c
)->repeat
= USEC_PER_SEC
;
700 r
= prepend_component(&t
, usec
, 0, &cc
);
711 static int parse_date(const char **p
, CalendarSpec
*c
) {
714 CalendarComponent
*first
, *second
, *third
;
725 /* @TIMESTAMP — UNIX time in seconds since the epoch */
730 r
= parse_one_number(t
+ 1, &t
, &value
);
735 if ((unsigned long) time
!= value
)
738 r
= calendarspec_from_time_t(c
, time
);
743 return 1; /* finito, don't parse H:M:S after that */
746 r
= parse_chain(&t
, false, &first
);
750 /* Already the end? A ':' as separator? In that case this was a time, not a date */
751 if (IN_SET(*t
, 0, ':')) {
757 c
->end_of_month
= true;
758 else if (*t
!= '-') {
764 r
= parse_chain(&t
, false, &second
);
770 /* Got two parts, hence it's month and day */
771 if (IN_SET(*t
, 0, ' ')) {
772 *p
= t
+ strspn(t
, " ");
776 } else if (c
->end_of_month
) {
783 c
->end_of_month
= true;
784 else if (*t
!= '-') {
791 r
= parse_chain(&t
, false, &third
);
798 /* Got three parts, hence it is year, month and day */
799 if (IN_SET(*t
, 0, ' ')) {
800 *p
= t
+ strspn(t
, " ");
813 static int parse_calendar_time(const char **p
, CalendarSpec
*c
) {
814 CalendarComponent
*h
= NULL
, *m
= NULL
, *s
= NULL
;
824 /* If no time is specified at all, then this means 00:00:00 */
828 r
= parse_chain(&t
, false, &h
);
838 r
= parse_chain(&t
, false, &m
);
842 /* Already at the end? Then it's hours and minutes, and seconds are 0 */
852 r
= parse_chain(&t
, true, &s
);
856 /* At the end? Then it's hours, minutes and seconds */
864 r
= const_chain(0, &h
);
868 r
= const_chain(0, &m
);
873 r
= const_chain(0, &s
);
892 int calendar_spec_from_string(const char *p
, CalendarSpec
**spec
) {
894 _cleanup_(calendar_spec_freep
) CalendarSpec
*c
= NULL
;
900 c
= new0(CalendarSpec
, 1);
906 utc
= endswith_no_case(p
, " UTC");
909 p
= strndupa(p
, utc
- p
);
911 const char *e
= NULL
;
916 /* Check if the local timezone was specified? */
917 for (j
= 0; j
<= 1; j
++) {
918 if (isempty(tzname
[j
]))
921 e
= endswith_no_case(p
, tzname
[j
]);
932 /* Found one of the two timezones specified? */
933 if (IN_SET(j
, 0, 1)) {
934 p
= strndupa(p
, e
- p
- 1);
937 const char *last_space
;
939 last_space
= strrchr(p
, ' ');
940 if (last_space
!= NULL
&& timezone_is_valid(last_space
+ 1, LOG_DEBUG
)) {
941 c
->timezone
= strdup(last_space
+ 1);
945 p
= strndupa(p
, last_space
- p
);
953 if (strcaseeq(p
, "minutely")) {
954 r
= const_chain(0, &c
->microsecond
);
958 } else if (strcaseeq(p
, "hourly")) {
959 r
= const_chain(0, &c
->minute
);
962 r
= const_chain(0, &c
->microsecond
);
966 } else if (strcaseeq(p
, "daily")) {
967 r
= const_chain(0, &c
->hour
);
970 r
= const_chain(0, &c
->minute
);
973 r
= const_chain(0, &c
->microsecond
);
977 } else if (strcaseeq(p
, "monthly")) {
978 r
= const_chain(1, &c
->day
);
981 r
= const_chain(0, &c
->hour
);
984 r
= const_chain(0, &c
->minute
);
987 r
= const_chain(0, &c
->microsecond
);
991 } else if (strcaseeq(p
, "annually") ||
992 strcaseeq(p
, "yearly") ||
993 strcaseeq(p
, "anually") /* backwards compatibility */ ) {
995 r
= const_chain(1, &c
->month
);
998 r
= const_chain(1, &c
->day
);
1001 r
= const_chain(0, &c
->hour
);
1004 r
= const_chain(0, &c
->minute
);
1007 r
= const_chain(0, &c
->microsecond
);
1011 } else if (strcaseeq(p
, "weekly")) {
1013 c
->weekdays_bits
= 1;
1015 r
= const_chain(0, &c
->hour
);
1018 r
= const_chain(0, &c
->minute
);
1021 r
= const_chain(0, &c
->microsecond
);
1025 } else if (strcaseeq(p
, "quarterly")) {
1027 r
= const_chain(1, &c
->month
);
1030 r
= const_chain(4, &c
->month
);
1033 r
= const_chain(7, &c
->month
);
1036 r
= const_chain(10, &c
->month
);
1039 r
= const_chain(1, &c
->day
);
1042 r
= const_chain(0, &c
->hour
);
1045 r
= const_chain(0, &c
->minute
);
1048 r
= const_chain(0, &c
->microsecond
);
1052 } else if (strcaseeq(p
, "biannually") ||
1053 strcaseeq(p
, "bi-annually") ||
1054 strcaseeq(p
, "semiannually") ||
1055 strcaseeq(p
, "semi-annually")) {
1057 r
= const_chain(1, &c
->month
);
1060 r
= const_chain(7, &c
->month
);
1063 r
= const_chain(1, &c
->day
);
1066 r
= const_chain(0, &c
->hour
);
1069 r
= const_chain(0, &c
->minute
);
1072 r
= const_chain(0, &c
->microsecond
);
1077 r
= parse_weekdays(&p
, c
);
1081 r
= parse_date(&p
, c
);
1086 r
= parse_calendar_time(&p
, c
);
1095 r
= calendar_spec_normalize(c
);
1099 if (!calendar_spec_valid(c
))
1102 *spec
= TAKE_PTR(c
);
1106 static int find_end_of_month(struct tm
*tm
, bool utc
, int day
) {
1110 t
.tm_mday
= 1 - day
;
1112 if (mktime_or_timegm(&t
, utc
) < 0 ||
1113 t
.tm_mon
!= tm
->tm_mon
)
1119 static int find_matching_component(const CalendarSpec
*spec
, const CalendarComponent
*c
,
1120 struct tm
*tm
, int *val
) {
1121 const CalendarComponent
*p
= c
;
1122 int start
, stop
, d
= -1;
1135 if (spec
->end_of_month
&& p
== spec
->day
) {
1136 start
= find_end_of_month(tm
, spec
->utc
, start
);
1137 stop
= find_end_of_month(tm
, spec
->utc
, stop
);
1140 SWAP_TWO(start
, stop
);
1143 if (start
>= *val
) {
1145 if (!d_set
|| start
< d
) {
1150 } else if (c
->repeat
> 0) {
1153 k
= start
+ c
->repeat
* DIV_ROUND_UP(*val
- start
, c
->repeat
);
1155 if ((!d_set
|| k
< d
) && (stop
< 0 || k
<= stop
)) {
1172 static bool tm_out_of_bounds(const struct tm
*tm
, bool utc
) {
1178 if (mktime_or_timegm(&t
, utc
) < 0)
1182 * Set an upper bound on the year so impossible dates like "*-02-31"
1183 * don't cause find_next() to loop forever. tm_year contains years
1184 * since 1900, so adjust it accordingly.
1186 if (tm
->tm_year
+ 1900 > MAX_YEAR
)
1189 /* Did any normalization take place? If so, it was out of bounds before */
1191 t
.tm_year
!= tm
->tm_year
||
1192 t
.tm_mon
!= tm
->tm_mon
||
1193 t
.tm_mday
!= tm
->tm_mday
||
1194 t
.tm_hour
!= tm
->tm_hour
||
1195 t
.tm_min
!= tm
->tm_min
||
1196 t
.tm_sec
!= tm
->tm_sec
;
1199 static bool matches_weekday(int weekdays_bits
, const struct tm
*tm
, bool utc
) {
1203 if (weekdays_bits
< 0 || weekdays_bits
>= BITS_WEEKDAYS
)
1207 if (mktime_or_timegm(&t
, utc
) < 0)
1210 k
= t
.tm_wday
== 0 ? 6 : t
.tm_wday
- 1;
1211 return (weekdays_bits
& (1 << k
));
1214 static int find_next(const CalendarSpec
*spec
, struct tm
*tm
, usec_t
*usec
) {
1226 /* Normalize the current date */
1227 (void) mktime_or_timegm(&c
, spec
->utc
);
1228 c
.tm_isdst
= spec
->dst
;
1231 r
= find_matching_component(spec
, spec
->year
, &c
, &c
.tm_year
);
1237 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1241 if (tm_out_of_bounds(&c
, spec
->utc
))
1245 r
= find_matching_component(spec
, spec
->month
, &c
, &c
.tm_mon
);
1250 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1252 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1256 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1260 r
= find_matching_component(spec
, spec
->day
, &c
, &c
.tm_mday
);
1262 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1263 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1266 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1270 if (!matches_weekday(spec
->weekdays_bits
, &c
, spec
->utc
)) {
1272 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1276 r
= find_matching_component(spec
, spec
->hour
, &c
, &c
.tm_hour
);
1278 c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1279 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1281 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1285 r
= find_matching_component(spec
, spec
->minute
, &c
, &c
.tm_min
);
1287 c
.tm_sec
= tm_usec
= 0;
1288 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1290 c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1294 c
.tm_sec
= c
.tm_sec
* USEC_PER_SEC
+ tm_usec
;
1295 r
= find_matching_component(spec
, spec
->microsecond
, &c
, &c
.tm_sec
);
1296 tm_usec
= c
.tm_sec
% USEC_PER_SEC
;
1297 c
.tm_sec
/= USEC_PER_SEC
;
1299 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1301 c
.tm_sec
= tm_usec
= 0;
1311 static int calendar_spec_next_usec_impl(const CalendarSpec
*spec
, usec_t usec
, usec_t
*next
) {
1320 if (usec
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
1324 t
= (time_t) (usec
/ USEC_PER_SEC
);
1325 assert_se(localtime_or_gmtime_r(&t
, &tm
, spec
->utc
));
1326 tm_usec
= usec
% USEC_PER_SEC
;
1328 r
= find_next(spec
, &tm
, &tm_usec
);
1332 t
= mktime_or_timegm(&tm
, spec
->utc
);
1336 *next
= (usec_t
) t
* USEC_PER_SEC
+ tm_usec
;
1340 typedef struct SpecNextResult
{
1345 int calendar_spec_next_usec(const CalendarSpec
*spec
, usec_t usec
, usec_t
*next
) {
1346 SpecNextResult
*shared
, tmp
;
1349 if (isempty(spec
->timezone
))
1350 return calendar_spec_next_usec_impl(spec
, usec
, next
);
1352 shared
= mmap(NULL
, sizeof *shared
, PROT_READ
|PROT_WRITE
, MAP_SHARED
|MAP_ANONYMOUS
, -1, 0);
1353 if (shared
== MAP_FAILED
)
1354 return negative_errno();
1356 r
= safe_fork("(sd-calendar)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG
|FORK_WAIT
, NULL
);
1358 (void) munmap(shared
, sizeof *shared
);
1362 if (setenv("TZ", spec
->timezone
, 1) != 0) {
1363 shared
->return_value
= negative_errno();
1364 _exit(EXIT_FAILURE
);
1369 shared
->return_value
= calendar_spec_next_usec_impl(spec
, usec
, &shared
->next
);
1371 _exit(EXIT_SUCCESS
);
1375 if (munmap(shared
, sizeof *shared
) < 0)
1376 return negative_errno();
1378 if (tmp
.return_value
== 0)
1381 return tmp
.return_value
;