1 /* SPDX-License-Identifier: LGPL-2.1+ */
11 #include <sys/timerfd.h>
12 #include <sys/timex.h>
13 #include <sys/types.h>
16 #include "alloc-util.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "process-util.h"
26 #include "serialize.h"
27 #include "stat-util.h"
28 #include "string-util.h"
30 #include "time-util.h"
32 static clockid_t
map_clock_id(clockid_t c
) {
34 /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus, clock_gettime() will
35 * fail for them. Since they are essentially the same as their non-ALARM pendants (their only difference is
36 * when timers are set on them), let's just map them accordingly. This way, we can get the correct time even on
41 case CLOCK_BOOTTIME_ALARM
:
42 return CLOCK_BOOTTIME
;
44 case CLOCK_REALTIME_ALARM
:
45 return CLOCK_REALTIME
;
52 usec_t
now(clockid_t clock_id
) {
55 assert_se(clock_gettime(map_clock_id(clock_id
), &ts
) == 0);
57 return timespec_load(&ts
);
60 nsec_t
now_nsec(clockid_t clock_id
) {
63 assert_se(clock_gettime(map_clock_id(clock_id
), &ts
) == 0);
65 return timespec_load_nsec(&ts
);
68 dual_timestamp
* dual_timestamp_get(dual_timestamp
*ts
) {
71 ts
->realtime
= now(CLOCK_REALTIME
);
72 ts
->monotonic
= now(CLOCK_MONOTONIC
);
77 triple_timestamp
* triple_timestamp_get(triple_timestamp
*ts
) {
80 ts
->realtime
= now(CLOCK_REALTIME
);
81 ts
->monotonic
= now(CLOCK_MONOTONIC
);
82 ts
->boottime
= clock_boottime_supported() ? now(CLOCK_BOOTTIME
) : USEC_INFINITY
;
87 dual_timestamp
* dual_timestamp_from_realtime(dual_timestamp
*ts
, usec_t u
) {
91 if (u
== USEC_INFINITY
|| u
<= 0) {
92 ts
->realtime
= ts
->monotonic
= u
;
98 delta
= (int64_t) now(CLOCK_REALTIME
) - (int64_t) u
;
99 ts
->monotonic
= usec_sub_signed(now(CLOCK_MONOTONIC
), delta
);
104 triple_timestamp
* triple_timestamp_from_realtime(triple_timestamp
*ts
, usec_t u
) {
109 if (u
== USEC_INFINITY
|| u
<= 0) {
110 ts
->realtime
= ts
->monotonic
= ts
->boottime
= u
;
115 delta
= (int64_t) now(CLOCK_REALTIME
) - (int64_t) u
;
116 ts
->monotonic
= usec_sub_signed(now(CLOCK_MONOTONIC
), delta
);
117 ts
->boottime
= clock_boottime_supported() ? usec_sub_signed(now(CLOCK_BOOTTIME
), delta
) : USEC_INFINITY
;
122 dual_timestamp
* dual_timestamp_from_monotonic(dual_timestamp
*ts
, usec_t u
) {
126 if (u
== USEC_INFINITY
) {
127 ts
->realtime
= ts
->monotonic
= USEC_INFINITY
;
132 delta
= (int64_t) now(CLOCK_MONOTONIC
) - (int64_t) u
;
133 ts
->realtime
= usec_sub_signed(now(CLOCK_REALTIME
), delta
);
138 dual_timestamp
* dual_timestamp_from_boottime_or_monotonic(dual_timestamp
*ts
, usec_t u
) {
141 if (u
== USEC_INFINITY
) {
142 ts
->realtime
= ts
->monotonic
= USEC_INFINITY
;
146 dual_timestamp_get(ts
);
147 delta
= (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u
;
148 ts
->realtime
= usec_sub_signed(ts
->realtime
, delta
);
149 ts
->monotonic
= usec_sub_signed(ts
->monotonic
, delta
);
154 usec_t
triple_timestamp_by_clock(triple_timestamp
*ts
, clockid_t clock
) {
159 case CLOCK_REALTIME_ALARM
:
162 case CLOCK_MONOTONIC
:
163 return ts
->monotonic
;
166 case CLOCK_BOOTTIME_ALARM
:
170 return USEC_INFINITY
;
174 usec_t
timespec_load(const struct timespec
*ts
) {
177 if (ts
->tv_sec
< 0 || ts
->tv_nsec
< 0)
178 return USEC_INFINITY
;
180 if ((usec_t
) ts
->tv_sec
> (UINT64_MAX
- (ts
->tv_nsec
/ NSEC_PER_USEC
)) / USEC_PER_SEC
)
181 return USEC_INFINITY
;
184 (usec_t
) ts
->tv_sec
* USEC_PER_SEC
+
185 (usec_t
) ts
->tv_nsec
/ NSEC_PER_USEC
;
188 nsec_t
timespec_load_nsec(const struct timespec
*ts
) {
191 if (ts
->tv_sec
< 0 || ts
->tv_nsec
< 0)
192 return NSEC_INFINITY
;
194 if ((nsec_t
) ts
->tv_sec
>= (UINT64_MAX
- ts
->tv_nsec
) / NSEC_PER_SEC
)
195 return NSEC_INFINITY
;
197 return (nsec_t
) ts
->tv_sec
* NSEC_PER_SEC
+ (nsec_t
) ts
->tv_nsec
;
200 struct timespec
*timespec_store(struct timespec
*ts
, usec_t u
) {
203 if (u
== USEC_INFINITY
||
204 u
/ USEC_PER_SEC
>= TIME_T_MAX
) {
205 ts
->tv_sec
= (time_t) -1;
206 ts
->tv_nsec
= (long) -1;
210 ts
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
211 ts
->tv_nsec
= (long int) ((u
% USEC_PER_SEC
) * NSEC_PER_USEC
);
216 usec_t
timeval_load(const struct timeval
*tv
) {
219 if (tv
->tv_sec
< 0 || tv
->tv_usec
< 0)
220 return USEC_INFINITY
;
222 if ((usec_t
) tv
->tv_sec
> (UINT64_MAX
- tv
->tv_usec
) / USEC_PER_SEC
)
223 return USEC_INFINITY
;
226 (usec_t
) tv
->tv_sec
* USEC_PER_SEC
+
227 (usec_t
) tv
->tv_usec
;
230 struct timeval
*timeval_store(struct timeval
*tv
, usec_t u
) {
233 if (u
== USEC_INFINITY
||
234 u
/ USEC_PER_SEC
> TIME_T_MAX
) {
235 tv
->tv_sec
= (time_t) -1;
236 tv
->tv_usec
= (suseconds_t
) -1;
238 tv
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
239 tv
->tv_usec
= (suseconds_t
) (u
% USEC_PER_SEC
);
245 static char *format_timestamp_internal(
252 /* The weekdays in non-localized (English) form. We use this instead of the localized form, so that our
253 * generated timestamps may be parsed with parse_timestamp(), and always read the same. */
254 static const char * const weekdays
[] = {
272 1 + 10 + /* space and date */
273 1 + 8 + /* space and time */
274 (us
? 1 + 6 : 0) + /* "." and microsecond part */
275 1 + 1 + /* space and shortest possible zone */
277 return NULL
; /* Not enough space even for the shortest form. */
278 if (t
<= 0 || t
== USEC_INFINITY
)
279 return NULL
; /* Timestamp is unset */
281 /* Let's not format times with years > 9999 */
282 if (t
> USEC_TIMESTAMP_FORMATTABLE_MAX
) {
283 assert(l
>= STRLEN("--- XXXX-XX-XX XX:XX:XX") + 1);
284 strcpy(buf
, "--- XXXX-XX-XX XX:XX:XX");
288 sec
= (time_t) (t
/ USEC_PER_SEC
); /* Round down */
290 if (!localtime_or_gmtime_r(&sec
, &tm
, utc
))
293 /* Start with the week day */
294 assert((size_t) tm
.tm_wday
< ELEMENTSOF(weekdays
));
295 memcpy(buf
, weekdays
[tm
.tm_wday
], 4);
297 /* Add the main components */
298 if (strftime(buf
+ 3, l
- 3, " %Y-%m-%d %H:%M:%S", &tm
) <= 0)
299 return NULL
; /* Doesn't fit */
301 /* Append the microseconds part, if that's requested */
305 return NULL
; /* Microseconds part doesn't fit. */
307 sprintf(buf
+ n
, ".%06"PRI_USEC
, t
% USEC_PER_SEC
);
310 /* Append the timezone */
313 /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r() normally uses the
314 * obsolete "GMT" instead. */
316 return NULL
; /* "UTC" doesn't fit. */
318 strcpy(buf
+ n
, " UTC");
320 } else if (!isempty(tm
.tm_zone
)) {
323 /* An explicit timezone is specified, let's use it, if it fits */
324 tn
= strlen(tm
.tm_zone
);
325 if (n
+ 1 + tn
+ 1 > l
) {
326 /* The full time zone does not fit in. Yuck. */
328 if (n
+ 1 + _POSIX_TZNAME_MAX
+ 1 > l
)
329 return NULL
; /* Not even enough space for the POSIX minimum (of 6)? In that case, complain that it doesn't fit */
331 /* So the time zone doesn't fit in fully, but the caller passed enough space for the POSIX
332 * minimum time zone length. In this case suppress the timezone entirely, in order not to dump
333 * an overly long, hard to read string on the user. This should be safe, because the user will
334 * assume the local timezone anyway if none is shown. And so does parse_timestamp(). */
337 strcpy(buf
+ n
, tm
.tm_zone
);
344 char *format_timestamp(char *buf
, size_t l
, usec_t t
) {
345 return format_timestamp_internal(buf
, l
, t
, false, false);
348 char *format_timestamp_utc(char *buf
, size_t l
, usec_t t
) {
349 return format_timestamp_internal(buf
, l
, t
, true, false);
352 char *format_timestamp_us(char *buf
, size_t l
, usec_t t
) {
353 return format_timestamp_internal(buf
, l
, t
, false, true);
356 char *format_timestamp_us_utc(char *buf
, size_t l
, usec_t t
) {
357 return format_timestamp_internal(buf
, l
, t
, true, true);
360 char *format_timestamp_relative(char *buf
, size_t l
, usec_t t
) {
364 if (t
<= 0 || t
== USEC_INFINITY
)
367 n
= now(CLOCK_REALTIME
);
376 if (d
>= USEC_PER_YEAR
)
377 snprintf(buf
, l
, USEC_FMT
" years " USEC_FMT
" months %s",
379 (d
% USEC_PER_YEAR
) / USEC_PER_MONTH
, s
);
380 else if (d
>= USEC_PER_MONTH
)
381 snprintf(buf
, l
, USEC_FMT
" months " USEC_FMT
" days %s",
383 (d
% USEC_PER_MONTH
) / USEC_PER_DAY
, s
);
384 else if (d
>= USEC_PER_WEEK
)
385 snprintf(buf
, l
, USEC_FMT
" weeks " USEC_FMT
" days %s",
387 (d
% USEC_PER_WEEK
) / USEC_PER_DAY
, s
);
388 else if (d
>= 2*USEC_PER_DAY
)
389 snprintf(buf
, l
, USEC_FMT
" days %s", d
/ USEC_PER_DAY
, s
);
390 else if (d
>= 25*USEC_PER_HOUR
)
391 snprintf(buf
, l
, "1 day " USEC_FMT
"h %s",
392 (d
- USEC_PER_DAY
) / USEC_PER_HOUR
, s
);
393 else if (d
>= 6*USEC_PER_HOUR
)
394 snprintf(buf
, l
, USEC_FMT
"h %s",
395 d
/ USEC_PER_HOUR
, s
);
396 else if (d
>= USEC_PER_HOUR
)
397 snprintf(buf
, l
, USEC_FMT
"h " USEC_FMT
"min %s",
399 (d
% USEC_PER_HOUR
) / USEC_PER_MINUTE
, s
);
400 else if (d
>= 5*USEC_PER_MINUTE
)
401 snprintf(buf
, l
, USEC_FMT
"min %s",
402 d
/ USEC_PER_MINUTE
, s
);
403 else if (d
>= USEC_PER_MINUTE
)
404 snprintf(buf
, l
, USEC_FMT
"min " USEC_FMT
"s %s",
406 (d
% USEC_PER_MINUTE
) / USEC_PER_SEC
, s
);
407 else if (d
>= USEC_PER_SEC
)
408 snprintf(buf
, l
, USEC_FMT
"s %s",
409 d
/ USEC_PER_SEC
, s
);
410 else if (d
>= USEC_PER_MSEC
)
411 snprintf(buf
, l
, USEC_FMT
"ms %s",
412 d
/ USEC_PER_MSEC
, s
);
414 snprintf(buf
, l
, USEC_FMT
"us %s",
417 snprintf(buf
, l
, "now");
423 char *format_timespan(char *buf
, size_t l
, usec_t t
, usec_t accuracy
) {
424 static const struct {
428 { "y", USEC_PER_YEAR
},
429 { "month", USEC_PER_MONTH
},
430 { "w", USEC_PER_WEEK
},
431 { "d", USEC_PER_DAY
},
432 { "h", USEC_PER_HOUR
},
433 { "min", USEC_PER_MINUTE
},
434 { "s", USEC_PER_SEC
},
435 { "ms", USEC_PER_MSEC
},
441 bool something
= false;
446 if (t
== USEC_INFINITY
) {
447 strncpy(p
, "infinity", l
-1);
453 strncpy(p
, "0", l
-1);
458 /* The result of this function can be parsed with parse_sec */
460 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
469 if (t
< accuracy
&& something
)
472 if (t
< table
[i
].usec
)
478 a
= t
/ table
[i
].usec
;
479 b
= t
% table
[i
].usec
;
481 /* Let's see if we should shows this in dot notation */
482 if (t
< USEC_PER_MINUTE
&& b
> 0) {
487 for (cc
= table
[i
].usec
; cc
> 1; cc
/= 10)
490 for (cc
= accuracy
; cc
> 1; cc
/= 10) {
497 "%s"USEC_FMT
".%0*"PRI_USEC
"%s",
509 /* No? Then let's show it normally */
520 n
= MIN((size_t) k
, l
);
533 static int parse_timestamp_impl(const char *t
, usec_t
*usec
, bool with_tz
) {
534 static const struct {
554 const char *k
, *utc
= NULL
, *tzn
= NULL
;
557 usec_t x_usec
, plus
= 0, minus
= 0, ret
;
558 int r
, weekday
= -1, dst
= -1;
563 * 2012-09-22 16:34:22
564 * 2012-09-22 16:34 (seconds will be set to 0)
565 * 2012-09-22 (time will be set to 00:00:00)
566 * 16:34:22 (date will be set to today)
567 * 16:34 (date will be set to today, seconds to 0)
569 * yesterday (time is set to 00:00:00)
570 * today (time is set to 00:00:00)
571 * tomorrow (time is set to 00:00:00)
574 * @2147483647 (seconds since epoch)
580 if (t
[0] == '@' && !with_tz
)
581 return parse_sec(t
+ 1, usec
);
583 ret
= now(CLOCK_REALTIME
);
589 else if (t
[0] == '+') {
590 r
= parse_sec(t
+1, &plus
);
596 } else if (t
[0] == '-') {
597 r
= parse_sec(t
+1, &minus
);
603 } else if ((k
= endswith(t
, " ago"))) {
604 t
= strndupa(t
, k
- t
);
606 r
= parse_sec(t
, &minus
);
612 } else if ((k
= endswith(t
, " left"))) {
613 t
= strndupa(t
, k
- t
);
615 r
= parse_sec(t
, &plus
);
622 /* See if the timestamp is suffixed with UTC */
623 utc
= endswith_no_case(t
, " UTC");
625 t
= strndupa(t
, utc
- t
);
627 const char *e
= NULL
;
632 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
633 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
634 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
635 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
636 * support arbitrary timezone specifications. */
638 for (j
= 0; j
<= 1; j
++) {
640 if (isempty(tzname
[j
]))
643 e
= endswith_no_case(t
, tzname
[j
]);
654 if (IN_SET(j
, 0, 1)) {
655 /* Found one of the two timezones specified. */
656 t
= strndupa(t
, e
- t
- 1);
663 x
= (time_t) (ret
/ USEC_PER_SEC
);
666 if (!localtime_or_gmtime_r(&x
, &tm
, utc
))
673 if (streq(t
, "today")) {
674 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
677 } else if (streq(t
, "yesterday")) {
679 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
682 } else if (streq(t
, "tomorrow")) {
684 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
688 for (i
= 0; i
< ELEMENTSOF(day_nr
); i
++) {
691 if (!startswith_no_case(t
, day_nr
[i
].name
))
694 skip
= strlen(day_nr
[i
].name
);
698 weekday
= day_nr
[i
].nr
;
704 k
= strptime(t
, "%y-%m-%d %H:%M:%S", &tm
);
713 k
= strptime(t
, "%Y-%m-%d %H:%M:%S", &tm
);
722 k
= strptime(t
, "%y-%m-%d %H:%M", &tm
);
729 k
= strptime(t
, "%Y-%m-%d %H:%M", &tm
);
736 k
= strptime(t
, "%y-%m-%d", &tm
);
738 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
743 k
= strptime(t
, "%Y-%m-%d", &tm
);
745 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
750 k
= strptime(t
, "%H:%M:%S", &tm
);
759 k
= strptime(t
, "%H:%M", &tm
);
772 r
= parse_fractional_part_u(&k
, 6, &add
);
783 if (weekday
>= 0 && tm
.tm_wday
!= weekday
)
786 x
= mktime_or_timegm(&tm
, utc
);
790 ret
= (usec_t
) x
* USEC_PER_SEC
+ x_usec
;
791 if (ret
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
795 if (ret
+ plus
< ret
) /* overflow? */
798 if (ret
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
811 typedef struct ParseTimestampResult
{
814 } ParseTimestampResult
;
816 int parse_timestamp(const char *t
, usec_t
*usec
) {
817 char *last_space
, *tz
= NULL
;
818 ParseTimestampResult
*shared
, tmp
;
821 last_space
= strrchr(t
, ' ');
822 if (last_space
!= NULL
&& timezone_is_valid(last_space
+ 1, LOG_DEBUG
))
825 if (!tz
|| endswith_no_case(t
, " UTC"))
826 return parse_timestamp_impl(t
, usec
, false);
828 shared
= mmap(NULL
, sizeof *shared
, PROT_READ
|PROT_WRITE
, MAP_SHARED
|MAP_ANONYMOUS
, -1, 0);
829 if (shared
== MAP_FAILED
)
830 return negative_errno();
832 r
= safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG
|FORK_WAIT
, NULL
);
834 (void) munmap(shared
, sizeof *shared
);
840 if (setenv("TZ", tz
, 1) != 0) {
841 shared
->return_value
= negative_errno();
847 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
848 * Otherwise just cut it off. */
849 with_tz
= !STR_IN_SET(tz
, tzname
[0], tzname
[1]);
851 /* Cut off the timezone if we don't need it. */
853 t
= strndupa(t
, last_space
- t
);
855 shared
->return_value
= parse_timestamp_impl(t
, &shared
->usec
, with_tz
);
861 if (munmap(shared
, sizeof *shared
) != 0)
862 return negative_errno();
864 if (tmp
.return_value
== 0)
867 return tmp
.return_value
;
870 static const char* extract_multiplier(const char *p
, usec_t
*multiplier
) {
871 static const struct {
875 { "seconds", USEC_PER_SEC
},
876 { "second", USEC_PER_SEC
},
877 { "sec", USEC_PER_SEC
},
878 { "s", USEC_PER_SEC
},
879 { "minutes", USEC_PER_MINUTE
},
880 { "minute", USEC_PER_MINUTE
},
881 { "min", USEC_PER_MINUTE
},
882 { "months", USEC_PER_MONTH
},
883 { "month", USEC_PER_MONTH
},
884 { "M", USEC_PER_MONTH
},
885 { "msec", USEC_PER_MSEC
},
886 { "ms", USEC_PER_MSEC
},
887 { "m", USEC_PER_MINUTE
},
888 { "hours", USEC_PER_HOUR
},
889 { "hour", USEC_PER_HOUR
},
890 { "hr", USEC_PER_HOUR
},
891 { "h", USEC_PER_HOUR
},
892 { "days", USEC_PER_DAY
},
893 { "day", USEC_PER_DAY
},
894 { "d", USEC_PER_DAY
},
895 { "weeks", USEC_PER_WEEK
},
896 { "week", USEC_PER_WEEK
},
897 { "w", USEC_PER_WEEK
},
898 { "years", USEC_PER_YEAR
},
899 { "year", USEC_PER_YEAR
},
900 { "y", USEC_PER_YEAR
},
907 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
910 e
= startswith(p
, table
[i
].suffix
);
912 *multiplier
= table
[i
].usec
;
920 int parse_time(const char *t
, usec_t
*usec
, usec_t default_unit
) {
923 bool something
= false;
927 assert(default_unit
> 0);
931 p
+= strspn(p
, WHITESPACE
);
932 s
= startswith(p
, "infinity");
934 s
+= strspn(s
, WHITESPACE
);
938 *usec
= USEC_INFINITY
;
943 usec_t multiplier
= default_unit
, k
;
947 p
+= strspn(p
, WHITESPACE
);
956 if (*p
== '-') /* Don't allow "-0" */
960 l
= strtoll(p
, &e
, 10);
968 p
+= strspn(p
, DIGITS
);
974 s
= extract_multiplier(p
+ strspn(p
, WHITESPACE
), &multiplier
);
975 if (s
== p
&& *s
!= '\0')
976 /* Don't allow '12.34.56', but accept '12.34 .56' or '12.34s.56'*/
981 if ((usec_t
) l
>= USEC_INFINITY
/ multiplier
)
984 k
= (usec_t
) l
* multiplier
;
985 if (k
>= USEC_INFINITY
- r
)
993 usec_t m
= multiplier
/ 10;
996 for (b
= e
+ 1; *b
>= '0' && *b
<= '9'; b
++, m
/= 10) {
997 k
= (usec_t
) (*b
- '0') * m
;
998 if (k
>= USEC_INFINITY
- r
)
1004 /* Don't allow "0.-0", "3.+1", "3. 1", "3.sec" or "3.hoge"*/
1015 int parse_sec(const char *t
, usec_t
*usec
) {
1016 return parse_time(t
, usec
, USEC_PER_SEC
);
1019 int parse_sec_fix_0(const char *t
, usec_t
*ret
) {
1026 r
= parse_sec(t
, &k
);
1030 *ret
= k
== 0 ? USEC_INFINITY
: k
;
1034 static const char* extract_nsec_multiplier(const char *p
, nsec_t
*multiplier
) {
1035 static const struct {
1039 { "seconds", NSEC_PER_SEC
},
1040 { "second", NSEC_PER_SEC
},
1041 { "sec", NSEC_PER_SEC
},
1042 { "s", NSEC_PER_SEC
},
1043 { "minutes", NSEC_PER_MINUTE
},
1044 { "minute", NSEC_PER_MINUTE
},
1045 { "min", NSEC_PER_MINUTE
},
1046 { "months", NSEC_PER_MONTH
},
1047 { "month", NSEC_PER_MONTH
},
1048 { "M", NSEC_PER_MONTH
},
1049 { "msec", NSEC_PER_MSEC
},
1050 { "ms", NSEC_PER_MSEC
},
1051 { "m", NSEC_PER_MINUTE
},
1052 { "hours", NSEC_PER_HOUR
},
1053 { "hour", NSEC_PER_HOUR
},
1054 { "hr", NSEC_PER_HOUR
},
1055 { "h", NSEC_PER_HOUR
},
1056 { "days", NSEC_PER_DAY
},
1057 { "day", NSEC_PER_DAY
},
1058 { "d", NSEC_PER_DAY
},
1059 { "weeks", NSEC_PER_WEEK
},
1060 { "week", NSEC_PER_WEEK
},
1061 { "w", NSEC_PER_WEEK
},
1062 { "years", NSEC_PER_YEAR
},
1063 { "year", NSEC_PER_YEAR
},
1064 { "y", NSEC_PER_YEAR
},
1065 { "usec", NSEC_PER_USEC
},
1066 { "us", NSEC_PER_USEC
},
1067 { "µs", NSEC_PER_USEC
},
1070 { "", 1ULL }, /* default is nsec */
1074 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
1077 e
= startswith(p
, table
[i
].suffix
);
1079 *multiplier
= table
[i
].nsec
;
1087 int parse_nsec(const char *t
, nsec_t
*nsec
) {
1090 bool something
= false;
1097 p
+= strspn(p
, WHITESPACE
);
1098 s
= startswith(p
, "infinity");
1100 s
+= strspn(s
, WHITESPACE
);
1104 *nsec
= NSEC_INFINITY
;
1109 nsec_t multiplier
= 1, k
;
1113 p
+= strspn(p
, WHITESPACE
);
1122 if (*p
== '-') /* Don't allow "-0" */
1126 l
= strtoll(p
, &e
, 10);
1134 p
+= strspn(p
, DIGITS
);
1140 s
= extract_nsec_multiplier(p
+ strspn(p
, WHITESPACE
), &multiplier
);
1141 if (s
== p
&& *s
!= '\0')
1142 /* Don't allow '12.34.56', but accept '12.34 .56' or '12.34s.56'*/
1147 if ((nsec_t
) l
>= NSEC_INFINITY
/ multiplier
)
1150 k
= (nsec_t
) l
* multiplier
;
1151 if (k
>= NSEC_INFINITY
- r
)
1159 nsec_t m
= multiplier
/ 10;
1162 for (b
= e
+ 1; *b
>= '0' && *b
<= '9'; b
++, m
/= 10) {
1163 k
= (nsec_t
) (*b
- '0') * m
;
1164 if (k
>= NSEC_INFINITY
- r
)
1170 /* Don't allow "0.-0", "3.+1", "3. 1", "3.sec" or "3.hoge"*/
1181 bool ntp_synced(void) {
1182 struct timex txc
= {};
1184 if (adjtimex(&txc
) < 0)
1187 if (txc
.status
& STA_UNSYNC
)
1193 int get_timezones(char ***ret
) {
1194 _cleanup_fclose_
FILE *f
= NULL
;
1195 _cleanup_strv_free_
char **zones
= NULL
;
1196 size_t n_zones
= 0, n_allocated
= 0;
1201 zones
= strv_new("UTC");
1208 f
= fopen("/usr/share/zoneinfo/zone.tab", "re");
1211 _cleanup_free_
char *line
= NULL
;
1215 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1223 if (isempty(p
) || *p
== '#')
1226 /* Skip over country code */
1227 p
+= strcspn(p
, WHITESPACE
);
1228 p
+= strspn(p
, WHITESPACE
);
1230 /* Skip over coordinates */
1231 p
+= strcspn(p
, WHITESPACE
);
1232 p
+= strspn(p
, WHITESPACE
);
1234 /* Found timezone name */
1235 k
= strcspn(p
, WHITESPACE
);
1243 if (!GREEDY_REALLOC(zones
, n_allocated
, n_zones
+ 2)) {
1248 zones
[n_zones
++] = w
;
1249 zones
[n_zones
] = NULL
;
1254 } else if (errno
!= ENOENT
)
1257 *ret
= TAKE_PTR(zones
);
1262 bool timezone_is_valid(const char *name
, int log_level
) {
1265 _cleanup_close_
int fd
= -1;
1275 for (p
= name
; *p
; p
++) {
1276 if (!(*p
>= '0' && *p
<= '9') &&
1277 !(*p
>= 'a' && *p
<= 'z') &&
1278 !(*p
>= 'A' && *p
<= 'Z') &&
1279 !IN_SET(*p
, '-', '_', '+', '/'))
1295 if (p
- name
>= PATH_MAX
)
1298 t
= strjoina("/usr/share/zoneinfo/", name
);
1300 fd
= open(t
, O_RDONLY
|O_CLOEXEC
);
1302 log_full_errno(log_level
, errno
, "Failed to open timezone file '%s': %m", t
);
1306 r
= fd_verify_regular(fd
);
1308 log_full_errno(log_level
, r
, "Timezone file '%s' is not a regular file: %m", t
);
1312 r
= loop_read_exact(fd
, buf
, 4, false);
1314 log_full_errno(log_level
, r
, "Failed to read from timezone file '%s': %m", t
);
1318 /* Magic from tzfile(5) */
1319 if (memcmp(buf
, "TZif", 4) != 0) {
1320 log_full(log_level
, "Timezone file '%s' has wrong magic bytes", t
);
1327 bool clock_boottime_supported(void) {
1328 static int supported
= -1;
1330 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1332 if (supported
< 0) {
1335 fd
= timerfd_create(CLOCK_BOOTTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
1347 clockid_t
clock_boottime_or_monotonic(void) {
1348 if (clock_boottime_supported())
1349 return CLOCK_BOOTTIME
;
1351 return CLOCK_MONOTONIC
;
1354 bool clock_supported(clockid_t clock
) {
1359 case CLOCK_MONOTONIC
:
1360 case CLOCK_REALTIME
:
1363 case CLOCK_BOOTTIME
:
1364 return clock_boottime_supported();
1366 case CLOCK_BOOTTIME_ALARM
:
1367 if (!clock_boottime_supported())
1372 /* For everything else, check properly */
1373 return clock_gettime(clock
, &ts
) >= 0;
1377 int get_timezone(char **tz
) {
1378 _cleanup_free_
char *t
= NULL
;
1383 r
= readlink_malloc("/etc/localtime", &t
);
1385 return r
; /* returns EINVAL if not a symlink */
1387 e
= path_startswith(t
, "/usr/share/zoneinfo/");
1389 e
= path_startswith(t
, "../usr/share/zoneinfo/");
1393 if (!timezone_is_valid(e
, LOG_DEBUG
))
1404 time_t mktime_or_timegm(struct tm
*tm
, bool utc
) {
1405 return utc
? timegm(tm
) : mktime(tm
);
1408 struct tm
*localtime_or_gmtime_r(const time_t *t
, struct tm
*tm
, bool utc
) {
1409 return utc
? gmtime_r(t
, tm
) : localtime_r(t
, tm
);
1412 unsigned long usec_to_jiffies(usec_t u
) {
1413 static thread_local
unsigned long hz
= 0;
1417 r
= sysconf(_SC_CLK_TCK
);
1423 return DIV_ROUND_UP(u
, USEC_PER_SEC
/ hz
);
1426 usec_t
usec_shift_clock(usec_t x
, clockid_t from
, clockid_t to
) {
1429 if (x
== USEC_INFINITY
)
1430 return USEC_INFINITY
;
1431 if (map_clock_id(from
) == map_clock_id(to
))
1438 /* x lies in the future */
1439 return usec_add(b
, usec_sub_unsigned(x
, a
));
1441 /* x lies in the past */
1442 return usec_sub_unsigned(b
, usec_sub_unsigned(a
, x
));
1445 bool in_utc_timezone(void) {
1448 return timezone
== 0 && daylight
== 0;
1451 int time_change_fd(void) {
1453 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1454 static const struct itimerspec its
= {
1455 .it_value
.tv_sec
= TIME_T_MAX
,
1458 _cleanup_close_
int fd
;
1460 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX
));
1462 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1463 * CLOCK_MONOTONIC. */
1465 fd
= timerfd_create(CLOCK_REALTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
1469 if (timerfd_settime(fd
, TFD_TIMER_ABSTIME
|TFD_TIMER_CANCEL_ON_SET
, &its
, NULL
) < 0)