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 "sort-util.h"
22 #include "string-util.h"
23 #include "time-util.h"
25 #define BITS_WEEKDAYS 127
29 /* An arbitrary limit on the length of the chains of components. We don't want to
30 * build a very long linked list, which would be slow to iterate over and might cause
31 * our stack to overflow. It's unlikely that legitimate uses require more than a few
32 * linked compenents anyway. */
33 #define CALENDARSPEC_COMPONENTS_MAX 240
35 static void free_chain(CalendarComponent
*c
) {
45 CalendarSpec
* calendar_spec_free(CalendarSpec
*c
) {
54 free_chain(c
->minute
);
55 free_chain(c
->microsecond
);
61 static int component_compare(CalendarComponent
* const *a
, CalendarComponent
* const *b
) {
64 r
= CMP((*a
)->start
, (*b
)->start
);
68 r
= CMP((*a
)->stop
, (*b
)->stop
);
72 return CMP((*a
)->repeat
, (*b
)->repeat
);
75 static void normalize_chain(CalendarComponent
**c
) {
76 CalendarComponent
**b
, *i
, **j
, *next
;
81 for (i
= *c
; i
; i
= i
->next
) {
85 * While we're counting the chain, also normalize `stop`
86 * so the length of the range is a multiple of `repeat`
88 if (i
->stop
> i
->start
&& i
->repeat
> 0)
89 i
->stop
-= (i
->stop
- i
->start
) % i
->repeat
;
96 j
= b
= newa(CalendarComponent
*, n
);
97 for (i
= *c
; i
; i
= i
->next
)
100 typesafe_qsort(b
, n
, component_compare
);
105 /* Drop non-unique entries */
106 for (k
= n
-1; k
> 0; k
--) {
107 if (component_compare(&b
[k
-1], &next
) == 0) {
119 static void fix_year(CalendarComponent
*c
) {
120 /* Turns 12 → 2012, 89 → 1989 */
123 if (c
->start
>= 0 && c
->start
< 70)
126 if (c
->stop
>= 0 && c
->stop
< 70)
129 if (c
->start
>= 70 && c
->start
< 100)
132 if (c
->stop
>= 70 && c
->stop
< 100)
139 int calendar_spec_normalize(CalendarSpec
*c
) {
142 if (streq_ptr(c
->timezone
, "UTC")) {
144 c
->timezone
= mfree(c
->timezone
);
147 if (c
->weekdays_bits
<= 0 || c
->weekdays_bits
>= BITS_WEEKDAYS
)
148 c
->weekdays_bits
= -1;
150 if (c
->end_of_month
&& !c
->day
)
151 c
->end_of_month
= false;
155 normalize_chain(&c
->year
);
156 normalize_chain(&c
->month
);
157 normalize_chain(&c
->day
);
158 normalize_chain(&c
->hour
);
159 normalize_chain(&c
->minute
);
160 normalize_chain(&c
->microsecond
);
165 _pure_
static bool chain_valid(CalendarComponent
*c
, int from
, int to
, bool end_of_month
) {
171 /* Forbid dates more than 28 days from the end of the month */
175 if (c
->start
< from
|| c
->start
> to
)
178 /* Avoid overly large values that could cause overflow */
179 if (c
->repeat
> to
- from
)
183 * c->repeat must be short enough so at least one repetition may
184 * occur before the end of the interval. For dates scheduled
185 * relative to the end of the month, c->start and c->stop
186 * correspond to the Nth last day of the month.
189 if (c
->stop
< from
|| c
->stop
> to
)
192 if (c
->start
+ c
->repeat
> c
->stop
)
195 if (end_of_month
&& c
->start
- c
->repeat
< from
)
198 if (!end_of_month
&& c
->start
+ c
->repeat
> to
)
203 return chain_valid(c
->next
, from
, to
, end_of_month
);
208 _pure_
bool calendar_spec_valid(CalendarSpec
*c
) {
211 if (c
->weekdays_bits
> BITS_WEEKDAYS
)
214 if (!chain_valid(c
->year
, MIN_YEAR
, MAX_YEAR
, false))
217 if (!chain_valid(c
->month
, 1, 12, false))
220 if (!chain_valid(c
->day
, 1, 31, c
->end_of_month
))
223 if (!chain_valid(c
->hour
, 0, 23, false))
226 if (!chain_valid(c
->minute
, 0, 59, false))
229 if (!chain_valid(c
->microsecond
, 0, 60*USEC_PER_SEC
-1, false))
235 static void format_weekdays(FILE *f
, const CalendarSpec
*c
) {
236 static const char *const days
[] = {
247 bool need_comma
= false;
251 assert(c
->weekdays_bits
> 0 && c
->weekdays_bits
<= BITS_WEEKDAYS
);
253 for (x
= 0, l
= -1; x
< (int) ELEMENTSOF(days
); x
++) {
255 if (c
->weekdays_bits
& (1 << x
)) {
270 fputs(x
> l
+ 2 ? ".." : ",", f
);
278 if (l
>= 0 && x
> l
+ 1) {
279 fputs(x
> l
+ 2 ? ".." : ",", f
);
284 static void format_chain(FILE *f
, int space
, const CalendarComponent
*c
, bool usec
) {
285 int d
= usec
? (int) USEC_PER_SEC
: 1;
294 if (usec
&& c
->start
== 0 && c
->repeat
== USEC_PER_SEC
&& !c
->next
) {
299 assert(c
->start
>= 0);
301 fprintf(f
, "%0*i", space
, c
->start
/ d
);
302 if (c
->start
% d
> 0)
303 fprintf(f
, ".%06i", c
->start
% d
);
306 fprintf(f
, "..%0*i", space
, c
->stop
/ d
);
308 fprintf(f
, ".%06i", c
->stop
% d
);
310 if (c
->repeat
> 0 && !(c
->stop
> 0 && c
->repeat
== d
))
311 fprintf(f
, "/%i", c
->repeat
/ d
);
312 if (c
->repeat
% d
> 0)
313 fprintf(f
, ".%06i", c
->repeat
% d
);
317 format_chain(f
, space
, c
->next
, usec
);
321 int calendar_spec_to_string(const CalendarSpec
*c
, char **p
) {
330 f
= open_memstream(&buf
, &sz
);
334 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
336 if (c
->weekdays_bits
> 0 && c
->weekdays_bits
<= BITS_WEEKDAYS
) {
337 format_weekdays(f
, c
);
341 format_chain(f
, 4, c
->year
, false);
343 format_chain(f
, 2, c
->month
, false);
344 fputc(c
->end_of_month
? '~' : '-', f
);
345 format_chain(f
, 2, c
->day
, false);
347 format_chain(f
, 2, c
->hour
, false);
349 format_chain(f
, 2, c
->minute
, false);
351 format_chain(f
, 2, c
->microsecond
, true);
355 else if (c
->timezone
!= NULL
) {
357 fputs(c
->timezone
, f
);
358 } else if (IN_SET(c
->dst
, 0, 1)) {
360 /* If daylight saving is explicitly on or off, let's show the used timezone. */
364 if (!isempty(tzname
[c
->dst
])) {
366 fputs(tzname
[c
->dst
], f
);
370 r
= fflush_and_check(f
);
383 static int parse_weekdays(const char **p
, CalendarSpec
*c
) {
384 static const struct {
414 for (i
= 0; i
< ELEMENTSOF(day_nr
); i
++) {
417 if (!startswith_no_case(*p
, day_nr
[i
].name
))
420 skip
= strlen(day_nr
[i
].name
);
422 if (!IN_SET((*p
)[skip
], 0, '-', '.', ',', ' '))
425 c
->weekdays_bits
|= 1 << day_nr
[i
].nr
;
430 if (l
> day_nr
[i
].nr
)
433 for (j
= l
+ 1; j
< day_nr
[i
].nr
; j
++)
434 c
->weekdays_bits
|= 1 << j
;
441 /* Couldn't find this prefix, so let's assume the
442 weekday was not specified and let's continue with
444 if (i
>= ELEMENTSOF(day_nr
))
445 return first
? 0 : -EINVAL
;
447 /* We reached the end of the string */
451 /* We reached the end of the weekday spec part */
453 *p
+= strspn(*p
, " ");
467 /* Support ranges with "-" for backwards compatibility */
468 } else if (**p
== '-') {
475 } else if (**p
== ',') {
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
;
490 static int parse_one_number(const char *p
, const char **e
, unsigned long *ret
) {
495 value
= strtoul(p
, &ee
, 10);
506 static int parse_component_decimal(const char **p
, bool usec
, int *res
) {
508 const char *e
= NULL
;
514 r
= parse_one_number(*p
, &e
, &value
);
519 if (value
* USEC_PER_SEC
/ USEC_PER_SEC
!= value
)
522 value
*= USEC_PER_SEC
;
524 /* One "." is a decimal point, but ".." is a range separator */
525 if (e
[0] == '.' && e
[1] != '.') {
529 r
= parse_fractional_part_u(&e
, 6, &add
);
533 if (add
+ value
< value
)
548 static int const_chain(int value
, CalendarComponent
**c
) {
549 CalendarComponent
*cc
= NULL
;
553 cc
= new0(CalendarComponent
, 1);
567 static int calendarspec_from_time_t(CalendarSpec
*c
, time_t time
) {
569 CalendarComponent
*year
= NULL
, *month
= NULL
, *day
= NULL
, *hour
= NULL
, *minute
= NULL
, *us
= NULL
;
572 if (!gmtime_r(&time
, &tm
))
575 r
= const_chain(tm
.tm_year
+ 1900, &year
);
579 r
= const_chain(tm
.tm_mon
+ 1, &month
);
583 r
= const_chain(tm
.tm_mday
, &day
);
587 r
= const_chain(tm
.tm_hour
, &hour
);
591 r
= const_chain(tm
.tm_min
, &minute
);
595 r
= const_chain(tm
.tm_sec
* USEC_PER_SEC
, &us
);
609 static int prepend_component(const char **p
, bool usec
, unsigned nesting
, CalendarComponent
**c
) {
610 int r
, start
, stop
= -1, repeat
= 0;
611 CalendarComponent
*cc
;
617 if (nesting
> CALENDARSPEC_COMPONENTS_MAX
)
620 r
= parse_component_decimal(&e
, usec
, &start
);
624 if (e
[0] == '.' && e
[1] == '.') {
626 r
= parse_component_decimal(&e
, usec
, &stop
);
630 repeat
= usec
? USEC_PER_SEC
: 1;
635 r
= parse_component_decimal(&e
, usec
, &repeat
);
643 if (!IN_SET(*e
, 0, ' ', ',', '-', '~', ':'))
646 cc
= new0(CalendarComponent
, 1);
660 return prepend_component(p
, usec
, nesting
+ 1, c
);
666 static int parse_chain(const char **p
, bool usec
, CalendarComponent
**c
) {
668 CalendarComponent
*cc
= NULL
;
678 r
= const_chain(0, c
);
681 (*c
)->repeat
= USEC_PER_SEC
;
689 r
= prepend_component(&t
, usec
, 0, &cc
);
700 static int parse_date(const char **p
, CalendarSpec
*c
) {
703 CalendarComponent
*first
, *second
, *third
;
714 /* @TIMESTAMP — UNIX time in seconds since the epoch */
719 r
= parse_one_number(t
+ 1, &t
, &value
);
724 if ((unsigned long) time
!= value
)
727 r
= calendarspec_from_time_t(c
, time
);
732 return 1; /* finito, don't parse H:M:S after that */
735 r
= parse_chain(&t
, false, &first
);
739 /* Already the end? A ':' as separator? In that case this was a time, not a date */
740 if (IN_SET(*t
, 0, ':')) {
746 c
->end_of_month
= true;
747 else if (*t
!= '-') {
753 r
= parse_chain(&t
, false, &second
);
759 /* Got two parts, hence it's month and day */
760 if (IN_SET(*t
, 0, ' ')) {
761 *p
= t
+ strspn(t
, " ");
765 } else if (c
->end_of_month
) {
772 c
->end_of_month
= true;
773 else if (*t
!= '-') {
780 r
= parse_chain(&t
, false, &third
);
787 /* Got three parts, hence it is year, month and day */
788 if (IN_SET(*t
, 0, ' ')) {
789 *p
= t
+ strspn(t
, " ");
802 static int parse_calendar_time(const char **p
, CalendarSpec
*c
) {
803 CalendarComponent
*h
= NULL
, *m
= NULL
, *s
= NULL
;
813 /* If no time is specified at all, then this means 00:00:00 */
817 r
= parse_chain(&t
, false, &h
);
827 r
= parse_chain(&t
, false, &m
);
831 /* Already at the end? Then it's hours and minutes, and seconds are 0 */
841 r
= parse_chain(&t
, true, &s
);
845 /* At the end? Then it's hours, minutes and seconds */
853 r
= const_chain(0, &h
);
857 r
= const_chain(0, &m
);
862 r
= const_chain(0, &s
);
881 int calendar_spec_from_string(const char *p
, CalendarSpec
**spec
) {
883 _cleanup_(calendar_spec_freep
) CalendarSpec
*c
= NULL
;
884 _cleanup_free_
char *p_tmp
= NULL
;
890 c
= new0(CalendarSpec
, 1);
896 utc
= endswith_no_case(p
, " UTC");
899 p
= p_tmp
= strndup(p
, utc
- p
);
903 const char *e
= NULL
;
908 /* Check if the local timezone was specified? */
909 for (j
= 0; j
<= 1; j
++) {
910 if (isempty(tzname
[j
]))
913 e
= endswith_no_case(p
, tzname
[j
]);
924 /* Found one of the two timezones specified? */
925 if (IN_SET(j
, 0, 1)) {
926 p
= p_tmp
= strndup(p
, e
- p
- 1);
932 const char *last_space
;
934 last_space
= strrchr(p
, ' ');
935 if (last_space
!= NULL
&& timezone_is_valid(last_space
+ 1, LOG_DEBUG
)) {
936 c
->timezone
= strdup(last_space
+ 1);
940 p
= p_tmp
= strndup(p
, last_space
- p
);
950 if (strcaseeq(p
, "minutely")) {
951 r
= const_chain(0, &c
->microsecond
);
955 } else if (strcaseeq(p
, "hourly")) {
956 r
= const_chain(0, &c
->minute
);
959 r
= const_chain(0, &c
->microsecond
);
963 } else if (strcaseeq(p
, "daily")) {
964 r
= const_chain(0, &c
->hour
);
967 r
= const_chain(0, &c
->minute
);
970 r
= const_chain(0, &c
->microsecond
);
974 } else if (strcaseeq(p
, "monthly")) {
975 r
= const_chain(1, &c
->day
);
978 r
= const_chain(0, &c
->hour
);
981 r
= const_chain(0, &c
->minute
);
984 r
= const_chain(0, &c
->microsecond
);
988 } else if (strcaseeq(p
, "annually") ||
989 strcaseeq(p
, "yearly") ||
990 strcaseeq(p
, "anually") /* backwards compatibility */ ) {
992 r
= const_chain(1, &c
->month
);
995 r
= const_chain(1, &c
->day
);
998 r
= const_chain(0, &c
->hour
);
1001 r
= const_chain(0, &c
->minute
);
1004 r
= const_chain(0, &c
->microsecond
);
1008 } else if (strcaseeq(p
, "weekly")) {
1010 c
->weekdays_bits
= 1;
1012 r
= const_chain(0, &c
->hour
);
1015 r
= const_chain(0, &c
->minute
);
1018 r
= const_chain(0, &c
->microsecond
);
1022 } else if (strcaseeq(p
, "quarterly")) {
1024 r
= const_chain(1, &c
->month
);
1027 r
= const_chain(4, &c
->month
);
1030 r
= const_chain(7, &c
->month
);
1033 r
= const_chain(10, &c
->month
);
1036 r
= const_chain(1, &c
->day
);
1039 r
= const_chain(0, &c
->hour
);
1042 r
= const_chain(0, &c
->minute
);
1045 r
= const_chain(0, &c
->microsecond
);
1049 } else if (strcaseeq(p
, "biannually") ||
1050 strcaseeq(p
, "bi-annually") ||
1051 strcaseeq(p
, "semiannually") ||
1052 strcaseeq(p
, "semi-annually")) {
1054 r
= const_chain(1, &c
->month
);
1057 r
= const_chain(7, &c
->month
);
1060 r
= const_chain(1, &c
->day
);
1063 r
= const_chain(0, &c
->hour
);
1066 r
= const_chain(0, &c
->minute
);
1069 r
= const_chain(0, &c
->microsecond
);
1074 r
= parse_weekdays(&p
, c
);
1078 r
= parse_date(&p
, c
);
1083 r
= parse_calendar_time(&p
, c
);
1092 r
= calendar_spec_normalize(c
);
1096 if (!calendar_spec_valid(c
))
1099 *spec
= TAKE_PTR(c
);
1103 static int find_end_of_month(struct tm
*tm
, bool utc
, int day
) {
1107 t
.tm_mday
= 1 - day
;
1109 if (mktime_or_timegm(&t
, utc
) < 0 ||
1110 t
.tm_mon
!= tm
->tm_mon
)
1116 static int find_matching_component(const CalendarSpec
*spec
, const CalendarComponent
*c
,
1117 struct tm
*tm
, int *val
) {
1118 const CalendarComponent
*p
= c
;
1119 int start
, stop
, d
= -1;
1132 if (spec
->end_of_month
&& p
== spec
->day
) {
1133 start
= find_end_of_month(tm
, spec
->utc
, start
);
1134 stop
= find_end_of_month(tm
, spec
->utc
, stop
);
1137 SWAP_TWO(start
, stop
);
1140 if (start
>= *val
) {
1142 if (!d_set
|| start
< d
) {
1147 } else if (c
->repeat
> 0) {
1150 k
= start
+ c
->repeat
* DIV_ROUND_UP(*val
- start
, c
->repeat
);
1152 if ((!d_set
|| k
< d
) && (stop
< 0 || k
<= stop
)) {
1169 static bool tm_out_of_bounds(const struct tm
*tm
, bool utc
) {
1175 if (mktime_or_timegm(&t
, utc
) < 0)
1179 * Set an upper bound on the year so impossible dates like "*-02-31"
1180 * don't cause find_next() to loop forever. tm_year contains years
1181 * since 1900, so adjust it accordingly.
1183 if (tm
->tm_year
+ 1900 > MAX_YEAR
)
1186 /* Did any normalization take place? If so, it was out of bounds before */
1188 t
.tm_year
!= tm
->tm_year
||
1189 t
.tm_mon
!= tm
->tm_mon
||
1190 t
.tm_mday
!= tm
->tm_mday
||
1191 t
.tm_hour
!= tm
->tm_hour
||
1192 t
.tm_min
!= tm
->tm_min
||
1193 t
.tm_sec
!= tm
->tm_sec
;
1196 static bool matches_weekday(int weekdays_bits
, const struct tm
*tm
, bool utc
) {
1200 if (weekdays_bits
< 0 || weekdays_bits
>= BITS_WEEKDAYS
)
1204 if (mktime_or_timegm(&t
, utc
) < 0)
1207 k
= t
.tm_wday
== 0 ? 6 : t
.tm_wday
- 1;
1208 return (weekdays_bits
& (1 << k
));
1211 static int find_next(const CalendarSpec
*spec
, struct tm
*tm
, usec_t
*usec
) {
1223 /* Normalize the current date */
1224 (void) mktime_or_timegm(&c
, spec
->utc
);
1225 c
.tm_isdst
= spec
->dst
;
1228 r
= find_matching_component(spec
, spec
->year
, &c
, &c
.tm_year
);
1234 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1238 if (tm_out_of_bounds(&c
, spec
->utc
))
1242 r
= find_matching_component(spec
, spec
->month
, &c
, &c
.tm_mon
);
1247 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1249 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1253 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1257 r
= find_matching_component(spec
, spec
->day
, &c
, &c
.tm_mday
);
1259 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1260 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1263 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1267 if (!matches_weekday(spec
->weekdays_bits
, &c
, spec
->utc
)) {
1269 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1273 r
= find_matching_component(spec
, spec
->hour
, &c
, &c
.tm_hour
);
1275 c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1276 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1278 c
.tm_hour
= c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1282 r
= find_matching_component(spec
, spec
->minute
, &c
, &c
.tm_min
);
1284 c
.tm_sec
= tm_usec
= 0;
1285 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1287 c
.tm_min
= c
.tm_sec
= tm_usec
= 0;
1291 c
.tm_sec
= c
.tm_sec
* USEC_PER_SEC
+ tm_usec
;
1292 r
= find_matching_component(spec
, spec
->microsecond
, &c
, &c
.tm_sec
);
1293 tm_usec
= c
.tm_sec
% USEC_PER_SEC
;
1294 c
.tm_sec
/= USEC_PER_SEC
;
1296 if (r
< 0 || tm_out_of_bounds(&c
, spec
->utc
)) {
1298 c
.tm_sec
= tm_usec
= 0;
1308 static int calendar_spec_next_usec_impl(const CalendarSpec
*spec
, usec_t usec
, usec_t
*next
) {
1317 if (usec
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
1321 t
= (time_t) (usec
/ USEC_PER_SEC
);
1322 assert_se(localtime_or_gmtime_r(&t
, &tm
, spec
->utc
));
1323 tm_usec
= usec
% USEC_PER_SEC
;
1325 r
= find_next(spec
, &tm
, &tm_usec
);
1329 t
= mktime_or_timegm(&tm
, spec
->utc
);
1333 *next
= (usec_t
) t
* USEC_PER_SEC
+ tm_usec
;
1337 typedef struct SpecNextResult
{
1342 int calendar_spec_next_usec(const CalendarSpec
*spec
, usec_t usec
, usec_t
*next
) {
1343 SpecNextResult
*shared
, tmp
;
1346 if (isempty(spec
->timezone
))
1347 return calendar_spec_next_usec_impl(spec
, usec
, next
);
1349 shared
= mmap(NULL
, sizeof *shared
, PROT_READ
|PROT_WRITE
, MAP_SHARED
|MAP_ANONYMOUS
, -1, 0);
1350 if (shared
== MAP_FAILED
)
1351 return negative_errno();
1353 r
= safe_fork("(sd-calendar)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG
|FORK_WAIT
, NULL
);
1355 (void) munmap(shared
, sizeof *shared
);
1359 if (setenv("TZ", spec
->timezone
, 1) != 0) {
1360 shared
->return_value
= negative_errno();
1361 _exit(EXIT_FAILURE
);
1366 shared
->return_value
= calendar_spec_next_usec_impl(spec
, usec
, &shared
->next
);
1368 _exit(EXIT_SUCCESS
);
1372 if (munmap(shared
, sizeof *shared
) < 0)
1373 return negative_errno();
1375 if (tmp
.return_value
== 0)
1378 return tmp
.return_value
;