1 /* SPDX-License-Identifier: LGPL-2.1+ */
15 #include "alloc-util.h"
16 #include "calendarspec.h"
19 #include "parse-util.h"
20 #include "process-util.h"
21 #include "string-util.h"
22 #include "time-util.h"
24 #define BITS_WEEKDAYS 127
28 /* An arbitrary limit on the length of the chains of components. We don't want to
29 * build a very long linked list, which would be slow to iterate over and might cause
30 * our stack to overflow. It's unlikely that legitimate uses require more than a few
31 * linked compenents anyway. */
32 #define CALENDARSPEC_COMPONENTS_MAX 240
34 static void free_chain(CalendarComponent
*c
) {
44 CalendarSpec
* calendar_spec_free(CalendarSpec
*c
) {
53 free_chain(c
->minute
);
54 free_chain(c
->microsecond
);
60 static int component_compare(CalendarComponent
* const *a
, CalendarComponent
* const *b
) {
63 r
= CMP((*a
)->start
, (*b
)->start
);
67 r
= CMP((*a
)->stop
, (*b
)->stop
);
71 return CMP((*a
)->repeat
, (*b
)->repeat
);
74 static void normalize_chain(CalendarComponent
**c
) {
75 CalendarComponent
**b
, *i
, **j
, *next
;
80 for (i
= *c
; i
; i
= i
->next
) {
84 * While we're counting the chain, also normalize `stop`
85 * so the length of the range is a multiple of `repeat`
87 if (i
->stop
> i
->start
&& i
->repeat
> 0)
88 i
->stop
-= (i
->stop
- i
->start
) % i
->repeat
;
95 j
= b
= newa(CalendarComponent
*, n
);
96 for (i
= *c
; i
; i
= i
->next
)
99 typesafe_qsort(b
, n
, component_compare
);
104 /* Drop non-unique entries */
105 for (k
= n
-1; k
> 0; k
--) {
106 if (component_compare(&b
[k
-1], &next
) == 0) {
118 static void fix_year(CalendarComponent
*c
) {
119 /* Turns 12 → 2012, 89 → 1989 */
122 if (c
->start
>= 0 && c
->start
< 70)
125 if (c
->stop
>= 0 && c
->stop
< 70)
128 if (c
->start
>= 70 && c
->start
< 100)
131 if (c
->stop
>= 70 && c
->stop
< 100)
138 int calendar_spec_normalize(CalendarSpec
*c
) {
141 if (streq_ptr(c
->timezone
, "UTC")) {
143 c
->timezone
= mfree(c
->timezone
);
146 if (c
->weekdays_bits
<= 0 || c
->weekdays_bits
>= BITS_WEEKDAYS
)
147 c
->weekdays_bits
= -1;
149 if (c
->end_of_month
&& !c
->day
)
150 c
->end_of_month
= false;
154 normalize_chain(&c
->year
);
155 normalize_chain(&c
->month
);
156 normalize_chain(&c
->day
);
157 normalize_chain(&c
->hour
);
158 normalize_chain(&c
->minute
);
159 normalize_chain(&c
->microsecond
);
164 _pure_
static bool chain_valid(CalendarComponent
*c
, int from
, int to
, bool end_of_month
) {
170 /* Forbid dates more than 28 days from the end of the month */
174 if (c
->start
< from
|| c
->start
> to
)
177 /* Avoid overly large values that could cause overflow */
178 if (c
->repeat
> to
- from
)
182 * c->repeat must be short enough so at least one repetition may
183 * occur before the end of the interval. For dates scheduled
184 * relative to the end of the month, c->start and c->stop
185 * correspond to the Nth last day of the month.
188 if (c
->stop
< from
|| c
->stop
> to
)
191 if (c
->start
+ c
->repeat
> c
->stop
)
194 if (end_of_month
&& c
->start
- c
->repeat
< from
)
197 if (!end_of_month
&& c
->start
+ c
->repeat
> to
)
202 return chain_valid(c
->next
, from
, to
, end_of_month
);
207 _pure_
bool calendar_spec_valid(CalendarSpec
*c
) {
210 if (c
->weekdays_bits
> BITS_WEEKDAYS
)
213 if (!chain_valid(c
->year
, MIN_YEAR
, MAX_YEAR
, false))
216 if (!chain_valid(c
->month
, 1, 12, false))
219 if (!chain_valid(c
->day
, 1, 31, c
->end_of_month
))
222 if (!chain_valid(c
->hour
, 0, 23, false))
225 if (!chain_valid(c
->minute
, 0, 59, false))
228 if (!chain_valid(c
->microsecond
, 0, 60*USEC_PER_SEC
-1, false))
234 static void format_weekdays(FILE *f
, const CalendarSpec
*c
) {
235 static const char *const days
[] = {
246 bool need_comma
= false;
250 assert(c
->weekdays_bits
> 0 && c
->weekdays_bits
<= BITS_WEEKDAYS
);
252 for (x
= 0, l
= -1; x
< (int) ELEMENTSOF(days
); x
++) {
254 if (c
->weekdays_bits
& (1 << x
)) {
269 fputs(x
> l
+ 2 ? ".." : ",", f
);
277 if (l
>= 0 && x
> l
+ 1) {
278 fputs(x
> l
+ 2 ? ".." : ",", f
);
283 static void format_chain(FILE *f
, int space
, const CalendarComponent
*c
, bool usec
) {
284 int d
= usec
? (int) USEC_PER_SEC
: 1;
293 if (usec
&& c
->start
== 0 && c
->repeat
== USEC_PER_SEC
&& !c
->next
) {
298 assert(c
->start
>= 0);
300 fprintf(f
, "%0*i", space
, c
->start
/ d
);
301 if (c
->start
% d
> 0)
302 fprintf(f
, ".%06i", c
->start
% d
);
305 fprintf(f
, "..%0*i", space
, c
->stop
/ d
);
307 fprintf(f
, ".%06i", c
->stop
% d
);
309 if (c
->repeat
> 0 && !(c
->stop
> 0 && c
->repeat
== d
))
310 fprintf(f
, "/%i", c
->repeat
/ d
);
311 if (c
->repeat
% d
> 0)
312 fprintf(f
, ".%06i", c
->repeat
% d
);
316 format_chain(f
, space
, c
->next
, usec
);
320 int calendar_spec_to_string(const CalendarSpec
*c
, char **p
) {
329 f
= open_memstream(&buf
, &sz
);
333 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
335 if (c
->weekdays_bits
> 0 && c
->weekdays_bits
<= BITS_WEEKDAYS
) {
336 format_weekdays(f
, c
);
340 format_chain(f
, 4, c
->year
, false);
342 format_chain(f
, 2, c
->month
, false);
343 fputc(c
->end_of_month
? '~' : '-', f
);
344 format_chain(f
, 2, c
->day
, false);
346 format_chain(f
, 2, c
->hour
, false);
348 format_chain(f
, 2, c
->minute
, false);
350 format_chain(f
, 2, c
->microsecond
, true);
354 else if (c
->timezone
!= NULL
) {
356 fputs(c
->timezone
, f
);
357 } else if (IN_SET(c
->dst
, 0, 1)) {
359 /* If daylight saving is explicitly on or off, let's show the used timezone. */
363 if (!isempty(tzname
[c
->dst
])) {
365 fputs(tzname
[c
->dst
], f
);
369 r
= fflush_and_check(f
);
382 static int parse_weekdays(const char **p
, CalendarSpec
*c
) {
383 static const struct {
413 for (i
= 0; i
< ELEMENTSOF(day_nr
); i
++) {
416 if (!startswith_no_case(*p
, day_nr
[i
].name
))
419 skip
= strlen(day_nr
[i
].name
);
421 if (!IN_SET((*p
)[skip
], 0, '-', '.', ',', ' '))
424 c
->weekdays_bits
|= 1 << day_nr
[i
].nr
;
429 if (l
> day_nr
[i
].nr
)
432 for (j
= l
+ 1; j
< day_nr
[i
].nr
; j
++)
433 c
->weekdays_bits
|= 1 << j
;
440 /* Couldn't find this prefix, so let's assume the
441 weekday was not specified and let's continue with
443 if (i
>= ELEMENTSOF(day_nr
))
444 return first
? 0 : -EINVAL
;
446 /* We reached the end of the string */
450 /* We reached the end of the weekday spec part */
452 *p
+= strspn(*p
, " ");
466 /* Support ranges with "-" for backwards compatibility */
467 } else if (**p
== '-') {
474 } else if (**p
== ',') {
479 /* Allow a trailing comma but not an open range */
480 if (IN_SET(**p
, 0, ' ')) {
481 *p
+= strspn(*p
, " ");
482 return l
< 0 ? 0 : -EINVAL
;
489 static int parse_one_number(const char *p
, const char **e
, unsigned long *ret
) {
494 value
= strtoul(p
, &ee
, 10);
505 static int parse_component_decimal(const char **p
, bool usec
, int *res
) {
507 const char *e
= NULL
;
513 r
= parse_one_number(*p
, &e
, &value
);
518 if (value
* USEC_PER_SEC
/ USEC_PER_SEC
!= value
)
521 value
*= USEC_PER_SEC
;
523 /* One "." is a decimal point, but ".." is a range separator */
524 if (e
[0] == '.' && e
[1] != '.') {
528 r
= parse_fractional_part_u(&e
, 6, &add
);
532 if (add
+ value
< value
)
547 static int const_chain(int value
, CalendarComponent
**c
) {
548 CalendarComponent
*cc
= NULL
;
552 cc
= new0(CalendarComponent
, 1);
566 static int calendarspec_from_time_t(CalendarSpec
*c
, time_t time
) {
568 CalendarComponent
*year
= NULL
, *month
= NULL
, *day
= NULL
, *hour
= NULL
, *minute
= NULL
, *us
= NULL
;
571 if (!gmtime_r(&time
, &tm
))
574 r
= const_chain(tm
.tm_year
+ 1900, &year
);
578 r
= const_chain(tm
.tm_mon
+ 1, &month
);
582 r
= const_chain(tm
.tm_mday
, &day
);
586 r
= const_chain(tm
.tm_hour
, &hour
);
590 r
= const_chain(tm
.tm_min
, &minute
);
594 r
= const_chain(tm
.tm_sec
* USEC_PER_SEC
, &us
);
608 static int prepend_component(const char **p
, bool usec
, unsigned nesting
, CalendarComponent
**c
) {
609 int r
, start
, stop
= -1, repeat
= 0;
610 CalendarComponent
*cc
;
616 if (nesting
> CALENDARSPEC_COMPONENTS_MAX
)
619 r
= parse_component_decimal(&e
, usec
, &start
);
623 if (e
[0] == '.' && e
[1] == '.') {
625 r
= parse_component_decimal(&e
, usec
, &stop
);
629 repeat
= usec
? USEC_PER_SEC
: 1;
634 r
= parse_component_decimal(&e
, usec
, &repeat
);
642 if (!IN_SET(*e
, 0, ' ', ',', '-', '~', ':'))
645 cc
= new0(CalendarComponent
, 1);
659 return prepend_component(p
, usec
, nesting
+ 1, c
);
665 static int parse_chain(const char **p
, bool usec
, CalendarComponent
**c
) {
667 CalendarComponent
*cc
= NULL
;
677 r
= const_chain(0, c
);
680 (*c
)->repeat
= USEC_PER_SEC
;
688 r
= prepend_component(&t
, usec
, 0, &cc
);
699 static int parse_date(const char **p
, CalendarSpec
*c
) {
702 CalendarComponent
*first
, *second
, *third
;
713 /* @TIMESTAMP — UNIX time in seconds since the epoch */
718 r
= parse_one_number(t
+ 1, &t
, &value
);
723 if ((unsigned long) time
!= value
)
726 r
= calendarspec_from_time_t(c
, time
);
731 return 1; /* finito, don't parse H:M:S after that */
734 r
= parse_chain(&t
, false, &first
);
738 /* Already the end? A ':' as separator? In that case this was a time, not a date */
739 if (IN_SET(*t
, 0, ':')) {
745 c
->end_of_month
= true;
746 else if (*t
!= '-') {
752 r
= parse_chain(&t
, false, &second
);
758 /* Got two parts, hence it's month and day */
759 if (IN_SET(*t
, 0, ' ')) {
760 *p
= t
+ strspn(t
, " ");
764 } else if (c
->end_of_month
) {
771 c
->end_of_month
= true;
772 else if (*t
!= '-') {
779 r
= parse_chain(&t
, false, &third
);
786 /* Got three parts, hence it is year, month and day */
787 if (IN_SET(*t
, 0, ' ')) {
788 *p
= t
+ strspn(t
, " ");
801 static int parse_calendar_time(const char **p
, CalendarSpec
*c
) {
802 CalendarComponent
*h
= NULL
, *m
= NULL
, *s
= NULL
;
812 /* If no time is specified at all, then this means 00:00:00 */
816 r
= parse_chain(&t
, false, &h
);
826 r
= parse_chain(&t
, false, &m
);
830 /* Already at the end? Then it's hours and minutes, and seconds are 0 */
840 r
= parse_chain(&t
, true, &s
);
844 /* At the end? Then it's hours, minutes and seconds */
852 r
= const_chain(0, &h
);
856 r
= const_chain(0, &m
);
861 r
= const_chain(0, &s
);
880 int calendar_spec_from_string(const char *p
, CalendarSpec
**spec
) {
882 _cleanup_(calendar_spec_freep
) CalendarSpec
*c
= NULL
;
883 _cleanup_free_
char *p_tmp
= NULL
;
889 c
= new0(CalendarSpec
, 1);
895 utc
= endswith_no_case(p
, " UTC");
898 p
= p_tmp
= strndup(p
, utc
- p
);
902 const char *e
= NULL
;
907 /* Check if the local timezone was specified? */
908 for (j
= 0; j
<= 1; j
++) {
909 if (isempty(tzname
[j
]))
912 e
= endswith_no_case(p
, tzname
[j
]);
923 /* Found one of the two timezones specified? */
924 if (IN_SET(j
, 0, 1)) {
925 p
= p_tmp
= strndup(p
, e
- p
- 1);
931 const char *last_space
;
933 last_space
= strrchr(p
, ' ');
934 if (last_space
!= NULL
&& timezone_is_valid(last_space
+ 1, LOG_DEBUG
)) {
935 c
->timezone
= strdup(last_space
+ 1);
939 p
= p_tmp
= strndup(p
, last_space
- p
);
949 if (strcaseeq(p
, "minutely")) {
950 r
= const_chain(0, &c
->microsecond
);
954 } else if (strcaseeq(p
, "hourly")) {
955 r
= const_chain(0, &c
->minute
);
958 r
= const_chain(0, &c
->microsecond
);
962 } else if (strcaseeq(p
, "daily")) {
963 r
= const_chain(0, &c
->hour
);
966 r
= const_chain(0, &c
->minute
);
969 r
= const_chain(0, &c
->microsecond
);
973 } else if (strcaseeq(p
, "monthly")) {
974 r
= const_chain(1, &c
->day
);
977 r
= const_chain(0, &c
->hour
);
980 r
= const_chain(0, &c
->minute
);
983 r
= const_chain(0, &c
->microsecond
);
987 } else if (strcaseeq(p
, "annually") ||
988 strcaseeq(p
, "yearly") ||
989 strcaseeq(p
, "anually") /* backwards compatibility */ ) {
991 r
= const_chain(1, &c
->month
);
994 r
= const_chain(1, &c
->day
);
997 r
= const_chain(0, &c
->hour
);
1000 r
= const_chain(0, &c
->minute
);
1003 r
= const_chain(0, &c
->microsecond
);
1007 } else if (strcaseeq(p
, "weekly")) {
1009 c
->weekdays_bits
= 1;
1011 r
= const_chain(0, &c
->hour
);
1014 r
= const_chain(0, &c
->minute
);
1017 r
= const_chain(0, &c
->microsecond
);
1021 } else if (strcaseeq(p
, "quarterly")) {
1023 r
= const_chain(1, &c
->month
);
1026 r
= const_chain(4, &c
->month
);
1029 r
= const_chain(7, &c
->month
);
1032 r
= const_chain(10, &c
->month
);
1035 r
= const_chain(1, &c
->day
);
1038 r
= const_chain(0, &c
->hour
);
1041 r
= const_chain(0, &c
->minute
);
1044 r
= const_chain(0, &c
->microsecond
);
1048 } else if (strcaseeq(p
, "biannually") ||
1049 strcaseeq(p
, "bi-annually") ||
1050 strcaseeq(p
, "semiannually") ||
1051 strcaseeq(p
, "semi-annually")) {
1053 r
= const_chain(1, &c
->month
);
1056 r
= const_chain(7, &c
->month
);
1059 r
= const_chain(1, &c
->day
);
1062 r
= const_chain(0, &c
->hour
);
1065 r
= const_chain(0, &c
->minute
);
1068 r
= const_chain(0, &c
->microsecond
);
1073 r
= parse_weekdays(&p
, c
);
1077 r
= parse_date(&p
, c
);
1082 r
= parse_calendar_time(&p
, c
);
1091 r
= calendar_spec_normalize(c
);
1095 if (!calendar_spec_valid(c
))
1098 *spec
= TAKE_PTR(c
);
1102 static int find_end_of_month(struct tm
*tm
, bool utc
, int day
) {
1106 t
.tm_mday
= 1 - day
;
1108 if (mktime_or_timegm(&t
, utc
) < 0 ||
1109 t
.tm_mon
!= tm
->tm_mon
)
1115 static int find_matching_component(const CalendarSpec
*spec
, const CalendarComponent
*c
,
1116 struct tm
*tm
, int *val
) {
1117 const CalendarComponent
*p
= c
;
1118 int start
, stop
, d
= -1;
1131 if (spec
->end_of_month
&& p
== spec
->day
) {
1132 start
= find_end_of_month(tm
, spec
->utc
, start
);
1133 stop
= find_end_of_month(tm
, spec
->utc
, stop
);
1136 SWAP_TWO(start
, stop
);
1139 if (start
>= *val
) {
1141 if (!d_set
|| start
< d
) {
1146 } else if (c
->repeat
> 0) {
1149 k
= start
+ c
->repeat
* DIV_ROUND_UP(*val
- start
, c
->repeat
);
1151 if ((!d_set
|| k
< d
) && (stop
< 0 || k
<= stop
)) {
1168 static bool tm_out_of_bounds(const struct tm
*tm
, bool utc
) {
1174 if (mktime_or_timegm(&t
, utc
) < 0)
1178 * Set an upper bound on the year so impossible dates like "*-02-31"
1179 * don't cause find_next() to loop forever. tm_year contains years
1180 * since 1900, so adjust it accordingly.
1182 if (tm
->tm_year
+ 1900 > MAX_YEAR
)
1185 /* Did any normalization take place? If so, it was out of bounds before */
1187 t
.tm_year
!= tm
->tm_year
||
1188 t
.tm_mon
!= tm
->tm_mon
||
1189 t
.tm_mday
!= tm
->tm_mday
||
1190 t
.tm_hour
!= tm
->tm_hour
||
1191 t
.tm_min
!= tm
->tm_min
||
1192 t
.tm_sec
!= tm
->tm_sec
;
1195 static bool matches_weekday(int weekdays_bits
, const struct tm
*tm
, bool utc
) {
1199 if (weekdays_bits
< 0 || weekdays_bits
>= BITS_WEEKDAYS
)
1203 if (mktime_or_timegm(&t
, utc
) < 0)
1206 k
= t
.tm_wday
== 0 ? 6 : t
.tm_wday
- 1;
1207 return (weekdays_bits
& (1 << k
));
1210 static int find_next(const CalendarSpec
*spec
, struct tm
*tm
, usec_t
*usec
) {
1222 /* Normalize the current date */
1223 (void) mktime_or_timegm(&c
, spec
->utc
);
1224 c
.tm_isdst
= spec
->dst
;
1227 r
= find_matching_component(spec
, spec
->year
, &c
, &c
.tm_year
);
1233 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1237 if (tm_out_of_bounds(&c
, spec
->utc
))
1241 r
= find_matching_component(spec
, spec
->month
, &c
, &c
.tm_mon
);
1246 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1248 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1252 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1256 r
= find_matching_component(spec
, spec
->day
, &c
, &c
.tm_mday
);
1258 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1259 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1262 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1266 if (!matches_weekday(spec
->weekdays_bits
, &c
, spec
->utc
)) {
1268 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1272 r
= find_matching_component(spec
, spec
->hour
, &c
, &c
.tm_hour
);
1274 c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1275 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1277 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1281 r
= find_matching_component(spec
, spec
->minute
, &c
, &c
.tm_min
);
1283 c
.tm_sec
= tm_usec
= 0;
1284 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1286 c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1290 c
.tm_sec
= c
.tm_sec
* USEC_PER_SEC
+ tm_usec
;
1291 r
= find_matching_component(spec
, spec
->microsecond
, &c
, &c
.tm_sec
);
1292 tm_usec
= c
.tm_sec
% USEC_PER_SEC
;
1293 c
.tm_sec
/= USEC_PER_SEC
;
1295 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1297 c
.tm_sec
= tm_usec
= 0;
1307 static int calendar_spec_next_usec_impl(const CalendarSpec
*spec
, usec_t usec
, usec_t
*next
) {
1316 if (usec
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
1320 t
= (time_t) (usec
/ USEC_PER_SEC
);
1321 assert_se(localtime_or_gmtime_r(&t
, &tm
, spec
->utc
));
1322 tm_usec
= usec
% USEC_PER_SEC
;
1324 r
= find_next(spec
, &tm
, &tm_usec
);
1328 t
= mktime_or_timegm(&tm
, spec
->utc
);
1332 *next
= (usec_t
) t
* USEC_PER_SEC
+ tm_usec
;
1336 typedef struct SpecNextResult
{
1341 int calendar_spec_next_usec(const CalendarSpec
*spec
, usec_t usec
, usec_t
*next
) {
1342 SpecNextResult
*shared
, tmp
;
1345 if (isempty(spec
->timezone
))
1346 return calendar_spec_next_usec_impl(spec
, usec
, next
);
1348 shared
= mmap(NULL
, sizeof *shared
, PROT_READ
|PROT_WRITE
, MAP_SHARED
|MAP_ANONYMOUS
, -1, 0);
1349 if (shared
== MAP_FAILED
)
1350 return negative_errno();
1352 r
= safe_fork("(sd-calendar)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG
|FORK_WAIT
, NULL
);
1354 (void) munmap(shared
, sizeof *shared
);
1358 if (setenv("TZ", spec
->timezone
, 1) != 0) {
1359 shared
->return_value
= negative_errno();
1360 _exit(EXIT_FAILURE
);
1365 shared
->return_value
= calendar_spec_next_usec_impl(spec
, usec
, &shared
->next
);
1367 _exit(EXIT_SUCCESS
);
1371 if (munmap(shared
, sizeof *shared
) < 0)
1372 return negative_errno();
1374 if (tmp
.return_value
== 0)
1377 return tmp
.return_value
;