1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/timerfd.h>
11 #include <sys/timex.h>
12 #include <sys/types.h>
15 #include "alloc-util.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
[] = {
270 1 + 10 + /* space and date */
271 1 + 8 + /* space and time */
272 (us
? 1 + 6 : 0) + /* "." and microsecond part */
273 1 + 1 + /* space and shortest possible zone */
275 return NULL
; /* Not enough space even for the shortest form. */
276 if (t
<= 0 || t
== USEC_INFINITY
)
277 return NULL
; /* Timestamp is unset */
279 /* Let's not format times with years > 9999 */
280 if (t
> USEC_TIMESTAMP_FORMATTABLE_MAX
) {
281 assert(l
>= strlen("--- XXXX-XX-XX XX:XX:XX") + 1);
282 strcpy(buf
, "--- XXXX-XX-XX XX:XX:XX");
286 sec
= (time_t) (t
/ USEC_PER_SEC
); /* Round down */
288 if (!localtime_or_gmtime_r(&sec
, &tm
, utc
))
291 /* Start with the week day */
292 assert((size_t) tm
.tm_wday
< ELEMENTSOF(weekdays
));
293 memcpy(buf
, weekdays
[tm
.tm_wday
], 4);
295 /* Add the main components */
296 if (strftime(buf
+ 3, l
- 3, " %Y-%m-%d %H:%M:%S", &tm
) <= 0)
297 return NULL
; /* Doesn't fit */
299 /* Append the microseconds part, if that's requested */
303 return NULL
; /* Microseconds part doesn't fit. */
305 sprintf(buf
+ n
, ".%06"PRI_USEC
, t
% USEC_PER_SEC
);
308 /* Append the timezone */
311 /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r() normally uses the
312 * obsolete "GMT" instead. */
314 return NULL
; /* "UTC" doesn't fit. */
316 strcpy(buf
+ n
, " UTC");
318 } else if (!isempty(tm
.tm_zone
)) {
321 /* An explicit timezone is specified, let's use it, if it fits */
322 tn
= strlen(tm
.tm_zone
);
323 if (n
+ 1 + tn
+ 1 > l
) {
324 /* The full time zone does not fit in. Yuck. */
326 if (n
+ 1 + _POSIX_TZNAME_MAX
+ 1 > l
)
327 return NULL
; /* Not even enough space for the POSIX minimum (of 6)? In that case, complain that it doesn't fit */
329 /* So the time zone doesn't fit in fully, but the caller passed enough space for the POSIX
330 * minimum time zone length. In this case suppress the timezone entirely, in order not to dump
331 * an overly long, hard to read string on the user. This should be safe, because the user will
332 * assume the local timezone anyway if none is shown. And so does parse_timestamp(). */
335 strcpy(buf
+ n
, tm
.tm_zone
);
342 char *format_timestamp(char *buf
, size_t l
, usec_t t
) {
343 return format_timestamp_internal(buf
, l
, t
, false, false);
346 char *format_timestamp_utc(char *buf
, size_t l
, usec_t t
) {
347 return format_timestamp_internal(buf
, l
, t
, true, false);
350 char *format_timestamp_us(char *buf
, size_t l
, usec_t t
) {
351 return format_timestamp_internal(buf
, l
, t
, false, true);
354 char *format_timestamp_us_utc(char *buf
, size_t l
, usec_t t
) {
355 return format_timestamp_internal(buf
, l
, t
, true, true);
358 char *format_timestamp_relative(char *buf
, size_t l
, usec_t t
) {
362 if (t
<= 0 || t
== USEC_INFINITY
)
365 n
= now(CLOCK_REALTIME
);
374 if (d
>= USEC_PER_YEAR
)
375 snprintf(buf
, l
, USEC_FMT
" years " USEC_FMT
" months %s",
377 (d
% USEC_PER_YEAR
) / USEC_PER_MONTH
, s
);
378 else if (d
>= USEC_PER_MONTH
)
379 snprintf(buf
, l
, USEC_FMT
" months " USEC_FMT
" days %s",
381 (d
% USEC_PER_MONTH
) / USEC_PER_DAY
, s
);
382 else if (d
>= USEC_PER_WEEK
)
383 snprintf(buf
, l
, USEC_FMT
" weeks " USEC_FMT
" days %s",
385 (d
% USEC_PER_WEEK
) / USEC_PER_DAY
, s
);
386 else if (d
>= 2*USEC_PER_DAY
)
387 snprintf(buf
, l
, USEC_FMT
" days %s", d
/ USEC_PER_DAY
, s
);
388 else if (d
>= 25*USEC_PER_HOUR
)
389 snprintf(buf
, l
, "1 day " USEC_FMT
"h %s",
390 (d
- USEC_PER_DAY
) / USEC_PER_HOUR
, s
);
391 else if (d
>= 6*USEC_PER_HOUR
)
392 snprintf(buf
, l
, USEC_FMT
"h %s",
393 d
/ USEC_PER_HOUR
, s
);
394 else if (d
>= USEC_PER_HOUR
)
395 snprintf(buf
, l
, USEC_FMT
"h " USEC_FMT
"min %s",
397 (d
% USEC_PER_HOUR
) / USEC_PER_MINUTE
, s
);
398 else if (d
>= 5*USEC_PER_MINUTE
)
399 snprintf(buf
, l
, USEC_FMT
"min %s",
400 d
/ USEC_PER_MINUTE
, s
);
401 else if (d
>= USEC_PER_MINUTE
)
402 snprintf(buf
, l
, USEC_FMT
"min " USEC_FMT
"s %s",
404 (d
% USEC_PER_MINUTE
) / USEC_PER_SEC
, s
);
405 else if (d
>= USEC_PER_SEC
)
406 snprintf(buf
, l
, USEC_FMT
"s %s",
407 d
/ USEC_PER_SEC
, s
);
408 else if (d
>= USEC_PER_MSEC
)
409 snprintf(buf
, l
, USEC_FMT
"ms %s",
410 d
/ USEC_PER_MSEC
, s
);
412 snprintf(buf
, l
, USEC_FMT
"us %s",
415 snprintf(buf
, l
, "now");
421 char *format_timespan(char *buf
, size_t l
, usec_t t
, usec_t accuracy
) {
422 static const struct {
426 { "y", USEC_PER_YEAR
},
427 { "month", USEC_PER_MONTH
},
428 { "w", USEC_PER_WEEK
},
429 { "d", USEC_PER_DAY
},
430 { "h", USEC_PER_HOUR
},
431 { "min", USEC_PER_MINUTE
},
432 { "s", USEC_PER_SEC
},
433 { "ms", USEC_PER_MSEC
},
439 bool something
= false;
444 if (t
== USEC_INFINITY
) {
445 strncpy(p
, "infinity", l
-1);
451 strncpy(p
, "0", l
-1);
456 /* The result of this function can be parsed with parse_sec */
458 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
467 if (t
< accuracy
&& something
)
470 if (t
< table
[i
].usec
)
476 a
= t
/ table
[i
].usec
;
477 b
= t
% table
[i
].usec
;
479 /* Let's see if we should shows this in dot notation */
480 if (t
< USEC_PER_MINUTE
&& b
> 0) {
485 for (cc
= table
[i
].usec
; cc
> 1; cc
/= 10)
488 for (cc
= accuracy
; cc
> 1; cc
/= 10) {
495 "%s"USEC_FMT
".%0*"PRI_USEC
"%s",
507 /* No? Then let's show it normally */
518 n
= MIN((size_t) k
, l
);
531 void dual_timestamp_serialize(FILE *f
, const char *name
, dual_timestamp
*t
) {
537 if (!dual_timestamp_is_set(t
))
540 fprintf(f
, "%s="USEC_FMT
" "USEC_FMT
"\n",
546 int dual_timestamp_deserialize(const char *value
, dual_timestamp
*t
) {
553 pos
= strspn(value
, WHITESPACE
);
554 if (value
[pos
] == '-')
556 pos
+= strspn(value
+ pos
, DIGITS
);
557 pos
+= strspn(value
+ pos
, WHITESPACE
);
558 if (value
[pos
] == '-')
561 r
= sscanf(value
, "%" PRIu64
"%" PRIu64
"%n", &a
, &b
, &pos
);
563 log_debug("Failed to parse dual timestamp value \"%s\".", value
);
567 if (value
[pos
] != '\0')
568 /* trailing garbage */
577 int timestamp_deserialize(const char *value
, usec_t
*timestamp
) {
582 r
= safe_atou64(value
, timestamp
);
584 return log_debug_errno(r
, "Failed to parse timestamp value \"%s\": %m", value
);
589 static int parse_timestamp_impl(const char *t
, usec_t
*usec
, bool with_tz
) {
590 static const struct {
610 const char *k
, *utc
= NULL
, *tzn
= NULL
;
613 usec_t x_usec
, plus
= 0, minus
= 0, ret
;
614 int r
, weekday
= -1, dst
= -1;
619 * 2012-09-22 16:34:22
620 * 2012-09-22 16:34 (seconds will be set to 0)
621 * 2012-09-22 (time will be set to 00:00:00)
622 * 16:34:22 (date will be set to today)
623 * 16:34 (date will be set to today, seconds to 0)
625 * yesterday (time is set to 00:00:00)
626 * today (time is set to 00:00:00)
627 * tomorrow (time is set to 00:00:00)
630 * @2147483647 (seconds since epoch)
636 if (t
[0] == '@' && !with_tz
)
637 return parse_sec(t
+ 1, usec
);
639 ret
= now(CLOCK_REALTIME
);
645 else if (t
[0] == '+') {
646 r
= parse_sec(t
+1, &plus
);
652 } else if (t
[0] == '-') {
653 r
= parse_sec(t
+1, &minus
);
659 } else if ((k
= endswith(t
, " ago"))) {
660 t
= strndupa(t
, k
- t
);
662 r
= parse_sec(t
, &minus
);
668 } else if ((k
= endswith(t
, " left"))) {
669 t
= strndupa(t
, k
- t
);
671 r
= parse_sec(t
, &plus
);
678 /* See if the timestamp is suffixed with UTC */
679 utc
= endswith_no_case(t
, " UTC");
681 t
= strndupa(t
, utc
- t
);
683 const char *e
= NULL
;
688 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
689 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
690 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
691 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
692 * support arbitrary timezone specifications. */
694 for (j
= 0; j
<= 1; j
++) {
696 if (isempty(tzname
[j
]))
699 e
= endswith_no_case(t
, tzname
[j
]);
710 if (IN_SET(j
, 0, 1)) {
711 /* Found one of the two timezones specified. */
712 t
= strndupa(t
, e
- t
- 1);
719 x
= (time_t) (ret
/ USEC_PER_SEC
);
722 if (!localtime_or_gmtime_r(&x
, &tm
, utc
))
729 if (streq(t
, "today")) {
730 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
733 } else if (streq(t
, "yesterday")) {
735 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
738 } else if (streq(t
, "tomorrow")) {
740 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
744 for (i
= 0; i
< ELEMENTSOF(day_nr
); i
++) {
747 if (!startswith_no_case(t
, day_nr
[i
].name
))
750 skip
= strlen(day_nr
[i
].name
);
754 weekday
= day_nr
[i
].nr
;
760 k
= strptime(t
, "%y-%m-%d %H:%M:%S", &tm
);
769 k
= strptime(t
, "%Y-%m-%d %H:%M:%S", &tm
);
778 k
= strptime(t
, "%y-%m-%d %H:%M", &tm
);
785 k
= strptime(t
, "%Y-%m-%d %H:%M", &tm
);
792 k
= strptime(t
, "%y-%m-%d", &tm
);
794 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
799 k
= strptime(t
, "%Y-%m-%d", &tm
);
801 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
806 k
= strptime(t
, "%H:%M:%S", &tm
);
815 k
= strptime(t
, "%H:%M", &tm
);
828 r
= parse_fractional_part_u(&k
, 6, &add
);
839 if (weekday
>= 0 && tm
.tm_wday
!= weekday
)
842 x
= mktime_or_timegm(&tm
, utc
);
846 ret
= (usec_t
) x
* USEC_PER_SEC
+ x_usec
;
847 if (ret
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
851 if (ret
+ plus
< ret
) /* overflow? */
854 if (ret
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
867 typedef struct ParseTimestampResult
{
870 } ParseTimestampResult
;
872 int parse_timestamp(const char *t
, usec_t
*usec
) {
873 char *last_space
, *tz
= NULL
;
874 ParseTimestampResult
*shared
, tmp
;
877 last_space
= strrchr(t
, ' ');
878 if (last_space
!= NULL
&& timezone_is_valid(last_space
+ 1, LOG_DEBUG
))
881 if (!tz
|| endswith_no_case(t
, " UTC"))
882 return parse_timestamp_impl(t
, usec
, false);
884 shared
= mmap(NULL
, sizeof *shared
, PROT_READ
|PROT_WRITE
, MAP_SHARED
|MAP_ANONYMOUS
, -1, 0);
885 if (shared
== MAP_FAILED
)
886 return negative_errno();
888 r
= safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG
|FORK_WAIT
, NULL
);
890 (void) munmap(shared
, sizeof *shared
);
896 if (setenv("TZ", tz
, 1) != 0) {
897 shared
->return_value
= negative_errno();
903 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
904 * Otherwise just cut it off. */
905 with_tz
= !STR_IN_SET(tz
, tzname
[0], tzname
[1]);
907 /* Cut off the timezone if we dont need it. */
909 t
= strndupa(t
, last_space
- t
);
911 shared
->return_value
= parse_timestamp_impl(t
, &shared
->usec
, with_tz
);
917 if (munmap(shared
, sizeof *shared
) != 0)
918 return negative_errno();
920 if (tmp
.return_value
== 0)
923 return tmp
.return_value
;
926 static char* extract_multiplier(char *p
, usec_t
*multiplier
) {
927 static const struct {
931 { "seconds", USEC_PER_SEC
},
932 { "second", USEC_PER_SEC
},
933 { "sec", USEC_PER_SEC
},
934 { "s", USEC_PER_SEC
},
935 { "minutes", USEC_PER_MINUTE
},
936 { "minute", USEC_PER_MINUTE
},
937 { "min", USEC_PER_MINUTE
},
938 { "months", USEC_PER_MONTH
},
939 { "month", USEC_PER_MONTH
},
940 { "M", USEC_PER_MONTH
},
941 { "msec", USEC_PER_MSEC
},
942 { "ms", USEC_PER_MSEC
},
943 { "m", USEC_PER_MINUTE
},
944 { "hours", USEC_PER_HOUR
},
945 { "hour", USEC_PER_HOUR
},
946 { "hr", USEC_PER_HOUR
},
947 { "h", USEC_PER_HOUR
},
948 { "days", USEC_PER_DAY
},
949 { "day", USEC_PER_DAY
},
950 { "d", USEC_PER_DAY
},
951 { "weeks", USEC_PER_WEEK
},
952 { "week", USEC_PER_WEEK
},
953 { "w", USEC_PER_WEEK
},
954 { "years", USEC_PER_YEAR
},
955 { "year", USEC_PER_YEAR
},
956 { "y", USEC_PER_YEAR
},
963 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
966 e
= startswith(p
, table
[i
].suffix
);
968 *multiplier
= table
[i
].usec
;
976 int parse_time(const char *t
, usec_t
*usec
, usec_t default_unit
) {
979 bool something
= false;
983 assert(default_unit
> 0);
987 p
+= strspn(p
, WHITESPACE
);
988 s
= startswith(p
, "infinity");
990 s
+= strspn(s
, WHITESPACE
);
994 *usec
= USEC_INFINITY
;
1002 usec_t multiplier
= default_unit
, k
;
1004 p
+= strspn(p
, WHITESPACE
);
1014 l
= strtoll(p
, &e
, 10);
1024 z
= strtoll(b
, &e
, 10);
1039 e
+= strspn(e
, WHITESPACE
);
1040 p
= extract_multiplier(e
, &multiplier
);
1044 k
= (usec_t
) z
* multiplier
;
1049 r
+= (usec_t
) l
* multiplier
+ k
;
1057 int parse_sec(const char *t
, usec_t
*usec
) {
1058 return parse_time(t
, usec
, USEC_PER_SEC
);
1061 int parse_sec_fix_0(const char *t
, usec_t
*usec
) {
1065 t
+= strspn(t
, WHITESPACE
);
1067 if (streq(t
, "0")) {
1068 *usec
= USEC_INFINITY
;
1072 return parse_sec(t
, usec
);
1075 int parse_nsec(const char *t
, nsec_t
*nsec
) {
1076 static const struct {
1080 { "seconds", NSEC_PER_SEC
},
1081 { "second", NSEC_PER_SEC
},
1082 { "sec", NSEC_PER_SEC
},
1083 { "s", NSEC_PER_SEC
},
1084 { "minutes", NSEC_PER_MINUTE
},
1085 { "minute", NSEC_PER_MINUTE
},
1086 { "min", NSEC_PER_MINUTE
},
1087 { "months", NSEC_PER_MONTH
},
1088 { "month", NSEC_PER_MONTH
},
1089 { "msec", NSEC_PER_MSEC
},
1090 { "ms", NSEC_PER_MSEC
},
1091 { "m", NSEC_PER_MINUTE
},
1092 { "hours", NSEC_PER_HOUR
},
1093 { "hour", NSEC_PER_HOUR
},
1094 { "hr", NSEC_PER_HOUR
},
1095 { "h", NSEC_PER_HOUR
},
1096 { "days", NSEC_PER_DAY
},
1097 { "day", NSEC_PER_DAY
},
1098 { "d", NSEC_PER_DAY
},
1099 { "weeks", NSEC_PER_WEEK
},
1100 { "week", NSEC_PER_WEEK
},
1101 { "w", NSEC_PER_WEEK
},
1102 { "years", NSEC_PER_YEAR
},
1103 { "year", NSEC_PER_YEAR
},
1104 { "y", NSEC_PER_YEAR
},
1105 { "usec", NSEC_PER_USEC
},
1106 { "us", NSEC_PER_USEC
},
1107 { "µs", NSEC_PER_USEC
},
1110 { "", 1ULL }, /* default is nsec */
1115 bool something
= false;
1122 p
+= strspn(p
, WHITESPACE
);
1123 s
= startswith(p
, "infinity");
1125 s
+= strspn(s
, WHITESPACE
);
1129 *nsec
= NSEC_INFINITY
;
1138 p
+= strspn(p
, WHITESPACE
);
1148 l
= strtoll(p
, &e
, 10);
1160 z
= strtoll(b
, &e
, 10);
1175 e
+= strspn(e
, WHITESPACE
);
1177 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
1178 if (startswith(e
, table
[i
].suffix
)) {
1179 nsec_t k
= (nsec_t
) z
* table
[i
].nsec
;
1184 r
+= (nsec_t
) l
* table
[i
].nsec
+ k
;
1185 p
= e
+ strlen(table
[i
].suffix
);
1191 if (i
>= ELEMENTSOF(table
))
1201 bool ntp_synced(void) {
1202 struct timex txc
= {};
1204 if (adjtimex(&txc
) < 0)
1207 if (txc
.status
& STA_UNSYNC
)
1213 int get_timezones(char ***ret
) {
1214 _cleanup_fclose_
FILE *f
= NULL
;
1215 _cleanup_strv_free_
char **zones
= NULL
;
1216 size_t n_zones
= 0, n_allocated
= 0;
1220 zones
= strv_new("UTC", NULL
);
1227 f
= fopen("/usr/share/zoneinfo/zone.tab", "re");
1231 FOREACH_LINE(l
, f
, return -errno
) {
1237 if (isempty(p
) || *p
== '#')
1240 /* Skip over country code */
1241 p
+= strcspn(p
, WHITESPACE
);
1242 p
+= strspn(p
, WHITESPACE
);
1244 /* Skip over coordinates */
1245 p
+= strcspn(p
, WHITESPACE
);
1246 p
+= strspn(p
, WHITESPACE
);
1248 /* Found timezone name */
1249 k
= strcspn(p
, WHITESPACE
);
1257 if (!GREEDY_REALLOC(zones
, n_allocated
, n_zones
+ 2)) {
1262 zones
[n_zones
++] = w
;
1263 zones
[n_zones
] = NULL
;
1268 } else if (errno
!= ENOENT
)
1271 *ret
= TAKE_PTR(zones
);
1276 bool timezone_is_valid(const char *name
, int log_level
) {
1279 _cleanup_close_
int fd
= -1;
1289 for (p
= name
; *p
; p
++) {
1290 if (!(*p
>= '0' && *p
<= '9') &&
1291 !(*p
>= 'a' && *p
<= 'z') &&
1292 !(*p
>= 'A' && *p
<= 'Z') &&
1293 !IN_SET(*p
, '-', '_', '+', '/'))
1309 if (p
- name
>= PATH_MAX
)
1312 t
= strjoina("/usr/share/zoneinfo/", name
);
1314 fd
= open(t
, O_RDONLY
|O_CLOEXEC
);
1316 log_full_errno(log_level
, errno
, "Failed to open timezone file '%s': %m", t
);
1320 r
= fd_verify_regular(fd
);
1322 log_full_errno(log_level
, r
, "Timezone file '%s' is not a regular file: %m", t
);
1326 r
= loop_read_exact(fd
, buf
, 4, false);
1328 log_full_errno(log_level
, r
, "Failed to read from timezone file '%s': %m", t
);
1332 /* Magic from tzfile(5) */
1333 if (memcmp(buf
, "TZif", 4) != 0) {
1334 log_full(log_level
, "Timezone file '%s' has wrong magic bytes", t
);
1341 bool clock_boottime_supported(void) {
1342 static int supported
= -1;
1344 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1346 if (supported
< 0) {
1349 fd
= timerfd_create(CLOCK_BOOTTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
1361 clockid_t
clock_boottime_or_monotonic(void) {
1362 if (clock_boottime_supported())
1363 return CLOCK_BOOTTIME
;
1365 return CLOCK_MONOTONIC
;
1368 bool clock_supported(clockid_t clock
) {
1373 case CLOCK_MONOTONIC
:
1374 case CLOCK_REALTIME
:
1377 case CLOCK_BOOTTIME
:
1378 return clock_boottime_supported();
1380 case CLOCK_BOOTTIME_ALARM
:
1381 if (!clock_boottime_supported())
1386 /* For everything else, check properly */
1387 return clock_gettime(clock
, &ts
) >= 0;
1391 int get_timezone(char **tz
) {
1392 _cleanup_free_
char *t
= NULL
;
1397 r
= readlink_malloc("/etc/localtime", &t
);
1399 return r
; /* returns EINVAL if not a symlink */
1401 e
= path_startswith(t
, "/usr/share/zoneinfo/");
1403 e
= path_startswith(t
, "../usr/share/zoneinfo/");
1407 if (!timezone_is_valid(e
, LOG_DEBUG
))
1418 time_t mktime_or_timegm(struct tm
*tm
, bool utc
) {
1419 return utc
? timegm(tm
) : mktime(tm
);
1422 struct tm
*localtime_or_gmtime_r(const time_t *t
, struct tm
*tm
, bool utc
) {
1423 return utc
? gmtime_r(t
, tm
) : localtime_r(t
, tm
);
1426 unsigned long usec_to_jiffies(usec_t u
) {
1427 static thread_local
unsigned long hz
= 0;
1431 r
= sysconf(_SC_CLK_TCK
);
1437 return DIV_ROUND_UP(u
, USEC_PER_SEC
/ hz
);
1440 usec_t
usec_shift_clock(usec_t x
, clockid_t from
, clockid_t to
) {
1443 if (x
== USEC_INFINITY
)
1444 return USEC_INFINITY
;
1445 if (map_clock_id(from
) == map_clock_id(to
))
1452 /* x lies in the future */
1453 return usec_add(b
, usec_sub_unsigned(x
, a
));
1455 /* x lies in the past */
1456 return usec_sub_unsigned(b
, usec_sub_unsigned(a
, x
));
1459 bool in_utc_timezone(void) {
1462 return timezone
== 0 && daylight
== 0;
1465 int time_change_fd(void) {
1467 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1468 static const struct itimerspec its
= {
1469 .it_value
.tv_sec
= TIME_T_MAX
,
1472 _cleanup_close_
int fd
;
1474 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX
));
1476 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1477 * CLOCK_MONOTONIC. */
1479 fd
= timerfd_create(CLOCK_REALTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
1483 if (timerfd_settime(fd
, TFD_TIMER_ABSTIME
|TFD_TIMER_CANCEL_ON_SET
, &its
, NULL
) < 0)