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"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "process-util.h"
27 #include "serialize.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 static int parse_timestamp_impl(const char *t
, usec_t
*usec
, bool with_tz
) {
535 static const struct {
555 const char *k
, *utc
= NULL
, *tzn
= NULL
;
558 usec_t x_usec
, plus
= 0, minus
= 0, ret
;
559 int r
, weekday
= -1, dst
= -1;
564 * 2012-09-22 16:34:22
565 * 2012-09-22 16:34 (seconds will be set to 0)
566 * 2012-09-22 (time will be set to 00:00:00)
567 * 16:34:22 (date will be set to today)
568 * 16:34 (date will be set to today, seconds to 0)
570 * yesterday (time is set to 00:00:00)
571 * today (time is set to 00:00:00)
572 * tomorrow (time is set to 00:00:00)
575 * @2147483647 (seconds since epoch)
581 if (t
[0] == '@' && !with_tz
)
582 return parse_sec(t
+ 1, usec
);
584 ret
= now(CLOCK_REALTIME
);
590 else if (t
[0] == '+') {
591 r
= parse_sec(t
+1, &plus
);
597 } else if (t
[0] == '-') {
598 r
= parse_sec(t
+1, &minus
);
604 } else if ((k
= endswith(t
, " ago"))) {
605 t
= strndupa(t
, k
- t
);
607 r
= parse_sec(t
, &minus
);
613 } else if ((k
= endswith(t
, " left"))) {
614 t
= strndupa(t
, k
- t
);
616 r
= parse_sec(t
, &plus
);
623 /* See if the timestamp is suffixed with UTC */
624 utc
= endswith_no_case(t
, " UTC");
626 t
= strndupa(t
, utc
- t
);
628 const char *e
= NULL
;
633 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
634 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
635 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
636 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
637 * support arbitrary timezone specifications. */
639 for (j
= 0; j
<= 1; j
++) {
641 if (isempty(tzname
[j
]))
644 e
= endswith_no_case(t
, tzname
[j
]);
655 if (IN_SET(j
, 0, 1)) {
656 /* Found one of the two timezones specified. */
657 t
= strndupa(t
, e
- t
- 1);
664 x
= (time_t) (ret
/ USEC_PER_SEC
);
667 if (!localtime_or_gmtime_r(&x
, &tm
, utc
))
674 if (streq(t
, "today")) {
675 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
678 } else if (streq(t
, "yesterday")) {
680 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
683 } else if (streq(t
, "tomorrow")) {
685 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
689 for (i
= 0; i
< ELEMENTSOF(day_nr
); i
++) {
692 if (!startswith_no_case(t
, day_nr
[i
].name
))
695 skip
= strlen(day_nr
[i
].name
);
699 weekday
= day_nr
[i
].nr
;
705 k
= strptime(t
, "%y-%m-%d %H:%M:%S", &tm
);
714 k
= strptime(t
, "%Y-%m-%d %H:%M:%S", &tm
);
723 k
= strptime(t
, "%y-%m-%d %H:%M", &tm
);
730 k
= strptime(t
, "%Y-%m-%d %H:%M", &tm
);
737 k
= strptime(t
, "%y-%m-%d", &tm
);
739 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
744 k
= strptime(t
, "%Y-%m-%d", &tm
);
746 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
751 k
= strptime(t
, "%H:%M:%S", &tm
);
760 k
= strptime(t
, "%H:%M", &tm
);
773 r
= parse_fractional_part_u(&k
, 6, &add
);
784 if (weekday
>= 0 && tm
.tm_wday
!= weekday
)
787 x
= mktime_or_timegm(&tm
, utc
);
791 ret
= (usec_t
) x
* USEC_PER_SEC
+ x_usec
;
792 if (ret
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
796 if (ret
+ plus
< ret
) /* overflow? */
799 if (ret
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
812 typedef struct ParseTimestampResult
{
815 } ParseTimestampResult
;
817 int parse_timestamp(const char *t
, usec_t
*usec
) {
818 char *last_space
, *tz
= NULL
;
819 ParseTimestampResult
*shared
, tmp
;
822 last_space
= strrchr(t
, ' ');
823 if (last_space
!= NULL
&& timezone_is_valid(last_space
+ 1, LOG_DEBUG
))
826 if (!tz
|| endswith_no_case(t
, " UTC"))
827 return parse_timestamp_impl(t
, usec
, false);
829 shared
= mmap(NULL
, sizeof *shared
, PROT_READ
|PROT_WRITE
, MAP_SHARED
|MAP_ANONYMOUS
, -1, 0);
830 if (shared
== MAP_FAILED
)
831 return negative_errno();
833 r
= safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG
|FORK_WAIT
, NULL
);
835 (void) munmap(shared
, sizeof *shared
);
841 if (setenv("TZ", tz
, 1) != 0) {
842 shared
->return_value
= negative_errno();
848 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
849 * Otherwise just cut it off. */
850 with_tz
= !STR_IN_SET(tz
, tzname
[0], tzname
[1]);
852 /* Cut off the timezone if we don't need it. */
854 t
= strndupa(t
, last_space
- t
);
856 shared
->return_value
= parse_timestamp_impl(t
, &shared
->usec
, with_tz
);
862 if (munmap(shared
, sizeof *shared
) != 0)
863 return negative_errno();
865 if (tmp
.return_value
== 0)
868 return tmp
.return_value
;
871 static char* extract_multiplier(char *p
, usec_t
*multiplier
) {
872 static const struct {
876 { "seconds", USEC_PER_SEC
},
877 { "second", USEC_PER_SEC
},
878 { "sec", USEC_PER_SEC
},
879 { "s", USEC_PER_SEC
},
880 { "minutes", USEC_PER_MINUTE
},
881 { "minute", USEC_PER_MINUTE
},
882 { "min", USEC_PER_MINUTE
},
883 { "months", USEC_PER_MONTH
},
884 { "month", USEC_PER_MONTH
},
885 { "M", USEC_PER_MONTH
},
886 { "msec", USEC_PER_MSEC
},
887 { "ms", USEC_PER_MSEC
},
888 { "m", USEC_PER_MINUTE
},
889 { "hours", USEC_PER_HOUR
},
890 { "hour", USEC_PER_HOUR
},
891 { "hr", USEC_PER_HOUR
},
892 { "h", USEC_PER_HOUR
},
893 { "days", USEC_PER_DAY
},
894 { "day", USEC_PER_DAY
},
895 { "d", USEC_PER_DAY
},
896 { "weeks", USEC_PER_WEEK
},
897 { "week", USEC_PER_WEEK
},
898 { "w", USEC_PER_WEEK
},
899 { "years", USEC_PER_YEAR
},
900 { "year", USEC_PER_YEAR
},
901 { "y", USEC_PER_YEAR
},
908 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
911 e
= startswith(p
, table
[i
].suffix
);
913 *multiplier
= table
[i
].usec
;
921 int parse_time(const char *t
, usec_t
*usec
, usec_t default_unit
) {
924 bool something
= false;
928 assert(default_unit
> 0);
932 p
+= strspn(p
, WHITESPACE
);
933 s
= startswith(p
, "infinity");
935 s
+= strspn(s
, WHITESPACE
);
939 *usec
= USEC_INFINITY
;
944 usec_t multiplier
= default_unit
, k
;
949 p
+= strspn(p
, WHITESPACE
);
958 if (*p
== '-') /* Don't allow "-0" */
962 l
= strtoll(p
, &e
, 10);
971 /* Don't allow "0.-0", "3.+1" or "3. 1" */
972 if (IN_SET(*b
, '-', '+') || isspace(*b
))
976 z
= strtoll(b
, &e
, 10);
989 e
+= strspn(e
, WHITESPACE
);
990 p
= extract_multiplier(e
, &multiplier
);
995 k
= ((usec_t
) -1) / multiplier
;
996 if ((usec_t
) l
+ 1 >= k
|| (usec_t
) z
>= k
)
999 k
= (usec_t
) z
* multiplier
;
1004 k
+= (usec_t
) l
* multiplier
;
1005 if (k
>= ((usec_t
) -1) - r
)
1016 int parse_sec(const char *t
, usec_t
*usec
) {
1017 return parse_time(t
, usec
, USEC_PER_SEC
);
1020 int parse_sec_fix_0(const char *t
, usec_t
*ret
) {
1027 r
= parse_sec(t
, &k
);
1031 *ret
= k
== 0 ? USEC_INFINITY
: k
;
1035 int parse_nsec(const char *t
, nsec_t
*nsec
) {
1036 static const struct {
1040 { "seconds", NSEC_PER_SEC
},
1041 { "second", NSEC_PER_SEC
},
1042 { "sec", NSEC_PER_SEC
},
1043 { "s", NSEC_PER_SEC
},
1044 { "minutes", NSEC_PER_MINUTE
},
1045 { "minute", NSEC_PER_MINUTE
},
1046 { "min", NSEC_PER_MINUTE
},
1047 { "months", NSEC_PER_MONTH
},
1048 { "month", 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 */
1075 bool something
= false;
1082 p
+= strspn(p
, WHITESPACE
);
1083 s
= startswith(p
, "infinity");
1085 s
+= strspn(s
, WHITESPACE
);
1089 *nsec
= NSEC_INFINITY
;
1098 p
+= strspn(p
, WHITESPACE
);
1111 l
= strtoll(p
, &e
, 10);
1120 if (IN_SET(*b
, '-', '+') || isspace(*b
))
1124 z
= strtoll(b
, &e
, 10);
1137 e
+= strspn(e
, WHITESPACE
);
1139 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
1140 if (startswith(e
, table
[i
].suffix
)) {
1143 k
= ((nsec_t
) -1) / table
[i
].nsec
;
1144 if ((nsec_t
) l
+ 1 >= k
|| (nsec_t
) z
>= k
)
1147 k
= (nsec_t
) z
* table
[i
].nsec
;
1152 k
+= (nsec_t
) l
* table
[i
].nsec
;
1153 if (k
>= ((nsec_t
) -1) - r
)
1157 p
= e
+ strlen(table
[i
].suffix
);
1163 if (i
>= ELEMENTSOF(table
))
1173 bool ntp_synced(void) {
1174 struct timex txc
= {};
1176 if (adjtimex(&txc
) < 0)
1179 if (txc
.status
& STA_UNSYNC
)
1185 int get_timezones(char ***ret
) {
1186 _cleanup_fclose_
FILE *f
= NULL
;
1187 _cleanup_strv_free_
char **zones
= NULL
;
1188 size_t n_zones
= 0, n_allocated
= 0;
1193 zones
= strv_new("UTC", NULL
);
1200 f
= fopen("/usr/share/zoneinfo/zone.tab", "re");
1203 _cleanup_free_
char *line
= NULL
;
1207 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1215 if (isempty(p
) || *p
== '#')
1218 /* Skip over country code */
1219 p
+= strcspn(p
, WHITESPACE
);
1220 p
+= strspn(p
, WHITESPACE
);
1222 /* Skip over coordinates */
1223 p
+= strcspn(p
, WHITESPACE
);
1224 p
+= strspn(p
, WHITESPACE
);
1226 /* Found timezone name */
1227 k
= strcspn(p
, WHITESPACE
);
1235 if (!GREEDY_REALLOC(zones
, n_allocated
, n_zones
+ 2)) {
1240 zones
[n_zones
++] = w
;
1241 zones
[n_zones
] = NULL
;
1246 } else if (errno
!= ENOENT
)
1249 *ret
= TAKE_PTR(zones
);
1254 bool timezone_is_valid(const char *name
, int log_level
) {
1257 _cleanup_close_
int fd
= -1;
1267 for (p
= name
; *p
; p
++) {
1268 if (!(*p
>= '0' && *p
<= '9') &&
1269 !(*p
>= 'a' && *p
<= 'z') &&
1270 !(*p
>= 'A' && *p
<= 'Z') &&
1271 !IN_SET(*p
, '-', '_', '+', '/'))
1287 if (p
- name
>= PATH_MAX
)
1290 t
= strjoina("/usr/share/zoneinfo/", name
);
1292 fd
= open(t
, O_RDONLY
|O_CLOEXEC
);
1294 log_full_errno(log_level
, errno
, "Failed to open timezone file '%s': %m", t
);
1298 r
= fd_verify_regular(fd
);
1300 log_full_errno(log_level
, r
, "Timezone file '%s' is not a regular file: %m", t
);
1304 r
= loop_read_exact(fd
, buf
, 4, false);
1306 log_full_errno(log_level
, r
, "Failed to read from timezone file '%s': %m", t
);
1310 /* Magic from tzfile(5) */
1311 if (memcmp(buf
, "TZif", 4) != 0) {
1312 log_full(log_level
, "Timezone file '%s' has wrong magic bytes", t
);
1319 bool clock_boottime_supported(void) {
1320 static int supported
= -1;
1322 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1324 if (supported
< 0) {
1327 fd
= timerfd_create(CLOCK_BOOTTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
1339 clockid_t
clock_boottime_or_monotonic(void) {
1340 if (clock_boottime_supported())
1341 return CLOCK_BOOTTIME
;
1343 return CLOCK_MONOTONIC
;
1346 bool clock_supported(clockid_t clock
) {
1351 case CLOCK_MONOTONIC
:
1352 case CLOCK_REALTIME
:
1355 case CLOCK_BOOTTIME
:
1356 return clock_boottime_supported();
1358 case CLOCK_BOOTTIME_ALARM
:
1359 if (!clock_boottime_supported())
1364 /* For everything else, check properly */
1365 return clock_gettime(clock
, &ts
) >= 0;
1369 int get_timezone(char **tz
) {
1370 _cleanup_free_
char *t
= NULL
;
1375 r
= readlink_malloc("/etc/localtime", &t
);
1377 return r
; /* returns EINVAL if not a symlink */
1379 e
= path_startswith(t
, "/usr/share/zoneinfo/");
1381 e
= path_startswith(t
, "../usr/share/zoneinfo/");
1385 if (!timezone_is_valid(e
, LOG_DEBUG
))
1396 time_t mktime_or_timegm(struct tm
*tm
, bool utc
) {
1397 return utc
? timegm(tm
) : mktime(tm
);
1400 struct tm
*localtime_or_gmtime_r(const time_t *t
, struct tm
*tm
, bool utc
) {
1401 return utc
? gmtime_r(t
, tm
) : localtime_r(t
, tm
);
1404 unsigned long usec_to_jiffies(usec_t u
) {
1405 static thread_local
unsigned long hz
= 0;
1409 r
= sysconf(_SC_CLK_TCK
);
1415 return DIV_ROUND_UP(u
, USEC_PER_SEC
/ hz
);
1418 usec_t
usec_shift_clock(usec_t x
, clockid_t from
, clockid_t to
) {
1421 if (x
== USEC_INFINITY
)
1422 return USEC_INFINITY
;
1423 if (map_clock_id(from
) == map_clock_id(to
))
1430 /* x lies in the future */
1431 return usec_add(b
, usec_sub_unsigned(x
, a
));
1433 /* x lies in the past */
1434 return usec_sub_unsigned(b
, usec_sub_unsigned(a
, x
));
1437 bool in_utc_timezone(void) {
1440 return timezone
== 0 && daylight
== 0;
1443 int time_change_fd(void) {
1445 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1446 static const struct itimerspec its
= {
1447 .it_value
.tv_sec
= TIME_T_MAX
,
1450 _cleanup_close_
int fd
;
1452 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX
));
1454 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1455 * CLOCK_MONOTONIC. */
1457 fd
= timerfd_create(CLOCK_REALTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
1461 if (timerfd_settime(fd
, TFD_TIMER_ABSTIME
|TFD_TIMER_CANCEL_ON_SET
, &its
, NULL
) < 0)