1 /* SPDX-License-Identifier: LGPL-2.1+ */
9 #include <sys/timerfd.h>
10 #include <sys/timex.h>
11 #include <sys/types.h>
14 #include "alloc-util.h"
21 #include "missing_timerfd.h"
22 #include "parse-util.h"
23 #include "path-util.h"
24 #include "process-util.h"
25 #include "stat-util.h"
26 #include "string-util.h"
28 #include "time-util.h"
30 static clockid_t
map_clock_id(clockid_t c
) {
32 /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus, clock_gettime() will
33 * fail for them. Since they are essentially the same as their non-ALARM pendants (their only difference is
34 * when timers are set on them), let's just map them accordingly. This way, we can get the correct time even on
39 case CLOCK_BOOTTIME_ALARM
:
40 return CLOCK_BOOTTIME
;
42 case CLOCK_REALTIME_ALARM
:
43 return CLOCK_REALTIME
;
50 usec_t
now(clockid_t clock_id
) {
53 assert_se(clock_gettime(map_clock_id(clock_id
), &ts
) == 0);
55 return timespec_load(&ts
);
58 nsec_t
now_nsec(clockid_t clock_id
) {
61 assert_se(clock_gettime(map_clock_id(clock_id
), &ts
) == 0);
63 return timespec_load_nsec(&ts
);
66 dual_timestamp
* dual_timestamp_get(dual_timestamp
*ts
) {
69 ts
->realtime
= now(CLOCK_REALTIME
);
70 ts
->monotonic
= now(CLOCK_MONOTONIC
);
75 triple_timestamp
* triple_timestamp_get(triple_timestamp
*ts
) {
78 ts
->realtime
= now(CLOCK_REALTIME
);
79 ts
->monotonic
= now(CLOCK_MONOTONIC
);
80 ts
->boottime
= clock_boottime_supported() ? now(CLOCK_BOOTTIME
) : USEC_INFINITY
;
85 dual_timestamp
* dual_timestamp_from_realtime(dual_timestamp
*ts
, usec_t u
) {
89 if (u
== USEC_INFINITY
|| u
<= 0) {
90 ts
->realtime
= ts
->monotonic
= u
;
96 delta
= (int64_t) now(CLOCK_REALTIME
) - (int64_t) u
;
97 ts
->monotonic
= usec_sub_signed(now(CLOCK_MONOTONIC
), delta
);
102 triple_timestamp
* triple_timestamp_from_realtime(triple_timestamp
*ts
, usec_t u
) {
107 if (u
== USEC_INFINITY
|| u
<= 0) {
108 ts
->realtime
= ts
->monotonic
= ts
->boottime
= u
;
113 delta
= (int64_t) now(CLOCK_REALTIME
) - (int64_t) u
;
114 ts
->monotonic
= usec_sub_signed(now(CLOCK_MONOTONIC
), delta
);
115 ts
->boottime
= clock_boottime_supported() ? usec_sub_signed(now(CLOCK_BOOTTIME
), delta
) : USEC_INFINITY
;
120 dual_timestamp
* dual_timestamp_from_monotonic(dual_timestamp
*ts
, usec_t u
) {
124 if (u
== USEC_INFINITY
) {
125 ts
->realtime
= ts
->monotonic
= USEC_INFINITY
;
130 delta
= (int64_t) now(CLOCK_MONOTONIC
) - (int64_t) u
;
131 ts
->realtime
= usec_sub_signed(now(CLOCK_REALTIME
), delta
);
136 dual_timestamp
* dual_timestamp_from_boottime_or_monotonic(dual_timestamp
*ts
, usec_t u
) {
139 if (u
== USEC_INFINITY
) {
140 ts
->realtime
= ts
->monotonic
= USEC_INFINITY
;
144 dual_timestamp_get(ts
);
145 delta
= (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u
;
146 ts
->realtime
= usec_sub_signed(ts
->realtime
, delta
);
147 ts
->monotonic
= usec_sub_signed(ts
->monotonic
, delta
);
152 usec_t
triple_timestamp_by_clock(triple_timestamp
*ts
, clockid_t clock
) {
157 case CLOCK_REALTIME_ALARM
:
160 case CLOCK_MONOTONIC
:
161 return ts
->monotonic
;
164 case CLOCK_BOOTTIME_ALARM
:
168 return USEC_INFINITY
;
172 usec_t
timespec_load(const struct timespec
*ts
) {
175 if (ts
->tv_sec
< 0 || ts
->tv_nsec
< 0)
176 return USEC_INFINITY
;
178 if ((usec_t
) ts
->tv_sec
> (UINT64_MAX
- (ts
->tv_nsec
/ NSEC_PER_USEC
)) / USEC_PER_SEC
)
179 return USEC_INFINITY
;
182 (usec_t
) ts
->tv_sec
* USEC_PER_SEC
+
183 (usec_t
) ts
->tv_nsec
/ NSEC_PER_USEC
;
186 nsec_t
timespec_load_nsec(const struct timespec
*ts
) {
189 if (ts
->tv_sec
< 0 || ts
->tv_nsec
< 0)
190 return NSEC_INFINITY
;
192 if ((nsec_t
) ts
->tv_sec
>= (UINT64_MAX
- ts
->tv_nsec
) / NSEC_PER_SEC
)
193 return NSEC_INFINITY
;
195 return (nsec_t
) ts
->tv_sec
* NSEC_PER_SEC
+ (nsec_t
) ts
->tv_nsec
;
198 struct timespec
*timespec_store(struct timespec
*ts
, usec_t u
) {
201 if (u
== USEC_INFINITY
||
202 u
/ USEC_PER_SEC
>= TIME_T_MAX
) {
203 ts
->tv_sec
= (time_t) -1;
204 ts
->tv_nsec
= (long) -1;
208 ts
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
209 ts
->tv_nsec
= (long int) ((u
% USEC_PER_SEC
) * NSEC_PER_USEC
);
214 usec_t
timeval_load(const struct timeval
*tv
) {
217 if (tv
->tv_sec
< 0 || tv
->tv_usec
< 0)
218 return USEC_INFINITY
;
220 if ((usec_t
) tv
->tv_sec
> (UINT64_MAX
- tv
->tv_usec
) / USEC_PER_SEC
)
221 return USEC_INFINITY
;
224 (usec_t
) tv
->tv_sec
* USEC_PER_SEC
+
225 (usec_t
) tv
->tv_usec
;
228 struct timeval
*timeval_store(struct timeval
*tv
, usec_t u
) {
231 if (u
== USEC_INFINITY
||
232 u
/ USEC_PER_SEC
> TIME_T_MAX
) {
233 tv
->tv_sec
= (time_t) -1;
234 tv
->tv_usec
= (suseconds_t
) -1;
236 tv
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
237 tv
->tv_usec
= (suseconds_t
) (u
% USEC_PER_SEC
);
243 static char *format_timestamp_internal(
250 /* The weekdays in non-localized (English) form. We use this instead of the localized form, so that our
251 * generated timestamps may be parsed with parse_timestamp(), and always read the same. */
252 static const char * const weekdays
[] = {
268 if (l
< (size_t) (3 + /* week day */
269 1 + 10 + /* space and date */
270 1 + 8 + /* space and time */
271 (us
? 1 + 6 : 0) + /* "." and microsecond part */
272 1 + 1 + /* space and shortest possible zone */
274 return NULL
; /* Not enough space even for the shortest form. */
275 if (t
<= 0 || t
== USEC_INFINITY
)
276 return NULL
; /* Timestamp is unset */
278 /* Let's not format times with years > 9999 */
279 if (t
> USEC_TIMESTAMP_FORMATTABLE_MAX
) {
280 assert(l
>= STRLEN("--- XXXX-XX-XX XX:XX:XX") + 1);
281 strcpy(buf
, "--- XXXX-XX-XX XX:XX:XX");
285 sec
= (time_t) (t
/ USEC_PER_SEC
); /* Round down */
287 if (!localtime_or_gmtime_r(&sec
, &tm
, utc
))
290 /* Start with the week day */
291 assert((size_t) tm
.tm_wday
< ELEMENTSOF(weekdays
));
292 memcpy(buf
, weekdays
[tm
.tm_wday
], 4);
294 /* Add the main components */
295 if (strftime(buf
+ 3, l
- 3, " %Y-%m-%d %H:%M:%S", &tm
) <= 0)
296 return NULL
; /* Doesn't fit */
298 /* Append the microseconds part, if that's requested */
302 return NULL
; /* Microseconds part doesn't fit. */
304 sprintf(buf
+ n
, ".%06"PRI_USEC
, t
% USEC_PER_SEC
);
307 /* Append the timezone */
310 /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r() normally uses the
311 * obsolete "GMT" instead. */
313 return NULL
; /* "UTC" doesn't fit. */
315 strcpy(buf
+ n
, " UTC");
317 } else if (!isempty(tm
.tm_zone
)) {
320 /* An explicit timezone is specified, let's use it, if it fits */
321 tn
= strlen(tm
.tm_zone
);
322 if (n
+ 1 + tn
+ 1 > l
) {
323 /* The full time zone does not fit in. Yuck. */
325 if (n
+ 1 + _POSIX_TZNAME_MAX
+ 1 > l
)
326 return NULL
; /* Not even enough space for the POSIX minimum (of 6)? In that case, complain that it doesn't fit */
328 /* So the time zone doesn't fit in fully, but the caller passed enough space for the POSIX
329 * minimum time zone length. In this case suppress the timezone entirely, in order not to dump
330 * an overly long, hard to read string on the user. This should be safe, because the user will
331 * assume the local timezone anyway if none is shown. And so does parse_timestamp(). */
334 strcpy(buf
+ n
, tm
.tm_zone
);
341 char *format_timestamp(char *buf
, size_t l
, usec_t t
) {
342 return format_timestamp_internal(buf
, l
, t
, false, false);
345 char *format_timestamp_utc(char *buf
, size_t l
, usec_t t
) {
346 return format_timestamp_internal(buf
, l
, t
, true, false);
349 char *format_timestamp_us(char *buf
, size_t l
, usec_t t
) {
350 return format_timestamp_internal(buf
, l
, t
, false, true);
353 char *format_timestamp_us_utc(char *buf
, size_t l
, usec_t t
) {
354 return format_timestamp_internal(buf
, l
, t
, true, true);
357 char *format_timestamp_relative(char *buf
, size_t l
, usec_t t
) {
361 if (t
<= 0 || t
== USEC_INFINITY
)
364 n
= now(CLOCK_REALTIME
);
373 if (d
>= USEC_PER_YEAR
)
374 snprintf(buf
, l
, USEC_FMT
" years " USEC_FMT
" months %s",
376 (d
% USEC_PER_YEAR
) / USEC_PER_MONTH
, s
);
377 else if (d
>= USEC_PER_MONTH
)
378 snprintf(buf
, l
, USEC_FMT
" months " USEC_FMT
" days %s",
380 (d
% USEC_PER_MONTH
) / USEC_PER_DAY
, s
);
381 else if (d
>= USEC_PER_WEEK
)
382 snprintf(buf
, l
, USEC_FMT
" weeks " USEC_FMT
" days %s",
384 (d
% USEC_PER_WEEK
) / USEC_PER_DAY
, s
);
385 else if (d
>= 2*USEC_PER_DAY
)
386 snprintf(buf
, l
, USEC_FMT
" days %s", d
/ USEC_PER_DAY
, s
);
387 else if (d
>= 25*USEC_PER_HOUR
)
388 snprintf(buf
, l
, "1 day " USEC_FMT
"h %s",
389 (d
- USEC_PER_DAY
) / USEC_PER_HOUR
, s
);
390 else if (d
>= 6*USEC_PER_HOUR
)
391 snprintf(buf
, l
, USEC_FMT
"h %s",
392 d
/ USEC_PER_HOUR
, s
);
393 else if (d
>= USEC_PER_HOUR
)
394 snprintf(buf
, l
, USEC_FMT
"h " USEC_FMT
"min %s",
396 (d
% USEC_PER_HOUR
) / USEC_PER_MINUTE
, s
);
397 else if (d
>= 5*USEC_PER_MINUTE
)
398 snprintf(buf
, l
, USEC_FMT
"min %s",
399 d
/ USEC_PER_MINUTE
, s
);
400 else if (d
>= USEC_PER_MINUTE
)
401 snprintf(buf
, l
, USEC_FMT
"min " USEC_FMT
"s %s",
403 (d
% USEC_PER_MINUTE
) / USEC_PER_SEC
, s
);
404 else if (d
>= USEC_PER_SEC
)
405 snprintf(buf
, l
, USEC_FMT
"s %s",
406 d
/ USEC_PER_SEC
, s
);
407 else if (d
>= USEC_PER_MSEC
)
408 snprintf(buf
, l
, USEC_FMT
"ms %s",
409 d
/ USEC_PER_MSEC
, s
);
411 snprintf(buf
, l
, USEC_FMT
"us %s",
414 snprintf(buf
, l
, "now");
420 char *format_timespan(char *buf
, size_t l
, usec_t t
, usec_t accuracy
) {
421 static const struct {
425 { "y", USEC_PER_YEAR
},
426 { "month", USEC_PER_MONTH
},
427 { "w", USEC_PER_WEEK
},
428 { "d", USEC_PER_DAY
},
429 { "h", USEC_PER_HOUR
},
430 { "min", USEC_PER_MINUTE
},
431 { "s", USEC_PER_SEC
},
432 { "ms", USEC_PER_MSEC
},
438 bool something
= false;
443 if (t
== USEC_INFINITY
) {
444 strncpy(p
, "infinity", l
-1);
450 strncpy(p
, "0", l
-1);
455 /* The result of this function can be parsed with parse_sec */
457 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
466 if (t
< accuracy
&& something
)
469 if (t
< table
[i
].usec
)
475 a
= t
/ table
[i
].usec
;
476 b
= t
% table
[i
].usec
;
478 /* Let's see if we should shows this in dot notation */
479 if (t
< USEC_PER_MINUTE
&& b
> 0) {
484 for (cc
= table
[i
].usec
; cc
> 1; cc
/= 10)
487 for (cc
= accuracy
; cc
> 1; cc
/= 10) {
494 "%s"USEC_FMT
".%0*"PRI_USEC
"%s",
506 /* No? Then let's show it normally */
517 n
= MIN((size_t) k
, l
);
530 static int parse_timestamp_impl(const char *t
, usec_t
*usec
, bool with_tz
) {
531 static const struct {
551 const char *k
, *utc
= NULL
, *tzn
= NULL
;
554 usec_t x_usec
, plus
= 0, minus
= 0, ret
;
555 int r
, weekday
= -1, dst
= -1;
560 * 2012-09-22 16:34:22
561 * 2012-09-22 16:34 (seconds will be set to 0)
562 * 2012-09-22 (time will be set to 00:00:00)
563 * 16:34:22 (date will be set to today)
564 * 16:34 (date will be set to today, seconds to 0)
566 * yesterday (time is set to 00:00:00)
567 * today (time is set to 00:00:00)
568 * tomorrow (time is set to 00:00:00)
571 * @2147483647 (seconds since epoch)
576 if (t
[0] == '@' && !with_tz
)
577 return parse_sec(t
+ 1, usec
);
579 ret
= now(CLOCK_REALTIME
);
585 else if (t
[0] == '+') {
586 r
= parse_sec(t
+1, &plus
);
592 } else if (t
[0] == '-') {
593 r
= parse_sec(t
+1, &minus
);
599 } else if ((k
= endswith(t
, " ago"))) {
600 t
= strndupa(t
, k
- t
);
602 r
= parse_sec(t
, &minus
);
608 } else if ((k
= endswith(t
, " left"))) {
609 t
= strndupa(t
, k
- t
);
611 r
= parse_sec(t
, &plus
);
618 /* See if the timestamp is suffixed with UTC */
619 utc
= endswith_no_case(t
, " UTC");
621 t
= strndupa(t
, utc
- t
);
623 const char *e
= NULL
;
628 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
629 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
630 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
631 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
632 * support arbitrary timezone specifications. */
634 for (j
= 0; j
<= 1; j
++) {
636 if (isempty(tzname
[j
]))
639 e
= endswith_no_case(t
, tzname
[j
]);
650 if (IN_SET(j
, 0, 1)) {
651 /* Found one of the two timezones specified. */
652 t
= strndupa(t
, e
- t
- 1);
659 x
= (time_t) (ret
/ USEC_PER_SEC
);
662 if (!localtime_or_gmtime_r(&x
, &tm
, utc
))
669 if (streq(t
, "today")) {
670 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
673 } else if (streq(t
, "yesterday")) {
675 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
678 } else if (streq(t
, "tomorrow")) {
680 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
684 for (i
= 0; i
< ELEMENTSOF(day_nr
); i
++) {
687 if (!startswith_no_case(t
, day_nr
[i
].name
))
690 skip
= strlen(day_nr
[i
].name
);
694 weekday
= day_nr
[i
].nr
;
700 k
= strptime(t
, "%y-%m-%d %H:%M:%S", &tm
);
709 k
= strptime(t
, "%Y-%m-%d %H:%M:%S", &tm
);
718 k
= strptime(t
, "%y-%m-%d %H:%M", &tm
);
725 k
= strptime(t
, "%Y-%m-%d %H:%M", &tm
);
732 k
= strptime(t
, "%y-%m-%d", &tm
);
734 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
739 k
= strptime(t
, "%Y-%m-%d", &tm
);
741 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
746 k
= strptime(t
, "%H:%M:%S", &tm
);
755 k
= strptime(t
, "%H:%M", &tm
);
768 r
= parse_fractional_part_u(&k
, 6, &add
);
779 if (weekday
>= 0 && tm
.tm_wday
!= weekday
)
782 x
= mktime_or_timegm(&tm
, utc
);
786 ret
= (usec_t
) x
* USEC_PER_SEC
+ x_usec
;
787 if (ret
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
791 if (ret
+ plus
< ret
) /* overflow? */
794 if (ret
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
807 typedef struct ParseTimestampResult
{
810 } ParseTimestampResult
;
812 int parse_timestamp(const char *t
, usec_t
*usec
) {
813 char *last_space
, *tz
= NULL
;
814 ParseTimestampResult
*shared
, tmp
;
817 last_space
= strrchr(t
, ' ');
818 if (last_space
!= NULL
&& timezone_is_valid(last_space
+ 1, LOG_DEBUG
))
821 if (!tz
|| endswith_no_case(t
, " UTC"))
822 return parse_timestamp_impl(t
, usec
, false);
824 shared
= mmap(NULL
, sizeof *shared
, PROT_READ
|PROT_WRITE
, MAP_SHARED
|MAP_ANONYMOUS
, -1, 0);
825 if (shared
== MAP_FAILED
)
826 return negative_errno();
828 r
= safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG
|FORK_WAIT
, NULL
);
830 (void) munmap(shared
, sizeof *shared
);
836 if (setenv("TZ", tz
, 1) != 0) {
837 shared
->return_value
= negative_errno();
843 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
844 * Otherwise just cut it off. */
845 with_tz
= !STR_IN_SET(tz
, tzname
[0], tzname
[1]);
847 /* Cut off the timezone if we don't need it. */
849 t
= strndupa(t
, last_space
- t
);
851 shared
->return_value
= parse_timestamp_impl(t
, &shared
->usec
, with_tz
);
857 if (munmap(shared
, sizeof *shared
) != 0)
858 return negative_errno();
860 if (tmp
.return_value
== 0 && usec
)
863 return tmp
.return_value
;
866 static const char* extract_multiplier(const char *p
, usec_t
*multiplier
) {
867 static const struct {
871 { "seconds", USEC_PER_SEC
},
872 { "second", USEC_PER_SEC
},
873 { "sec", USEC_PER_SEC
},
874 { "s", USEC_PER_SEC
},
875 { "minutes", USEC_PER_MINUTE
},
876 { "minute", USEC_PER_MINUTE
},
877 { "min", USEC_PER_MINUTE
},
878 { "months", USEC_PER_MONTH
},
879 { "month", USEC_PER_MONTH
},
880 { "M", USEC_PER_MONTH
},
881 { "msec", USEC_PER_MSEC
},
882 { "ms", USEC_PER_MSEC
},
883 { "m", USEC_PER_MINUTE
},
884 { "hours", USEC_PER_HOUR
},
885 { "hour", USEC_PER_HOUR
},
886 { "hr", USEC_PER_HOUR
},
887 { "h", USEC_PER_HOUR
},
888 { "days", USEC_PER_DAY
},
889 { "day", USEC_PER_DAY
},
890 { "d", USEC_PER_DAY
},
891 { "weeks", USEC_PER_WEEK
},
892 { "week", USEC_PER_WEEK
},
893 { "w", USEC_PER_WEEK
},
894 { "years", USEC_PER_YEAR
},
895 { "year", USEC_PER_YEAR
},
896 { "y", USEC_PER_YEAR
},
903 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
906 e
= startswith(p
, table
[i
].suffix
);
908 *multiplier
= table
[i
].usec
;
916 int parse_time(const char *t
, usec_t
*usec
, usec_t default_unit
) {
919 bool something
= false;
922 assert(default_unit
> 0);
926 p
+= strspn(p
, WHITESPACE
);
927 s
= startswith(p
, "infinity");
929 s
+= strspn(s
, WHITESPACE
);
934 *usec
= USEC_INFINITY
;
939 usec_t multiplier
= default_unit
, k
;
943 p
+= strspn(p
, WHITESPACE
);
952 if (*p
== '-') /* Don't allow "-0" */
956 l
= strtoll(p
, &e
, 10);
964 p
+= strspn(p
, DIGITS
);
970 s
= extract_multiplier(p
+ strspn(p
, WHITESPACE
), &multiplier
);
971 if (s
== p
&& *s
!= '\0')
972 /* Don't allow '12.34.56', but accept '12.34 .56' or '12.34s.56'*/
977 if ((usec_t
) l
>= USEC_INFINITY
/ multiplier
)
980 k
= (usec_t
) l
* multiplier
;
981 if (k
>= USEC_INFINITY
- r
)
989 usec_t m
= multiplier
/ 10;
992 for (b
= e
+ 1; *b
>= '0' && *b
<= '9'; b
++, m
/= 10) {
993 k
= (usec_t
) (*b
- '0') * m
;
994 if (k
>= USEC_INFINITY
- r
)
1000 /* Don't allow "0.-0", "3.+1", "3. 1", "3.sec" or "3.hoge"*/
1011 int parse_sec(const char *t
, usec_t
*usec
) {
1012 return parse_time(t
, usec
, USEC_PER_SEC
);
1015 int parse_sec_fix_0(const char *t
, usec_t
*ret
) {
1022 r
= parse_sec(t
, &k
);
1026 *ret
= k
== 0 ? USEC_INFINITY
: k
;
1030 int parse_sec_def_infinity(const char *t
, usec_t
*ret
) {
1031 t
+= strspn(t
, WHITESPACE
);
1033 *ret
= USEC_INFINITY
;
1036 return parse_sec(t
, ret
);
1039 static const char* extract_nsec_multiplier(const char *p
, nsec_t
*multiplier
) {
1040 static const struct {
1044 { "seconds", NSEC_PER_SEC
},
1045 { "second", NSEC_PER_SEC
},
1046 { "sec", NSEC_PER_SEC
},
1047 { "s", NSEC_PER_SEC
},
1048 { "minutes", NSEC_PER_MINUTE
},
1049 { "minute", NSEC_PER_MINUTE
},
1050 { "min", NSEC_PER_MINUTE
},
1051 { "months", NSEC_PER_MONTH
},
1052 { "month", NSEC_PER_MONTH
},
1053 { "M", NSEC_PER_MONTH
},
1054 { "msec", NSEC_PER_MSEC
},
1055 { "ms", NSEC_PER_MSEC
},
1056 { "m", NSEC_PER_MINUTE
},
1057 { "hours", NSEC_PER_HOUR
},
1058 { "hour", NSEC_PER_HOUR
},
1059 { "hr", NSEC_PER_HOUR
},
1060 { "h", NSEC_PER_HOUR
},
1061 { "days", NSEC_PER_DAY
},
1062 { "day", NSEC_PER_DAY
},
1063 { "d", NSEC_PER_DAY
},
1064 { "weeks", NSEC_PER_WEEK
},
1065 { "week", NSEC_PER_WEEK
},
1066 { "w", NSEC_PER_WEEK
},
1067 { "years", NSEC_PER_YEAR
},
1068 { "year", NSEC_PER_YEAR
},
1069 { "y", NSEC_PER_YEAR
},
1070 { "usec", NSEC_PER_USEC
},
1071 { "us", NSEC_PER_USEC
},
1072 { "µs", NSEC_PER_USEC
},
1075 { "", 1ULL }, /* default is nsec */
1079 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
1082 e
= startswith(p
, table
[i
].suffix
);
1084 *multiplier
= table
[i
].nsec
;
1092 int parse_nsec(const char *t
, nsec_t
*nsec
) {
1095 bool something
= false;
1102 p
+= strspn(p
, WHITESPACE
);
1103 s
= startswith(p
, "infinity");
1105 s
+= strspn(s
, WHITESPACE
);
1109 *nsec
= NSEC_INFINITY
;
1114 nsec_t multiplier
= 1, k
;
1118 p
+= strspn(p
, WHITESPACE
);
1127 if (*p
== '-') /* Don't allow "-0" */
1131 l
= strtoll(p
, &e
, 10);
1139 p
+= strspn(p
, DIGITS
);
1145 s
= extract_nsec_multiplier(p
+ strspn(p
, WHITESPACE
), &multiplier
);
1146 if (s
== p
&& *s
!= '\0')
1147 /* Don't allow '12.34.56', but accept '12.34 .56' or '12.34s.56'*/
1152 if ((nsec_t
) l
>= NSEC_INFINITY
/ multiplier
)
1155 k
= (nsec_t
) l
* multiplier
;
1156 if (k
>= NSEC_INFINITY
- r
)
1164 nsec_t m
= multiplier
/ 10;
1167 for (b
= e
+ 1; *b
>= '0' && *b
<= '9'; b
++, m
/= 10) {
1168 k
= (nsec_t
) (*b
- '0') * m
;
1169 if (k
>= NSEC_INFINITY
- r
)
1175 /* Don't allow "0.-0", "3.+1", "3. 1", "3.sec" or "3.hoge"*/
1186 bool ntp_synced(void) {
1187 struct timex txc
= {};
1189 if (adjtimex(&txc
) < 0)
1192 /* Consider the system clock synchronized if the reported maximum error is smaller than the maximum
1193 * value (16 seconds). Ignore the STA_UNSYNC flag as it may have been set to prevent the kernel from
1194 * touching the RTC. */
1195 if (txc
.maxerror
>= 16000000)
1201 int get_timezones(char ***ret
) {
1202 _cleanup_fclose_
FILE *f
= NULL
;
1203 _cleanup_strv_free_
char **zones
= NULL
;
1204 size_t n_zones
= 0, n_allocated
= 0;
1209 zones
= strv_new("UTC");
1216 f
= fopen("/usr/share/zoneinfo/zone1970.tab", "re");
1219 _cleanup_free_
char *line
= NULL
;
1223 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1231 if (isempty(p
) || *p
== '#')
1234 /* Skip over country code */
1235 p
+= strcspn(p
, WHITESPACE
);
1236 p
+= strspn(p
, WHITESPACE
);
1238 /* Skip over coordinates */
1239 p
+= strcspn(p
, WHITESPACE
);
1240 p
+= strspn(p
, WHITESPACE
);
1242 /* Found timezone name */
1243 k
= strcspn(p
, WHITESPACE
);
1251 if (!GREEDY_REALLOC(zones
, n_allocated
, n_zones
+ 2)) {
1256 zones
[n_zones
++] = w
;
1257 zones
[n_zones
] = NULL
;
1262 } else if (errno
!= ENOENT
)
1265 *ret
= TAKE_PTR(zones
);
1270 bool timezone_is_valid(const char *name
, int log_level
) {
1273 _cleanup_close_
int fd
= -1;
1283 for (p
= name
; *p
; p
++) {
1284 if (!(*p
>= '0' && *p
<= '9') &&
1285 !(*p
>= 'a' && *p
<= 'z') &&
1286 !(*p
>= 'A' && *p
<= 'Z') &&
1287 !IN_SET(*p
, '-', '_', '+', '/'))
1303 if (p
- name
>= PATH_MAX
)
1306 t
= strjoina("/usr/share/zoneinfo/", name
);
1308 fd
= open(t
, O_RDONLY
|O_CLOEXEC
);
1310 log_full_errno(log_level
, errno
, "Failed to open timezone file '%s': %m", t
);
1314 r
= fd_verify_regular(fd
);
1316 log_full_errno(log_level
, r
, "Timezone file '%s' is not a regular file: %m", t
);
1320 r
= loop_read_exact(fd
, buf
, 4, false);
1322 log_full_errno(log_level
, r
, "Failed to read from timezone file '%s': %m", t
);
1326 /* Magic from tzfile(5) */
1327 if (memcmp(buf
, "TZif", 4) != 0) {
1328 log_full(log_level
, "Timezone file '%s' has wrong magic bytes", t
);
1335 bool clock_boottime_supported(void) {
1336 static int supported
= -1;
1338 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1340 if (supported
< 0) {
1343 fd
= timerfd_create(CLOCK_BOOTTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
1355 clockid_t
clock_boottime_or_monotonic(void) {
1356 if (clock_boottime_supported())
1357 return CLOCK_BOOTTIME
;
1359 return CLOCK_MONOTONIC
;
1362 bool clock_supported(clockid_t clock
) {
1367 case CLOCK_MONOTONIC
:
1368 case CLOCK_REALTIME
:
1371 case CLOCK_BOOTTIME
:
1372 return clock_boottime_supported();
1374 case CLOCK_BOOTTIME_ALARM
:
1375 if (!clock_boottime_supported())
1380 /* For everything else, check properly */
1381 return clock_gettime(clock
, &ts
) >= 0;
1385 int get_timezone(char **tz
) {
1386 _cleanup_free_
char *t
= NULL
;
1391 r
= readlink_malloc("/etc/localtime", &t
);
1393 return r
; /* returns EINVAL if not a symlink */
1395 e
= PATH_STARTSWITH_SET(t
, "/usr/share/zoneinfo/", "../usr/share/zoneinfo/");
1399 if (!timezone_is_valid(e
, LOG_DEBUG
))
1410 time_t mktime_or_timegm(struct tm
*tm
, bool utc
) {
1411 return utc
? timegm(tm
) : mktime(tm
);
1414 struct tm
*localtime_or_gmtime_r(const time_t *t
, struct tm
*tm
, bool utc
) {
1415 return utc
? gmtime_r(t
, tm
) : localtime_r(t
, tm
);
1418 static uint32_t sysconf_clock_ticks_cached(void) {
1419 static thread_local
uint32_t hz
= 0;
1423 r
= sysconf(_SC_CLK_TCK
);
1432 uint32_t usec_to_jiffies(usec_t u
) {
1433 uint32_t hz
= sysconf_clock_ticks_cached();
1434 return DIV_ROUND_UP(u
, USEC_PER_SEC
/ hz
);
1437 usec_t
jiffies_to_usec(uint32_t j
) {
1438 uint32_t hz
= sysconf_clock_ticks_cached();
1439 return DIV_ROUND_UP(j
* USEC_PER_SEC
, hz
);
1442 usec_t
usec_shift_clock(usec_t x
, clockid_t from
, clockid_t to
) {
1445 if (x
== USEC_INFINITY
)
1446 return USEC_INFINITY
;
1447 if (map_clock_id(from
) == map_clock_id(to
))
1454 /* x lies in the future */
1455 return usec_add(b
, usec_sub_unsigned(x
, a
));
1457 /* x lies in the past */
1458 return usec_sub_unsigned(b
, usec_sub_unsigned(a
, x
));
1461 bool in_utc_timezone(void) {
1464 return timezone
== 0 && daylight
== 0;
1467 int time_change_fd(void) {
1469 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1470 static const struct itimerspec its
= {
1471 .it_value
.tv_sec
= TIME_T_MAX
,
1474 _cleanup_close_
int fd
;
1476 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX
));
1478 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1479 * CLOCK_MONOTONIC. */
1481 fd
= timerfd_create(CLOCK_REALTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
1485 if (timerfd_settime(fd
, TFD_TIMER_ABSTIME
|TFD_TIMER_CANCEL_ON_SET
, &its
, NULL
) < 0)