1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2012 Lennart Poettering
12 #include <stdio_ext.h>
18 #include "alloc-util.h"
19 #include "calendarspec.h"
22 #include "parse-util.h"
23 #include "process-util.h"
24 #include "string-util.h"
25 #include "time-util.h"
27 #define BITS_WEEKDAYS 127
31 /* An arbitrary limit on the length of the chains of components. We don't want to
32 * build a very long linked list, which would be slow to iterate over and might cause
33 * our stack to overflow. It's unlikely that legitimate uses require more than a few
34 * linked compenents anyway. */
35 #define CALENDARSPEC_COMPONENTS_MAX 240
37 static void free_chain(CalendarComponent
*c
) {
47 CalendarSpec
* calendar_spec_free(CalendarSpec
*c
) {
56 free_chain(c
->minute
);
57 free_chain(c
->microsecond
);
63 static int component_compare(const void *_a
, const void *_b
) {
64 CalendarComponent
* const *a
= _a
, * const *b
= _b
;
66 if ((*a
)->start
< (*b
)->start
)
68 if ((*a
)->start
> (*b
)->start
)
71 if ((*a
)->stop
< (*b
)->stop
)
73 if ((*a
)->stop
> (*b
)->stop
)
76 if ((*a
)->repeat
< (*b
)->repeat
)
78 if ((*a
)->repeat
> (*b
)->repeat
)
84 static void normalize_chain(CalendarComponent
**c
) {
85 CalendarComponent
**b
, *i
, **j
, *next
;
90 for (i
= *c
; i
; i
= i
->next
) {
94 * While we're counting the chain, also normalize `stop`
95 * so the length of the range is a multiple of `repeat`
97 if (i
->stop
> i
->start
&& i
->repeat
> 0)
98 i
->stop
-= (i
->stop
- i
->start
) % i
->repeat
;
105 j
= b
= newa(CalendarComponent
*, n
);
106 for (i
= *c
; i
; i
= i
->next
)
109 qsort(b
, n
, sizeof(CalendarComponent
*), component_compare
);
114 /* Drop non-unique entries */
115 for (k
= n
-1; k
> 0; k
--) {
116 if (component_compare(&b
[k
-1], &next
) == 0) {
128 static void fix_year(CalendarComponent
*c
) {
129 /* Turns 12 → 2012, 89 → 1989 */
132 if (c
->start
>= 0 && c
->start
< 70)
135 if (c
->stop
>= 0 && c
->stop
< 70)
138 if (c
->start
>= 70 && c
->start
< 100)
141 if (c
->stop
>= 70 && c
->stop
< 100)
148 int calendar_spec_normalize(CalendarSpec
*c
) {
151 if (streq_ptr(c
->timezone
, "UTC")) {
153 c
->timezone
= mfree(c
->timezone
);
156 if (c
->weekdays_bits
<= 0 || c
->weekdays_bits
>= BITS_WEEKDAYS
)
157 c
->weekdays_bits
= -1;
159 if (c
->end_of_month
&& !c
->day
)
160 c
->end_of_month
= false;
164 normalize_chain(&c
->year
);
165 normalize_chain(&c
->month
);
166 normalize_chain(&c
->day
);
167 normalize_chain(&c
->hour
);
168 normalize_chain(&c
->minute
);
169 normalize_chain(&c
->microsecond
);
174 _pure_
static bool chain_valid(CalendarComponent
*c
, int from
, int to
, bool end_of_month
) {
180 /* Forbid dates more than 28 days from the end of the month */
184 if (c
->start
< from
|| c
->start
> to
)
187 /* Avoid overly large values that could cause overflow */
188 if (c
->repeat
> to
- from
)
192 * c->repeat must be short enough so at least one repetition may
193 * occur before the end of the interval. For dates scheduled
194 * relative to the end of the month, c->start and c->stop
195 * correspond to the Nth last day of the month.
198 if (c
->stop
< from
|| c
->stop
> to
)
201 if (c
->start
+ c
->repeat
> c
->stop
)
204 if (end_of_month
&& c
->start
- c
->repeat
< from
)
207 if (!end_of_month
&& c
->start
+ c
->repeat
> to
)
212 return chain_valid(c
->next
, from
, to
, end_of_month
);
217 _pure_
bool calendar_spec_valid(CalendarSpec
*c
) {
220 if (c
->weekdays_bits
> BITS_WEEKDAYS
)
223 if (!chain_valid(c
->year
, MIN_YEAR
, MAX_YEAR
, false))
226 if (!chain_valid(c
->month
, 1, 12, false))
229 if (!chain_valid(c
->day
, 1, 31, c
->end_of_month
))
232 if (!chain_valid(c
->hour
, 0, 23, false))
235 if (!chain_valid(c
->minute
, 0, 59, false))
238 if (!chain_valid(c
->microsecond
, 0, 60*USEC_PER_SEC
-1, false))
244 static void format_weekdays(FILE *f
, const CalendarSpec
*c
) {
245 static const char *const days
[] = {
256 bool need_comma
= false;
260 assert(c
->weekdays_bits
> 0 && c
->weekdays_bits
<= BITS_WEEKDAYS
);
262 for (x
= 0, l
= -1; x
< (int) ELEMENTSOF(days
); x
++) {
264 if (c
->weekdays_bits
& (1 << x
)) {
279 fputs(x
> l
+ 2 ? ".." : ",", f
);
287 if (l
>= 0 && x
> l
+ 1) {
288 fputs(x
> l
+ 2 ? ".." : ",", f
);
293 static void format_chain(FILE *f
, int space
, const CalendarComponent
*c
, bool usec
) {
294 int d
= usec
? (int) USEC_PER_SEC
: 1;
303 if (usec
&& c
->start
== 0 && c
->repeat
== USEC_PER_SEC
&& !c
->next
) {
308 assert(c
->start
>= 0);
310 fprintf(f
, "%0*i", space
, c
->start
/ d
);
311 if (c
->start
% d
> 0)
312 fprintf(f
, ".%06i", c
->start
% d
);
315 fprintf(f
, "..%0*i", space
, c
->stop
/ d
);
317 fprintf(f
, ".%06i", c
->stop
% d
);
319 if (c
->repeat
> 0 && !(c
->stop
> 0 && c
->repeat
== d
))
320 fprintf(f
, "/%i", c
->repeat
/ d
);
321 if (c
->repeat
% d
> 0)
322 fprintf(f
, ".%06i", c
->repeat
% d
);
326 format_chain(f
, space
, c
->next
, usec
);
330 int calendar_spec_to_string(const CalendarSpec
*c
, char **p
) {
339 f
= open_memstream(&buf
, &sz
);
343 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
345 if (c
->weekdays_bits
> 0 && c
->weekdays_bits
<= BITS_WEEKDAYS
) {
346 format_weekdays(f
, c
);
350 format_chain(f
, 4, c
->year
, false);
352 format_chain(f
, 2, c
->month
, false);
353 fputc(c
->end_of_month
? '~' : '-', f
);
354 format_chain(f
, 2, c
->day
, false);
356 format_chain(f
, 2, c
->hour
, false);
358 format_chain(f
, 2, c
->minute
, false);
360 format_chain(f
, 2, c
->microsecond
, true);
364 else if (c
->timezone
!= NULL
) {
366 fputs(c
->timezone
, f
);
367 } else if (IN_SET(c
->dst
, 0, 1)) {
369 /* If daylight saving is explicitly on or off, let's show the used timezone. */
373 if (!isempty(tzname
[c
->dst
])) {
375 fputs(tzname
[c
->dst
], f
);
379 r
= fflush_and_check(f
);
392 static int parse_weekdays(const char **p
, CalendarSpec
*c
) {
393 static const struct {
423 for (i
= 0; i
< ELEMENTSOF(day_nr
); i
++) {
426 if (!startswith_no_case(*p
, day_nr
[i
].name
))
429 skip
= strlen(day_nr
[i
].name
);
431 if (!IN_SET((*p
)[skip
], 0, '-', '.', ',', ' '))
434 c
->weekdays_bits
|= 1 << day_nr
[i
].nr
;
439 if (l
> day_nr
[i
].nr
)
442 for (j
= l
+ 1; j
< day_nr
[i
].nr
; j
++)
443 c
->weekdays_bits
|= 1 << j
;
450 /* Couldn't find this prefix, so let's assume the
451 weekday was not specified and let's continue with
453 if (i
>= ELEMENTSOF(day_nr
))
454 return first
? 0 : -EINVAL
;
456 /* We reached the end of the string */
460 /* We reached the end of the weekday spec part */
462 *p
+= strspn(*p
, " ");
476 /* Support ranges with "-" for backwards compatibility */
477 } else if (**p
== '-') {
484 } else if (**p
== ',') {
489 /* Allow a trailing comma but not an open range */
490 if (IN_SET(**p
, 0, ' ')) {
491 *p
+= strspn(*p
, " ");
492 return l
< 0 ? 0 : -EINVAL
;
499 static int parse_one_number(const char *p
, const char **e
, unsigned long *ret
) {
504 value
= strtoul(p
, &ee
, 10);
515 static int parse_component_decimal(const char **p
, bool usec
, int *res
) {
517 const char *e
= NULL
;
523 r
= parse_one_number(*p
, &e
, &value
);
528 if (value
* USEC_PER_SEC
/ USEC_PER_SEC
!= value
)
531 value
*= USEC_PER_SEC
;
533 /* One "." is a decimal point, but ".." is a range separator */
534 if (e
[0] == '.' && e
[1] != '.') {
538 r
= parse_fractional_part_u(&e
, 6, &add
);
542 if (add
+ value
< value
)
557 static int const_chain(int value
, CalendarComponent
**c
) {
558 CalendarComponent
*cc
= NULL
;
562 cc
= new0(CalendarComponent
, 1);
576 static int calendarspec_from_time_t(CalendarSpec
*c
, time_t time
) {
578 CalendarComponent
*year
= NULL
, *month
= NULL
, *day
= NULL
, *hour
= NULL
, *minute
= NULL
, *us
= NULL
;
581 if (!gmtime_r(&time
, &tm
))
584 r
= const_chain(tm
.tm_year
+ 1900, &year
);
588 r
= const_chain(tm
.tm_mon
+ 1, &month
);
592 r
= const_chain(tm
.tm_mday
, &day
);
596 r
= const_chain(tm
.tm_hour
, &hour
);
600 r
= const_chain(tm
.tm_min
, &minute
);
604 r
= const_chain(tm
.tm_sec
* USEC_PER_SEC
, &us
);
618 static int prepend_component(const char **p
, bool usec
, unsigned nesting
, CalendarComponent
**c
) {
619 int r
, start
, stop
= -1, repeat
= 0;
620 CalendarComponent
*cc
;
626 if (nesting
> CALENDARSPEC_COMPONENTS_MAX
)
629 r
= parse_component_decimal(&e
, usec
, &start
);
633 if (e
[0] == '.' && e
[1] == '.') {
635 r
= parse_component_decimal(&e
, usec
, &stop
);
639 repeat
= usec
? USEC_PER_SEC
: 1;
644 r
= parse_component_decimal(&e
, usec
, &repeat
);
652 if (!IN_SET(*e
, 0, ' ', ',', '-', '~', ':'))
655 cc
= new0(CalendarComponent
, 1);
669 return prepend_component(p
, usec
, nesting
+ 1, c
);
675 static int parse_chain(const char **p
, bool usec
, CalendarComponent
**c
) {
677 CalendarComponent
*cc
= NULL
;
687 r
= const_chain(0, c
);
690 (*c
)->repeat
= USEC_PER_SEC
;
698 r
= prepend_component(&t
, usec
, 0, &cc
);
709 static int parse_date(const char **p
, CalendarSpec
*c
) {
712 CalendarComponent
*first
, *second
, *third
;
723 /* @TIMESTAMP — UNIX time in seconds since the epoch */
728 r
= parse_one_number(t
+ 1, &t
, &value
);
733 if ((unsigned long) time
!= value
)
736 r
= calendarspec_from_time_t(c
, time
);
741 return 1; /* finito, don't parse H:M:S after that */
744 r
= parse_chain(&t
, false, &first
);
748 /* Already the end? A ':' as separator? In that case this was a time, not a date */
749 if (IN_SET(*t
, 0, ':')) {
755 c
->end_of_month
= true;
756 else if (*t
!= '-') {
762 r
= parse_chain(&t
, false, &second
);
768 /* Got two parts, hence it's month and day */
769 if (IN_SET(*t
, 0, ' ')) {
770 *p
= t
+ strspn(t
, " ");
774 } else if (c
->end_of_month
) {
781 c
->end_of_month
= true;
782 else if (*t
!= '-') {
789 r
= parse_chain(&t
, false, &third
);
796 /* Got three parts, hence it is year, month and day */
797 if (IN_SET(*t
, 0, ' ')) {
798 *p
= t
+ strspn(t
, " ");
811 static int parse_calendar_time(const char **p
, CalendarSpec
*c
) {
812 CalendarComponent
*h
= NULL
, *m
= NULL
, *s
= NULL
;
822 /* If no time is specified at all, then this means 00:00:00 */
826 r
= parse_chain(&t
, false, &h
);
836 r
= parse_chain(&t
, false, &m
);
840 /* Already at the end? Then it's hours and minutes, and seconds are 0 */
850 r
= parse_chain(&t
, true, &s
);
854 /* At the end? Then it's hours, minutes and seconds */
862 r
= const_chain(0, &h
);
866 r
= const_chain(0, &m
);
871 r
= const_chain(0, &s
);
890 int calendar_spec_from_string(const char *p
, CalendarSpec
**spec
) {
892 _cleanup_(calendar_spec_freep
) CalendarSpec
*c
= NULL
;
898 c
= new0(CalendarSpec
, 1);
904 utc
= endswith_no_case(p
, " UTC");
907 p
= strndupa(p
, utc
- p
);
909 const char *e
= NULL
;
914 /* Check if the local timezone was specified? */
915 for (j
= 0; j
<= 1; j
++) {
916 if (isempty(tzname
[j
]))
919 e
= endswith_no_case(p
, tzname
[j
]);
930 /* Found one of the two timezones specified? */
931 if (IN_SET(j
, 0, 1)) {
932 p
= strndupa(p
, e
- p
- 1);
935 const char *last_space
;
937 last_space
= strrchr(p
, ' ');
938 if (last_space
!= NULL
&& timezone_is_valid(last_space
+ 1, LOG_DEBUG
)) {
939 c
->timezone
= strdup(last_space
+ 1);
943 p
= strndupa(p
, last_space
- p
);
951 if (strcaseeq(p
, "minutely")) {
952 r
= const_chain(0, &c
->microsecond
);
956 } else if (strcaseeq(p
, "hourly")) {
957 r
= const_chain(0, &c
->minute
);
960 r
= const_chain(0, &c
->microsecond
);
964 } else if (strcaseeq(p
, "daily")) {
965 r
= const_chain(0, &c
->hour
);
968 r
= const_chain(0, &c
->minute
);
971 r
= const_chain(0, &c
->microsecond
);
975 } else if (strcaseeq(p
, "monthly")) {
976 r
= const_chain(1, &c
->day
);
979 r
= const_chain(0, &c
->hour
);
982 r
= const_chain(0, &c
->minute
);
985 r
= const_chain(0, &c
->microsecond
);
989 } else if (strcaseeq(p
, "annually") ||
990 strcaseeq(p
, "yearly") ||
991 strcaseeq(p
, "anually") /* backwards compatibility */ ) {
993 r
= const_chain(1, &c
->month
);
996 r
= const_chain(1, &c
->day
);
999 r
= const_chain(0, &c
->hour
);
1002 r
= const_chain(0, &c
->minute
);
1005 r
= const_chain(0, &c
->microsecond
);
1009 } else if (strcaseeq(p
, "weekly")) {
1011 c
->weekdays_bits
= 1;
1013 r
= const_chain(0, &c
->hour
);
1016 r
= const_chain(0, &c
->minute
);
1019 r
= const_chain(0, &c
->microsecond
);
1023 } else if (strcaseeq(p
, "quarterly")) {
1025 r
= const_chain(1, &c
->month
);
1028 r
= const_chain(4, &c
->month
);
1031 r
= const_chain(7, &c
->month
);
1034 r
= const_chain(10, &c
->month
);
1037 r
= const_chain(1, &c
->day
);
1040 r
= const_chain(0, &c
->hour
);
1043 r
= const_chain(0, &c
->minute
);
1046 r
= const_chain(0, &c
->microsecond
);
1050 } else if (strcaseeq(p
, "biannually") ||
1051 strcaseeq(p
, "bi-annually") ||
1052 strcaseeq(p
, "semiannually") ||
1053 strcaseeq(p
, "semi-annually")) {
1055 r
= const_chain(1, &c
->month
);
1058 r
= const_chain(7, &c
->month
);
1061 r
= const_chain(1, &c
->day
);
1064 r
= const_chain(0, &c
->hour
);
1067 r
= const_chain(0, &c
->minute
);
1070 r
= const_chain(0, &c
->microsecond
);
1075 r
= parse_weekdays(&p
, c
);
1079 r
= parse_date(&p
, c
);
1084 r
= parse_calendar_time(&p
, c
);
1093 r
= calendar_spec_normalize(c
);
1097 if (!calendar_spec_valid(c
))
1100 *spec
= TAKE_PTR(c
);
1104 static int find_end_of_month(struct tm
*tm
, bool utc
, int day
) {
1108 t
.tm_mday
= 1 - day
;
1110 if (mktime_or_timegm(&t
, utc
) < 0 ||
1111 t
.tm_mon
!= tm
->tm_mon
)
1117 static int find_matching_component(const CalendarSpec
*spec
, const CalendarComponent
*c
,
1118 struct tm
*tm
, int *val
) {
1119 const CalendarComponent
*p
= c
;
1120 int start
, stop
, d
= -1;
1133 if (spec
->end_of_month
&& p
== spec
->day
) {
1134 start
= find_end_of_month(tm
, spec
->utc
, start
);
1135 stop
= find_end_of_month(tm
, spec
->utc
, stop
);
1138 SWAP_TWO(start
, stop
);
1141 if (start
>= *val
) {
1143 if (!d_set
|| start
< d
) {
1148 } else if (c
->repeat
> 0) {
1151 k
= start
+ c
->repeat
* DIV_ROUND_UP(*val
- start
, c
->repeat
);
1153 if ((!d_set
|| k
< d
) && (stop
< 0 || k
<= stop
)) {
1170 static bool tm_out_of_bounds(const struct tm
*tm
, bool utc
) {
1176 if (mktime_or_timegm(&t
, utc
) < 0)
1180 * Set an upper bound on the year so impossible dates like "*-02-31"
1181 * don't cause find_next() to loop forever. tm_year contains years
1182 * since 1900, so adjust it accordingly.
1184 if (tm
->tm_year
+ 1900 > MAX_YEAR
)
1187 /* Did any normalization take place? If so, it was out of bounds before */
1189 t
.tm_year
!= tm
->tm_year
||
1190 t
.tm_mon
!= tm
->tm_mon
||
1191 t
.tm_mday
!= tm
->tm_mday
||
1192 t
.tm_hour
!= tm
->tm_hour
||
1193 t
.tm_min
!= tm
->tm_min
||
1194 t
.tm_sec
!= tm
->tm_sec
;
1197 static bool matches_weekday(int weekdays_bits
, const struct tm
*tm
, bool utc
) {
1201 if (weekdays_bits
< 0 || weekdays_bits
>= BITS_WEEKDAYS
)
1205 if (mktime_or_timegm(&t
, utc
) < 0)
1208 k
= t
.tm_wday
== 0 ? 6 : t
.tm_wday
- 1;
1209 return (weekdays_bits
& (1 << k
));
1212 static int find_next(const CalendarSpec
*spec
, struct tm
*tm
, usec_t
*usec
) {
1224 /* Normalize the current date */
1225 (void) mktime_or_timegm(&c
, spec
->utc
);
1226 c
.tm_isdst
= spec
->dst
;
1229 r
= find_matching_component(spec
, spec
->year
, &c
, &c
.tm_year
);
1235 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1239 if (tm_out_of_bounds(&c
, spec
->utc
))
1243 r
= find_matching_component(spec
, spec
->month
, &c
, &c
.tm_mon
);
1248 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1250 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1254 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1258 r
= find_matching_component(spec
, spec
->day
, &c
, &c
.tm_mday
);
1260 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1261 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1264 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1268 if (!matches_weekday(spec
->weekdays_bits
, &c
, spec
->utc
)) {
1270 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1274 r
= find_matching_component(spec
, spec
->hour
, &c
, &c
.tm_hour
);
1276 c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1277 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1279 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1283 r
= find_matching_component(spec
, spec
->minute
, &c
, &c
.tm_min
);
1285 c
.tm_sec
= tm_usec
= 0;
1286 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1288 c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1292 c
.tm_sec
= c
.tm_sec
* USEC_PER_SEC
+ tm_usec
;
1293 r
= find_matching_component(spec
, spec
->microsecond
, &c
, &c
.tm_sec
);
1294 tm_usec
= c
.tm_sec
% USEC_PER_SEC
;
1295 c
.tm_sec
/= USEC_PER_SEC
;
1297 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1299 c
.tm_sec
= tm_usec
= 0;
1309 static int calendar_spec_next_usec_impl(const CalendarSpec
*spec
, usec_t usec
, usec_t
*next
) {
1318 if (usec
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
1322 t
= (time_t) (usec
/ USEC_PER_SEC
);
1323 assert_se(localtime_or_gmtime_r(&t
, &tm
, spec
->utc
));
1324 tm_usec
= usec
% USEC_PER_SEC
;
1326 r
= find_next(spec
, &tm
, &tm_usec
);
1330 t
= mktime_or_timegm(&tm
, spec
->utc
);
1334 *next
= (usec_t
) t
* USEC_PER_SEC
+ tm_usec
;
1338 typedef struct SpecNextResult
{
1343 int calendar_spec_next_usec(const CalendarSpec
*spec
, usec_t usec
, usec_t
*next
) {
1344 SpecNextResult
*shared
, tmp
;
1347 if (isempty(spec
->timezone
))
1348 return calendar_spec_next_usec_impl(spec
, usec
, next
);
1350 shared
= mmap(NULL
, sizeof *shared
, PROT_READ
|PROT_WRITE
, MAP_SHARED
|MAP_ANONYMOUS
, -1, 0);
1351 if (shared
== MAP_FAILED
)
1352 return negative_errno();
1354 r
= safe_fork("(sd-calendar)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG
|FORK_WAIT
, NULL
);
1356 (void) munmap(shared
, sizeof *shared
);
1360 if (setenv("TZ", spec
->timezone
, 1) != 0) {
1361 shared
->return_value
= negative_errno();
1362 _exit(EXIT_FAILURE
);
1367 shared
->return_value
= calendar_spec_next_usec_impl(spec
, usec
, &shared
->next
);
1369 _exit(EXIT_SUCCESS
);
1373 if (munmap(shared
, sizeof *shared
) < 0)
1374 return negative_errno();
1376 if (tmp
.return_value
== 0)
1379 return tmp
.return_value
;