1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2010 Lennart Poettering
13 #include <sys/timerfd.h>
14 #include <sys/timex.h>
15 #include <sys/types.h>
18 #include "alloc-util.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 #include "process-util.h"
28 #include "stat-util.h"
29 #include "string-util.h"
31 #include "time-util.h"
33 static clockid_t
map_clock_id(clockid_t c
) {
35 /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus, clock_gettime() will
36 * fail for them. Since they are essentially the same as their non-ALARM pendants (their only difference is
37 * when timers are set on them), let's just map them accordingly. This way, we can get the correct time even on
42 case CLOCK_BOOTTIME_ALARM
:
43 return CLOCK_BOOTTIME
;
45 case CLOCK_REALTIME_ALARM
:
46 return CLOCK_REALTIME
;
53 usec_t
now(clockid_t clock_id
) {
56 assert_se(clock_gettime(map_clock_id(clock_id
), &ts
) == 0);
58 return timespec_load(&ts
);
61 nsec_t
now_nsec(clockid_t clock_id
) {
64 assert_se(clock_gettime(map_clock_id(clock_id
), &ts
) == 0);
66 return timespec_load_nsec(&ts
);
69 dual_timestamp
* dual_timestamp_get(dual_timestamp
*ts
) {
72 ts
->realtime
= now(CLOCK_REALTIME
);
73 ts
->monotonic
= now(CLOCK_MONOTONIC
);
78 triple_timestamp
* triple_timestamp_get(triple_timestamp
*ts
) {
81 ts
->realtime
= now(CLOCK_REALTIME
);
82 ts
->monotonic
= now(CLOCK_MONOTONIC
);
83 ts
->boottime
= clock_boottime_supported() ? now(CLOCK_BOOTTIME
) : USEC_INFINITY
;
88 dual_timestamp
* dual_timestamp_from_realtime(dual_timestamp
*ts
, usec_t u
) {
92 if (u
== USEC_INFINITY
|| u
<= 0) {
93 ts
->realtime
= ts
->monotonic
= u
;
99 delta
= (int64_t) now(CLOCK_REALTIME
) - (int64_t) u
;
100 ts
->monotonic
= usec_sub_signed(now(CLOCK_MONOTONIC
), delta
);
105 triple_timestamp
* triple_timestamp_from_realtime(triple_timestamp
*ts
, usec_t u
) {
110 if (u
== USEC_INFINITY
|| u
<= 0) {
111 ts
->realtime
= ts
->monotonic
= ts
->boottime
= u
;
116 delta
= (int64_t) now(CLOCK_REALTIME
) - (int64_t) u
;
117 ts
->monotonic
= usec_sub_signed(now(CLOCK_MONOTONIC
), delta
);
118 ts
->boottime
= clock_boottime_supported() ? usec_sub_signed(now(CLOCK_BOOTTIME
), delta
) : USEC_INFINITY
;
123 dual_timestamp
* dual_timestamp_from_monotonic(dual_timestamp
*ts
, usec_t u
) {
127 if (u
== USEC_INFINITY
) {
128 ts
->realtime
= ts
->monotonic
= USEC_INFINITY
;
133 delta
= (int64_t) now(CLOCK_MONOTONIC
) - (int64_t) u
;
134 ts
->realtime
= usec_sub_signed(now(CLOCK_REALTIME
), delta
);
139 dual_timestamp
* dual_timestamp_from_boottime_or_monotonic(dual_timestamp
*ts
, usec_t u
) {
142 if (u
== USEC_INFINITY
) {
143 ts
->realtime
= ts
->monotonic
= USEC_INFINITY
;
147 dual_timestamp_get(ts
);
148 delta
= (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u
;
149 ts
->realtime
= usec_sub_signed(ts
->realtime
, delta
);
150 ts
->monotonic
= usec_sub_signed(ts
->monotonic
, delta
);
155 usec_t
triple_timestamp_by_clock(triple_timestamp
*ts
, clockid_t clock
) {
160 case CLOCK_REALTIME_ALARM
:
163 case CLOCK_MONOTONIC
:
164 return ts
->monotonic
;
167 case CLOCK_BOOTTIME_ALARM
:
171 return USEC_INFINITY
;
175 usec_t
timespec_load(const struct timespec
*ts
) {
178 if (ts
->tv_sec
< 0 || ts
->tv_nsec
< 0)
179 return USEC_INFINITY
;
181 if ((usec_t
) ts
->tv_sec
> (UINT64_MAX
- (ts
->tv_nsec
/ NSEC_PER_USEC
)) / USEC_PER_SEC
)
182 return USEC_INFINITY
;
185 (usec_t
) ts
->tv_sec
* USEC_PER_SEC
+
186 (usec_t
) ts
->tv_nsec
/ NSEC_PER_USEC
;
189 nsec_t
timespec_load_nsec(const struct timespec
*ts
) {
192 if (ts
->tv_sec
< 0 || ts
->tv_nsec
< 0)
193 return NSEC_INFINITY
;
195 if ((nsec_t
) ts
->tv_sec
>= (UINT64_MAX
- ts
->tv_nsec
) / NSEC_PER_SEC
)
196 return NSEC_INFINITY
;
198 return (nsec_t
) ts
->tv_sec
* NSEC_PER_SEC
+ (nsec_t
) ts
->tv_nsec
;
201 struct timespec
*timespec_store(struct timespec
*ts
, usec_t u
) {
204 if (u
== USEC_INFINITY
||
205 u
/ USEC_PER_SEC
>= TIME_T_MAX
) {
206 ts
->tv_sec
= (time_t) -1;
207 ts
->tv_nsec
= (long) -1;
211 ts
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
212 ts
->tv_nsec
= (long int) ((u
% USEC_PER_SEC
) * NSEC_PER_USEC
);
217 usec_t
timeval_load(const struct timeval
*tv
) {
220 if (tv
->tv_sec
< 0 || tv
->tv_usec
< 0)
221 return USEC_INFINITY
;
223 if ((usec_t
) tv
->tv_sec
> (UINT64_MAX
- tv
->tv_usec
) / USEC_PER_SEC
)
224 return USEC_INFINITY
;
227 (usec_t
) tv
->tv_sec
* USEC_PER_SEC
+
228 (usec_t
) tv
->tv_usec
;
231 struct timeval
*timeval_store(struct timeval
*tv
, usec_t u
) {
234 if (u
== USEC_INFINITY
||
235 u
/ USEC_PER_SEC
> TIME_T_MAX
) {
236 tv
->tv_sec
= (time_t) -1;
237 tv
->tv_usec
= (suseconds_t
) -1;
239 tv
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
240 tv
->tv_usec
= (suseconds_t
) (u
% USEC_PER_SEC
);
246 static char *format_timestamp_internal(
253 /* The weekdays in non-localized (English) form. We use this instead of the localized form, so that our
254 * generated timestamps may be parsed with parse_timestamp(), and always read the same. */
255 static const char * const weekdays
[] = {
273 1 + 10 + /* space and date */
274 1 + 8 + /* space and time */
275 (us
? 1 + 6 : 0) + /* "." and microsecond part */
276 1 + 1 + /* space and shortest possible zone */
278 return NULL
; /* Not enough space even for the shortest form. */
279 if (t
<= 0 || t
== USEC_INFINITY
)
280 return NULL
; /* Timestamp is unset */
282 /* Let's not format times with years > 9999 */
283 if (t
> USEC_TIMESTAMP_FORMATTABLE_MAX
) {
284 assert(l
>= strlen("--- XXXX-XX-XX XX:XX:XX") + 1);
285 strcpy(buf
, "--- XXXX-XX-XX XX:XX:XX");
289 sec
= (time_t) (t
/ USEC_PER_SEC
); /* Round down */
291 if (!localtime_or_gmtime_r(&sec
, &tm
, utc
))
294 /* Start with the week day */
295 assert((size_t) tm
.tm_wday
< ELEMENTSOF(weekdays
));
296 memcpy(buf
, weekdays
[tm
.tm_wday
], 4);
298 /* Add the main components */
299 if (strftime(buf
+ 3, l
- 3, " %Y-%m-%d %H:%M:%S", &tm
) <= 0)
300 return NULL
; /* Doesn't fit */
302 /* Append the microseconds part, if that's requested */
306 return NULL
; /* Microseconds part doesn't fit. */
308 sprintf(buf
+ n
, ".%06"PRI_USEC
, t
% USEC_PER_SEC
);
311 /* Append the timezone */
314 /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r() normally uses the
315 * obsolete "GMT" instead. */
317 return NULL
; /* "UTC" doesn't fit. */
319 strcpy(buf
+ n
, " UTC");
321 } else if (!isempty(tm
.tm_zone
)) {
324 /* An explicit timezone is specified, let's use it, if it fits */
325 tn
= strlen(tm
.tm_zone
);
326 if (n
+ 1 + tn
+ 1 > l
) {
327 /* The full time zone does not fit in. Yuck. */
329 if (n
+ 1 + _POSIX_TZNAME_MAX
+ 1 > l
)
330 return NULL
; /* Not even enough space for the POSIX minimum (of 6)? In that case, complain that it doesn't fit */
332 /* So the time zone doesn't fit in fully, but the caller passed enough space for the POSIX
333 * minimum time zone length. In this case suppress the timezone entirely, in order not to dump
334 * an overly long, hard to read string on the user. This should be safe, because the user will
335 * assume the local timezone anyway if none is shown. And so does parse_timestamp(). */
338 strcpy(buf
+ n
, tm
.tm_zone
);
345 char *format_timestamp(char *buf
, size_t l
, usec_t t
) {
346 return format_timestamp_internal(buf
, l
, t
, false, false);
349 char *format_timestamp_utc(char *buf
, size_t l
, usec_t t
) {
350 return format_timestamp_internal(buf
, l
, t
, true, false);
353 char *format_timestamp_us(char *buf
, size_t l
, usec_t t
) {
354 return format_timestamp_internal(buf
, l
, t
, false, true);
357 char *format_timestamp_us_utc(char *buf
, size_t l
, usec_t t
) {
358 return format_timestamp_internal(buf
, l
, t
, true, true);
361 char *format_timestamp_relative(char *buf
, size_t l
, usec_t t
) {
365 if (t
<= 0 || t
== USEC_INFINITY
)
368 n
= now(CLOCK_REALTIME
);
377 if (d
>= USEC_PER_YEAR
)
378 snprintf(buf
, l
, USEC_FMT
" years " USEC_FMT
" months %s",
380 (d
% USEC_PER_YEAR
) / USEC_PER_MONTH
, s
);
381 else if (d
>= USEC_PER_MONTH
)
382 snprintf(buf
, l
, USEC_FMT
" months " USEC_FMT
" days %s",
384 (d
% USEC_PER_MONTH
) / USEC_PER_DAY
, s
);
385 else if (d
>= USEC_PER_WEEK
)
386 snprintf(buf
, l
, USEC_FMT
" weeks " USEC_FMT
" days %s",
388 (d
% USEC_PER_WEEK
) / USEC_PER_DAY
, s
);
389 else if (d
>= 2*USEC_PER_DAY
)
390 snprintf(buf
, l
, USEC_FMT
" days %s", d
/ USEC_PER_DAY
, s
);
391 else if (d
>= 25*USEC_PER_HOUR
)
392 snprintf(buf
, l
, "1 day " USEC_FMT
"h %s",
393 (d
- USEC_PER_DAY
) / USEC_PER_HOUR
, s
);
394 else if (d
>= 6*USEC_PER_HOUR
)
395 snprintf(buf
, l
, USEC_FMT
"h %s",
396 d
/ USEC_PER_HOUR
, s
);
397 else if (d
>= USEC_PER_HOUR
)
398 snprintf(buf
, l
, USEC_FMT
"h " USEC_FMT
"min %s",
400 (d
% USEC_PER_HOUR
) / USEC_PER_MINUTE
, s
);
401 else if (d
>= 5*USEC_PER_MINUTE
)
402 snprintf(buf
, l
, USEC_FMT
"min %s",
403 d
/ USEC_PER_MINUTE
, s
);
404 else if (d
>= USEC_PER_MINUTE
)
405 snprintf(buf
, l
, USEC_FMT
"min " USEC_FMT
"s %s",
407 (d
% USEC_PER_MINUTE
) / USEC_PER_SEC
, s
);
408 else if (d
>= USEC_PER_SEC
)
409 snprintf(buf
, l
, USEC_FMT
"s %s",
410 d
/ USEC_PER_SEC
, s
);
411 else if (d
>= USEC_PER_MSEC
)
412 snprintf(buf
, l
, USEC_FMT
"ms %s",
413 d
/ USEC_PER_MSEC
, s
);
415 snprintf(buf
, l
, USEC_FMT
"us %s",
418 snprintf(buf
, l
, "now");
424 char *format_timespan(char *buf
, size_t l
, usec_t t
, usec_t accuracy
) {
425 static const struct {
429 { "y", USEC_PER_YEAR
},
430 { "month", USEC_PER_MONTH
},
431 { "w", USEC_PER_WEEK
},
432 { "d", USEC_PER_DAY
},
433 { "h", USEC_PER_HOUR
},
434 { "min", USEC_PER_MINUTE
},
435 { "s", USEC_PER_SEC
},
436 { "ms", USEC_PER_MSEC
},
442 bool something
= false;
447 if (t
== USEC_INFINITY
) {
448 strncpy(p
, "infinity", l
-1);
454 strncpy(p
, "0", l
-1);
459 /* The result of this function can be parsed with parse_sec */
461 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
470 if (t
< accuracy
&& something
)
473 if (t
< table
[i
].usec
)
479 a
= t
/ table
[i
].usec
;
480 b
= t
% table
[i
].usec
;
482 /* Let's see if we should shows this in dot notation */
483 if (t
< USEC_PER_MINUTE
&& b
> 0) {
488 for (cc
= table
[i
].usec
; cc
> 1; cc
/= 10)
491 for (cc
= accuracy
; cc
> 1; cc
/= 10) {
498 "%s"USEC_FMT
".%0*"PRI_USEC
"%s",
510 /* No? Then let's show it normally */
521 n
= MIN((size_t) k
, l
);
534 void dual_timestamp_serialize(FILE *f
, const char *name
, dual_timestamp
*t
) {
540 if (!dual_timestamp_is_set(t
))
543 fprintf(f
, "%s="USEC_FMT
" "USEC_FMT
"\n",
549 int dual_timestamp_deserialize(const char *value
, dual_timestamp
*t
) {
556 pos
= strspn(value
, WHITESPACE
);
557 if (value
[pos
] == '-')
559 pos
+= strspn(value
+ pos
, DIGITS
);
560 pos
+= strspn(value
+ pos
, WHITESPACE
);
561 if (value
[pos
] == '-')
564 r
= sscanf(value
, "%" PRIu64
"%" PRIu64
"%n", &a
, &b
, &pos
);
566 log_debug("Failed to parse dual timestamp value \"%s\".", value
);
570 if (value
[pos
] != '\0')
571 /* trailing garbage */
580 int timestamp_deserialize(const char *value
, usec_t
*timestamp
) {
585 r
= safe_atou64(value
, timestamp
);
587 return log_debug_errno(r
, "Failed to parse timestamp value \"%s\": %m", value
);
592 static int parse_timestamp_impl(const char *t
, usec_t
*usec
, bool with_tz
) {
593 static const struct {
613 const char *k
, *utc
= NULL
, *tzn
= NULL
;
616 usec_t x_usec
, plus
= 0, minus
= 0, ret
;
617 int r
, weekday
= -1, dst
= -1;
622 * 2012-09-22 16:34:22
623 * 2012-09-22 16:34 (seconds will be set to 0)
624 * 2012-09-22 (time will be set to 00:00:00)
625 * 16:34:22 (date will be set to today)
626 * 16:34 (date will be set to today, seconds to 0)
628 * yesterday (time is set to 00:00:00)
629 * today (time is set to 00:00:00)
630 * tomorrow (time is set to 00:00:00)
633 * @2147483647 (seconds since epoch)
639 if (t
[0] == '@' && !with_tz
)
640 return parse_sec(t
+ 1, usec
);
642 ret
= now(CLOCK_REALTIME
);
648 else if (t
[0] == '+') {
649 r
= parse_sec(t
+1, &plus
);
655 } else if (t
[0] == '-') {
656 r
= parse_sec(t
+1, &minus
);
662 } else if ((k
= endswith(t
, " ago"))) {
663 t
= strndupa(t
, k
- t
);
665 r
= parse_sec(t
, &minus
);
671 } else if ((k
= endswith(t
, " left"))) {
672 t
= strndupa(t
, k
- t
);
674 r
= parse_sec(t
, &plus
);
681 /* See if the timestamp is suffixed with UTC */
682 utc
= endswith_no_case(t
, " UTC");
684 t
= strndupa(t
, utc
- t
);
686 const char *e
= NULL
;
691 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
692 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
693 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
694 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
695 * support arbitrary timezone specifications. */
697 for (j
= 0; j
<= 1; j
++) {
699 if (isempty(tzname
[j
]))
702 e
= endswith_no_case(t
, tzname
[j
]);
713 if (IN_SET(j
, 0, 1)) {
714 /* Found one of the two timezones specified. */
715 t
= strndupa(t
, e
- t
- 1);
722 x
= (time_t) (ret
/ USEC_PER_SEC
);
725 if (!localtime_or_gmtime_r(&x
, &tm
, utc
))
732 if (streq(t
, "today")) {
733 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
736 } else if (streq(t
, "yesterday")) {
738 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
741 } else if (streq(t
, "tomorrow")) {
743 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
747 for (i
= 0; i
< ELEMENTSOF(day_nr
); i
++) {
750 if (!startswith_no_case(t
, day_nr
[i
].name
))
753 skip
= strlen(day_nr
[i
].name
);
757 weekday
= day_nr
[i
].nr
;
763 k
= strptime(t
, "%y-%m-%d %H:%M:%S", &tm
);
772 k
= strptime(t
, "%Y-%m-%d %H:%M:%S", &tm
);
781 k
= strptime(t
, "%y-%m-%d %H:%M", &tm
);
788 k
= strptime(t
, "%Y-%m-%d %H:%M", &tm
);
795 k
= strptime(t
, "%y-%m-%d", &tm
);
797 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
802 k
= strptime(t
, "%Y-%m-%d", &tm
);
804 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
809 k
= strptime(t
, "%H:%M:%S", &tm
);
818 k
= strptime(t
, "%H:%M", &tm
);
831 r
= parse_fractional_part_u(&k
, 6, &add
);
842 if (weekday
>= 0 && tm
.tm_wday
!= weekday
)
845 x
= mktime_or_timegm(&tm
, utc
);
849 ret
= (usec_t
) x
* USEC_PER_SEC
+ x_usec
;
850 if (ret
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
854 if (ret
+ plus
< ret
) /* overflow? */
857 if (ret
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
870 typedef struct ParseTimestampResult
{
873 } ParseTimestampResult
;
875 int parse_timestamp(const char *t
, usec_t
*usec
) {
876 char *last_space
, *tz
= NULL
;
877 ParseTimestampResult
*shared
, tmp
;
880 last_space
= strrchr(t
, ' ');
881 if (last_space
!= NULL
&& timezone_is_valid(last_space
+ 1, LOG_DEBUG
))
884 if (!tz
|| endswith_no_case(t
, " UTC"))
885 return parse_timestamp_impl(t
, usec
, false);
887 shared
= mmap(NULL
, sizeof *shared
, PROT_READ
|PROT_WRITE
, MAP_SHARED
|MAP_ANONYMOUS
, -1, 0);
888 if (shared
== MAP_FAILED
)
889 return negative_errno();
891 r
= safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG
|FORK_WAIT
, NULL
);
893 (void) munmap(shared
, sizeof *shared
);
899 if (setenv("TZ", tz
, 1) != 0) {
900 shared
->return_value
= negative_errno();
906 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
907 * Otherwise just cut it off. */
908 with_tz
= !STR_IN_SET(tz
, tzname
[0], tzname
[1]);
910 /* Cut off the timezone if we dont need it. */
912 t
= strndupa(t
, last_space
- t
);
914 shared
->return_value
= parse_timestamp_impl(t
, &shared
->usec
, with_tz
);
920 if (munmap(shared
, sizeof *shared
) != 0)
921 return negative_errno();
923 if (tmp
.return_value
== 0)
926 return tmp
.return_value
;
929 static char* extract_multiplier(char *p
, usec_t
*multiplier
) {
930 static const struct {
934 { "seconds", USEC_PER_SEC
},
935 { "second", USEC_PER_SEC
},
936 { "sec", USEC_PER_SEC
},
937 { "s", USEC_PER_SEC
},
938 { "minutes", USEC_PER_MINUTE
},
939 { "minute", USEC_PER_MINUTE
},
940 { "min", USEC_PER_MINUTE
},
941 { "months", USEC_PER_MONTH
},
942 { "month", USEC_PER_MONTH
},
943 { "M", USEC_PER_MONTH
},
944 { "msec", USEC_PER_MSEC
},
945 { "ms", USEC_PER_MSEC
},
946 { "m", USEC_PER_MINUTE
},
947 { "hours", USEC_PER_HOUR
},
948 { "hour", USEC_PER_HOUR
},
949 { "hr", USEC_PER_HOUR
},
950 { "h", USEC_PER_HOUR
},
951 { "days", USEC_PER_DAY
},
952 { "day", USEC_PER_DAY
},
953 { "d", USEC_PER_DAY
},
954 { "weeks", USEC_PER_WEEK
},
955 { "week", USEC_PER_WEEK
},
956 { "w", USEC_PER_WEEK
},
957 { "years", USEC_PER_YEAR
},
958 { "year", USEC_PER_YEAR
},
959 { "y", USEC_PER_YEAR
},
966 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
969 e
= startswith(p
, table
[i
].suffix
);
971 *multiplier
= table
[i
].usec
;
979 int parse_time(const char *t
, usec_t
*usec
, usec_t default_unit
) {
982 bool something
= false;
986 assert(default_unit
> 0);
990 p
+= strspn(p
, WHITESPACE
);
991 s
= startswith(p
, "infinity");
993 s
+= strspn(s
, WHITESPACE
);
997 *usec
= USEC_INFINITY
;
1005 usec_t multiplier
= default_unit
, k
;
1007 p
+= strspn(p
, WHITESPACE
);
1017 l
= strtoll(p
, &e
, 10);
1027 z
= strtoll(b
, &e
, 10);
1042 e
+= strspn(e
, WHITESPACE
);
1043 p
= extract_multiplier(e
, &multiplier
);
1047 k
= (usec_t
) z
* multiplier
;
1052 r
+= (usec_t
) l
* multiplier
+ k
;
1060 int parse_sec(const char *t
, usec_t
*usec
) {
1061 return parse_time(t
, usec
, USEC_PER_SEC
);
1064 int parse_sec_fix_0(const char *t
, usec_t
*usec
) {
1068 t
+= strspn(t
, WHITESPACE
);
1070 if (streq(t
, "0")) {
1071 *usec
= USEC_INFINITY
;
1075 return parse_sec(t
, usec
);
1078 int parse_nsec(const char *t
, nsec_t
*nsec
) {
1079 static const struct {
1083 { "seconds", NSEC_PER_SEC
},
1084 { "second", NSEC_PER_SEC
},
1085 { "sec", NSEC_PER_SEC
},
1086 { "s", NSEC_PER_SEC
},
1087 { "minutes", NSEC_PER_MINUTE
},
1088 { "minute", NSEC_PER_MINUTE
},
1089 { "min", NSEC_PER_MINUTE
},
1090 { "months", NSEC_PER_MONTH
},
1091 { "month", NSEC_PER_MONTH
},
1092 { "msec", NSEC_PER_MSEC
},
1093 { "ms", NSEC_PER_MSEC
},
1094 { "m", NSEC_PER_MINUTE
},
1095 { "hours", NSEC_PER_HOUR
},
1096 { "hour", NSEC_PER_HOUR
},
1097 { "hr", NSEC_PER_HOUR
},
1098 { "h", NSEC_PER_HOUR
},
1099 { "days", NSEC_PER_DAY
},
1100 { "day", NSEC_PER_DAY
},
1101 { "d", NSEC_PER_DAY
},
1102 { "weeks", NSEC_PER_WEEK
},
1103 { "week", NSEC_PER_WEEK
},
1104 { "w", NSEC_PER_WEEK
},
1105 { "years", NSEC_PER_YEAR
},
1106 { "year", NSEC_PER_YEAR
},
1107 { "y", NSEC_PER_YEAR
},
1108 { "usec", NSEC_PER_USEC
},
1109 { "us", NSEC_PER_USEC
},
1110 { "µs", NSEC_PER_USEC
},
1113 { "", 1ULL }, /* default is nsec */
1118 bool something
= false;
1125 p
+= strspn(p
, WHITESPACE
);
1126 s
= startswith(p
, "infinity");
1128 s
+= strspn(s
, WHITESPACE
);
1132 *nsec
= NSEC_INFINITY
;
1141 p
+= strspn(p
, WHITESPACE
);
1151 l
= strtoll(p
, &e
, 10);
1163 z
= strtoll(b
, &e
, 10);
1178 e
+= strspn(e
, WHITESPACE
);
1180 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
1181 if (startswith(e
, table
[i
].suffix
)) {
1182 nsec_t k
= (nsec_t
) z
* table
[i
].nsec
;
1187 r
+= (nsec_t
) l
* table
[i
].nsec
+ k
;
1188 p
= e
+ strlen(table
[i
].suffix
);
1194 if (i
>= ELEMENTSOF(table
))
1204 bool ntp_synced(void) {
1205 struct timex txc
= {};
1207 if (adjtimex(&txc
) < 0)
1210 if (txc
.status
& STA_UNSYNC
)
1216 int get_timezones(char ***ret
) {
1217 _cleanup_fclose_
FILE *f
= NULL
;
1218 _cleanup_strv_free_
char **zones
= NULL
;
1219 size_t n_zones
= 0, n_allocated
= 0;
1223 zones
= strv_new("UTC", NULL
);
1230 f
= fopen("/usr/share/zoneinfo/zone.tab", "re");
1234 FOREACH_LINE(l
, f
, return -errno
) {
1240 if (isempty(p
) || *p
== '#')
1243 /* Skip over country code */
1244 p
+= strcspn(p
, WHITESPACE
);
1245 p
+= strspn(p
, WHITESPACE
);
1247 /* Skip over coordinates */
1248 p
+= strcspn(p
, WHITESPACE
);
1249 p
+= strspn(p
, WHITESPACE
);
1251 /* Found timezone name */
1252 k
= strcspn(p
, WHITESPACE
);
1260 if (!GREEDY_REALLOC(zones
, n_allocated
, n_zones
+ 2)) {
1265 zones
[n_zones
++] = w
;
1266 zones
[n_zones
] = NULL
;
1271 } else if (errno
!= ENOENT
)
1274 *ret
= TAKE_PTR(zones
);
1279 bool timezone_is_valid(const char *name
, int log_level
) {
1282 _cleanup_close_
int fd
= -1;
1292 for (p
= name
; *p
; p
++) {
1293 if (!(*p
>= '0' && *p
<= '9') &&
1294 !(*p
>= 'a' && *p
<= 'z') &&
1295 !(*p
>= 'A' && *p
<= 'Z') &&
1296 !IN_SET(*p
, '-', '_', '+', '/'))
1312 if (p
- name
>= PATH_MAX
)
1315 t
= strjoina("/usr/share/zoneinfo/", name
);
1317 fd
= open(t
, O_RDONLY
|O_CLOEXEC
);
1319 log_full_errno(log_level
, errno
, "Failed to open timezone file '%s': %m", t
);
1323 r
= fd_verify_regular(fd
);
1325 log_full_errno(log_level
, r
, "Timezone file '%s' is not a regular file: %m", t
);
1329 r
= loop_read_exact(fd
, buf
, 4, false);
1331 log_full_errno(log_level
, r
, "Failed to read from timezone file '%s': %m", t
);
1335 /* Magic from tzfile(5) */
1336 if (memcmp(buf
, "TZif", 4) != 0) {
1337 log_full(log_level
, "Timezone file '%s' has wrong magic bytes", t
);
1344 bool clock_boottime_supported(void) {
1345 static int supported
= -1;
1347 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1349 if (supported
< 0) {
1352 fd
= timerfd_create(CLOCK_BOOTTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
1364 clockid_t
clock_boottime_or_monotonic(void) {
1365 if (clock_boottime_supported())
1366 return CLOCK_BOOTTIME
;
1368 return CLOCK_MONOTONIC
;
1371 bool clock_supported(clockid_t clock
) {
1376 case CLOCK_MONOTONIC
:
1377 case CLOCK_REALTIME
:
1380 case CLOCK_BOOTTIME
:
1381 return clock_boottime_supported();
1383 case CLOCK_BOOTTIME_ALARM
:
1384 if (!clock_boottime_supported())
1389 /* For everything else, check properly */
1390 return clock_gettime(clock
, &ts
) >= 0;
1394 int get_timezone(char **tz
) {
1395 _cleanup_free_
char *t
= NULL
;
1400 r
= readlink_malloc("/etc/localtime", &t
);
1402 return r
; /* returns EINVAL if not a symlink */
1404 e
= path_startswith(t
, "/usr/share/zoneinfo/");
1406 e
= path_startswith(t
, "../usr/share/zoneinfo/");
1410 if (!timezone_is_valid(e
, LOG_DEBUG
))
1421 time_t mktime_or_timegm(struct tm
*tm
, bool utc
) {
1422 return utc
? timegm(tm
) : mktime(tm
);
1425 struct tm
*localtime_or_gmtime_r(const time_t *t
, struct tm
*tm
, bool utc
) {
1426 return utc
? gmtime_r(t
, tm
) : localtime_r(t
, tm
);
1429 unsigned long usec_to_jiffies(usec_t u
) {
1430 static thread_local
unsigned long hz
= 0;
1434 r
= sysconf(_SC_CLK_TCK
);
1440 return DIV_ROUND_UP(u
, USEC_PER_SEC
/ hz
);
1443 usec_t
usec_shift_clock(usec_t x
, clockid_t from
, clockid_t to
) {
1446 if (x
== USEC_INFINITY
)
1447 return USEC_INFINITY
;
1448 if (map_clock_id(from
) == map_clock_id(to
))
1455 /* x lies in the future */
1456 return usec_add(b
, usec_sub_unsigned(x
, a
));
1458 /* x lies in the past */
1459 return usec_sub_unsigned(b
, usec_sub_unsigned(a
, x
));
1462 bool in_utc_timezone(void) {
1465 return timezone
== 0 && daylight
== 0;
1468 int time_change_fd(void) {
1470 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1471 static const struct itimerspec its
= {
1472 .it_value
.tv_sec
= TIME_T_MAX
,
1475 _cleanup_close_
int fd
;
1477 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX
));
1479 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1480 * CLOCK_MONOTONIC. */
1482 fd
= timerfd_create(CLOCK_REALTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
1486 if (timerfd_settime(fd
, TFD_TIMER_ABSTIME
|TFD_TIMER_CANCEL_ON_SET
, &its
, NULL
) < 0)