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 "stat-util.h"
27 #include "string-util.h"
29 #include "time-util.h"
31 static clockid_t
map_clock_id(clockid_t c
) {
33 /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus, clock_gettime() will
34 * fail for them. Since they are essentially the same as their non-ALARM pendants (their only difference is
35 * when timers are set on them), let's just map them accordingly. This way, we can get the correct time even on
40 case CLOCK_BOOTTIME_ALARM
:
41 return CLOCK_BOOTTIME
;
43 case CLOCK_REALTIME_ALARM
:
44 return CLOCK_REALTIME
;
51 usec_t
now(clockid_t clock_id
) {
54 assert_se(clock_gettime(map_clock_id(clock_id
), &ts
) == 0);
56 return timespec_load(&ts
);
59 nsec_t
now_nsec(clockid_t clock_id
) {
62 assert_se(clock_gettime(map_clock_id(clock_id
), &ts
) == 0);
64 return timespec_load_nsec(&ts
);
67 dual_timestamp
* dual_timestamp_get(dual_timestamp
*ts
) {
70 ts
->realtime
= now(CLOCK_REALTIME
);
71 ts
->monotonic
= now(CLOCK_MONOTONIC
);
76 triple_timestamp
* triple_timestamp_get(triple_timestamp
*ts
) {
79 ts
->realtime
= now(CLOCK_REALTIME
);
80 ts
->monotonic
= now(CLOCK_MONOTONIC
);
81 ts
->boottime
= clock_boottime_supported() ? now(CLOCK_BOOTTIME
) : USEC_INFINITY
;
86 dual_timestamp
* dual_timestamp_from_realtime(dual_timestamp
*ts
, usec_t u
) {
90 if (u
== USEC_INFINITY
|| u
<= 0) {
91 ts
->realtime
= ts
->monotonic
= u
;
97 delta
= (int64_t) now(CLOCK_REALTIME
) - (int64_t) u
;
98 ts
->monotonic
= usec_sub_signed(now(CLOCK_MONOTONIC
), delta
);
103 triple_timestamp
* triple_timestamp_from_realtime(triple_timestamp
*ts
, usec_t u
) {
108 if (u
== USEC_INFINITY
|| u
<= 0) {
109 ts
->realtime
= ts
->monotonic
= ts
->boottime
= u
;
114 delta
= (int64_t) now(CLOCK_REALTIME
) - (int64_t) u
;
115 ts
->monotonic
= usec_sub_signed(now(CLOCK_MONOTONIC
), delta
);
116 ts
->boottime
= clock_boottime_supported() ? usec_sub_signed(now(CLOCK_BOOTTIME
), delta
) : USEC_INFINITY
;
121 dual_timestamp
* dual_timestamp_from_monotonic(dual_timestamp
*ts
, usec_t u
) {
125 if (u
== USEC_INFINITY
) {
126 ts
->realtime
= ts
->monotonic
= USEC_INFINITY
;
131 delta
= (int64_t) now(CLOCK_MONOTONIC
) - (int64_t) u
;
132 ts
->realtime
= usec_sub_signed(now(CLOCK_REALTIME
), delta
);
137 dual_timestamp
* dual_timestamp_from_boottime_or_monotonic(dual_timestamp
*ts
, usec_t u
) {
140 if (u
== USEC_INFINITY
) {
141 ts
->realtime
= ts
->monotonic
= USEC_INFINITY
;
145 dual_timestamp_get(ts
);
146 delta
= (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u
;
147 ts
->realtime
= usec_sub_signed(ts
->realtime
, delta
);
148 ts
->monotonic
= usec_sub_signed(ts
->monotonic
, delta
);
153 usec_t
triple_timestamp_by_clock(triple_timestamp
*ts
, clockid_t clock
) {
158 case CLOCK_REALTIME_ALARM
:
161 case CLOCK_MONOTONIC
:
162 return ts
->monotonic
;
165 case CLOCK_BOOTTIME_ALARM
:
169 return USEC_INFINITY
;
173 usec_t
timespec_load(const struct timespec
*ts
) {
176 if (ts
->tv_sec
< 0 || ts
->tv_nsec
< 0)
177 return USEC_INFINITY
;
179 if ((usec_t
) ts
->tv_sec
> (UINT64_MAX
- (ts
->tv_nsec
/ NSEC_PER_USEC
)) / USEC_PER_SEC
)
180 return USEC_INFINITY
;
183 (usec_t
) ts
->tv_sec
* USEC_PER_SEC
+
184 (usec_t
) ts
->tv_nsec
/ NSEC_PER_USEC
;
187 nsec_t
timespec_load_nsec(const struct timespec
*ts
) {
190 if (ts
->tv_sec
< 0 || ts
->tv_nsec
< 0)
191 return NSEC_INFINITY
;
193 if ((nsec_t
) ts
->tv_sec
>= (UINT64_MAX
- ts
->tv_nsec
) / NSEC_PER_SEC
)
194 return NSEC_INFINITY
;
196 return (nsec_t
) ts
->tv_sec
* NSEC_PER_SEC
+ (nsec_t
) ts
->tv_nsec
;
199 struct timespec
*timespec_store(struct timespec
*ts
, usec_t u
) {
202 if (u
== USEC_INFINITY
||
203 u
/ USEC_PER_SEC
>= TIME_T_MAX
) {
204 ts
->tv_sec
= (time_t) -1;
205 ts
->tv_nsec
= (long) -1;
209 ts
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
210 ts
->tv_nsec
= (long int) ((u
% USEC_PER_SEC
) * NSEC_PER_USEC
);
215 usec_t
timeval_load(const struct timeval
*tv
) {
218 if (tv
->tv_sec
< 0 || tv
->tv_usec
< 0)
219 return USEC_INFINITY
;
221 if ((usec_t
) tv
->tv_sec
> (UINT64_MAX
- tv
->tv_usec
) / USEC_PER_SEC
)
222 return USEC_INFINITY
;
225 (usec_t
) tv
->tv_sec
* USEC_PER_SEC
+
226 (usec_t
) tv
->tv_usec
;
229 struct timeval
*timeval_store(struct timeval
*tv
, usec_t u
) {
232 if (u
== USEC_INFINITY
||
233 u
/ USEC_PER_SEC
> TIME_T_MAX
) {
234 tv
->tv_sec
= (time_t) -1;
235 tv
->tv_usec
= (suseconds_t
) -1;
237 tv
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
238 tv
->tv_usec
= (suseconds_t
) (u
% USEC_PER_SEC
);
244 static char *format_timestamp_internal(
251 /* The weekdays in non-localized (English) form. We use this instead of the localized form, so that our
252 * generated timestamps may be parsed with parse_timestamp(), and always read the same. */
253 static const char * const weekdays
[] = {
271 1 + 10 + /* space and date */
272 1 + 8 + /* space and time */
273 (us
? 1 + 6 : 0) + /* "." and microsecond part */
274 1 + 1 + /* space and shortest possible zone */
276 return NULL
; /* Not enough space even for the shortest form. */
277 if (t
<= 0 || t
== USEC_INFINITY
)
278 return NULL
; /* Timestamp is unset */
280 /* Let's not format times with years > 9999 */
281 if (t
> USEC_TIMESTAMP_FORMATTABLE_MAX
) {
282 assert(l
>= strlen("--- XXXX-XX-XX XX:XX:XX") + 1);
283 strcpy(buf
, "--- XXXX-XX-XX XX:XX:XX");
287 sec
= (time_t) (t
/ USEC_PER_SEC
); /* Round down */
289 if (!localtime_or_gmtime_r(&sec
, &tm
, utc
))
292 /* Start with the week day */
293 assert((size_t) tm
.tm_wday
< ELEMENTSOF(weekdays
));
294 memcpy(buf
, weekdays
[tm
.tm_wday
], 4);
296 /* Add the main components */
297 if (strftime(buf
+ 3, l
- 3, " %Y-%m-%d %H:%M:%S", &tm
) <= 0)
298 return NULL
; /* Doesn't fit */
300 /* Append the microseconds part, if that's requested */
304 return NULL
; /* Microseconds part doesn't fit. */
306 sprintf(buf
+ n
, ".%06"PRI_USEC
, t
% USEC_PER_SEC
);
309 /* Append the timezone */
312 /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r() normally uses the
313 * obsolete "GMT" instead. */
315 return NULL
; /* "UTC" doesn't fit. */
317 strcpy(buf
+ n
, " UTC");
319 } else if (!isempty(tm
.tm_zone
)) {
322 /* An explicit timezone is specified, let's use it, if it fits */
323 tn
= strlen(tm
.tm_zone
);
324 if (n
+ 1 + tn
+ 1 > l
) {
325 /* The full time zone does not fit in. Yuck. */
327 if (n
+ 1 + _POSIX_TZNAME_MAX
+ 1 > l
)
328 return NULL
; /* Not even enough space for the POSIX minimum (of 6)? In that case, complain that it doesn't fit */
330 /* So the time zone doesn't fit in fully, but the caller passed enough space for the POSIX
331 * minimum time zone length. In this case suppress the timezone entirely, in order not to dump
332 * an overly long, hard to read string on the user. This should be safe, because the user will
333 * assume the local timezone anyway if none is shown. And so does parse_timestamp(). */
336 strcpy(buf
+ n
, tm
.tm_zone
);
343 char *format_timestamp(char *buf
, size_t l
, usec_t t
) {
344 return format_timestamp_internal(buf
, l
, t
, false, false);
347 char *format_timestamp_utc(char *buf
, size_t l
, usec_t t
) {
348 return format_timestamp_internal(buf
, l
, t
, true, false);
351 char *format_timestamp_us(char *buf
, size_t l
, usec_t t
) {
352 return format_timestamp_internal(buf
, l
, t
, false, true);
355 char *format_timestamp_us_utc(char *buf
, size_t l
, usec_t t
) {
356 return format_timestamp_internal(buf
, l
, t
, true, true);
359 char *format_timestamp_relative(char *buf
, size_t l
, usec_t t
) {
363 if (t
<= 0 || t
== USEC_INFINITY
)
366 n
= now(CLOCK_REALTIME
);
375 if (d
>= USEC_PER_YEAR
)
376 snprintf(buf
, l
, USEC_FMT
" years " USEC_FMT
" months %s",
378 (d
% USEC_PER_YEAR
) / USEC_PER_MONTH
, s
);
379 else if (d
>= USEC_PER_MONTH
)
380 snprintf(buf
, l
, USEC_FMT
" months " USEC_FMT
" days %s",
382 (d
% USEC_PER_MONTH
) / USEC_PER_DAY
, s
);
383 else if (d
>= USEC_PER_WEEK
)
384 snprintf(buf
, l
, USEC_FMT
" weeks " USEC_FMT
" days %s",
386 (d
% USEC_PER_WEEK
) / USEC_PER_DAY
, s
);
387 else if (d
>= 2*USEC_PER_DAY
)
388 snprintf(buf
, l
, USEC_FMT
" days %s", d
/ USEC_PER_DAY
, s
);
389 else if (d
>= 25*USEC_PER_HOUR
)
390 snprintf(buf
, l
, "1 day " USEC_FMT
"h %s",
391 (d
- USEC_PER_DAY
) / USEC_PER_HOUR
, s
);
392 else if (d
>= 6*USEC_PER_HOUR
)
393 snprintf(buf
, l
, USEC_FMT
"h %s",
394 d
/ USEC_PER_HOUR
, s
);
395 else if (d
>= USEC_PER_HOUR
)
396 snprintf(buf
, l
, USEC_FMT
"h " USEC_FMT
"min %s",
398 (d
% USEC_PER_HOUR
) / USEC_PER_MINUTE
, s
);
399 else if (d
>= 5*USEC_PER_MINUTE
)
400 snprintf(buf
, l
, USEC_FMT
"min %s",
401 d
/ USEC_PER_MINUTE
, s
);
402 else if (d
>= USEC_PER_MINUTE
)
403 snprintf(buf
, l
, USEC_FMT
"min " USEC_FMT
"s %s",
405 (d
% USEC_PER_MINUTE
) / USEC_PER_SEC
, s
);
406 else if (d
>= USEC_PER_SEC
)
407 snprintf(buf
, l
, USEC_FMT
"s %s",
408 d
/ USEC_PER_SEC
, s
);
409 else if (d
>= USEC_PER_MSEC
)
410 snprintf(buf
, l
, USEC_FMT
"ms %s",
411 d
/ USEC_PER_MSEC
, s
);
413 snprintf(buf
, l
, USEC_FMT
"us %s",
416 snprintf(buf
, l
, "now");
422 char *format_timespan(char *buf
, size_t l
, usec_t t
, usec_t accuracy
) {
423 static const struct {
427 { "y", USEC_PER_YEAR
},
428 { "month", USEC_PER_MONTH
},
429 { "w", USEC_PER_WEEK
},
430 { "d", USEC_PER_DAY
},
431 { "h", USEC_PER_HOUR
},
432 { "min", USEC_PER_MINUTE
},
433 { "s", USEC_PER_SEC
},
434 { "ms", USEC_PER_MSEC
},
440 bool something
= false;
445 if (t
== USEC_INFINITY
) {
446 strncpy(p
, "infinity", l
-1);
452 strncpy(p
, "0", l
-1);
457 /* The result of this function can be parsed with parse_sec */
459 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
468 if (t
< accuracy
&& something
)
471 if (t
< table
[i
].usec
)
477 a
= t
/ table
[i
].usec
;
478 b
= t
% table
[i
].usec
;
480 /* Let's see if we should shows this in dot notation */
481 if (t
< USEC_PER_MINUTE
&& b
> 0) {
486 for (cc
= table
[i
].usec
; cc
> 1; cc
/= 10)
489 for (cc
= accuracy
; cc
> 1; cc
/= 10) {
496 "%s"USEC_FMT
".%0*"PRI_USEC
"%s",
508 /* No? Then let's show it normally */
519 n
= MIN((size_t) k
, l
);
532 void dual_timestamp_serialize(FILE *f
, const char *name
, dual_timestamp
*t
) {
538 if (!dual_timestamp_is_set(t
))
541 fprintf(f
, "%s="USEC_FMT
" "USEC_FMT
"\n",
547 int dual_timestamp_deserialize(const char *value
, dual_timestamp
*t
) {
554 pos
= strspn(value
, WHITESPACE
);
555 if (value
[pos
] == '-')
557 pos
+= strspn(value
+ pos
, DIGITS
);
558 pos
+= strspn(value
+ pos
, WHITESPACE
);
559 if (value
[pos
] == '-')
562 r
= sscanf(value
, "%" PRIu64
"%" PRIu64
"%n", &a
, &b
, &pos
);
564 log_debug("Failed to parse dual timestamp value \"%s\".", value
);
568 if (value
[pos
] != '\0')
569 /* trailing garbage */
578 int timestamp_deserialize(const char *value
, usec_t
*timestamp
) {
583 r
= safe_atou64(value
, timestamp
);
585 return log_debug_errno(r
, "Failed to parse timestamp value \"%s\": %m", value
);
590 static int parse_timestamp_impl(const char *t
, usec_t
*usec
, bool with_tz
) {
591 static const struct {
611 const char *k
, *utc
= NULL
, *tzn
= NULL
;
614 usec_t x_usec
, plus
= 0, minus
= 0, ret
;
615 int r
, weekday
= -1, dst
= -1;
620 * 2012-09-22 16:34:22
621 * 2012-09-22 16:34 (seconds will be set to 0)
622 * 2012-09-22 (time will be set to 00:00:00)
623 * 16:34:22 (date will be set to today)
624 * 16:34 (date will be set to today, seconds to 0)
626 * yesterday (time is set to 00:00:00)
627 * today (time is set to 00:00:00)
628 * tomorrow (time is set to 00:00:00)
631 * @2147483647 (seconds since epoch)
637 if (t
[0] == '@' && !with_tz
)
638 return parse_sec(t
+ 1, usec
);
640 ret
= now(CLOCK_REALTIME
);
646 else if (t
[0] == '+') {
647 r
= parse_sec(t
+1, &plus
);
653 } else if (t
[0] == '-') {
654 r
= parse_sec(t
+1, &minus
);
660 } else if ((k
= endswith(t
, " ago"))) {
661 t
= strndupa(t
, k
- t
);
663 r
= parse_sec(t
, &minus
);
669 } else if ((k
= endswith(t
, " left"))) {
670 t
= strndupa(t
, k
- t
);
672 r
= parse_sec(t
, &plus
);
679 /* See if the timestamp is suffixed with UTC */
680 utc
= endswith_no_case(t
, " UTC");
682 t
= strndupa(t
, utc
- t
);
684 const char *e
= NULL
;
689 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
690 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
691 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
692 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
693 * support arbitrary timezone specifications. */
695 for (j
= 0; j
<= 1; j
++) {
697 if (isempty(tzname
[j
]))
700 e
= endswith_no_case(t
, tzname
[j
]);
711 if (IN_SET(j
, 0, 1)) {
712 /* Found one of the two timezones specified. */
713 t
= strndupa(t
, e
- t
- 1);
720 x
= (time_t) (ret
/ USEC_PER_SEC
);
723 if (!localtime_or_gmtime_r(&x
, &tm
, utc
))
730 if (streq(t
, "today")) {
731 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
734 } else if (streq(t
, "yesterday")) {
736 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
739 } else if (streq(t
, "tomorrow")) {
741 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
745 for (i
= 0; i
< ELEMENTSOF(day_nr
); i
++) {
748 if (!startswith_no_case(t
, day_nr
[i
].name
))
751 skip
= strlen(day_nr
[i
].name
);
755 weekday
= day_nr
[i
].nr
;
761 k
= strptime(t
, "%y-%m-%d %H:%M:%S", &tm
);
770 k
= strptime(t
, "%Y-%m-%d %H:%M:%S", &tm
);
779 k
= strptime(t
, "%y-%m-%d %H:%M", &tm
);
786 k
= strptime(t
, "%Y-%m-%d %H:%M", &tm
);
793 k
= strptime(t
, "%y-%m-%d", &tm
);
795 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
800 k
= strptime(t
, "%Y-%m-%d", &tm
);
802 tm
.tm_sec
= tm
.tm_min
= tm
.tm_hour
= 0;
807 k
= strptime(t
, "%H:%M:%S", &tm
);
816 k
= strptime(t
, "%H:%M", &tm
);
829 r
= parse_fractional_part_u(&k
, 6, &add
);
840 if (weekday
>= 0 && tm
.tm_wday
!= weekday
)
843 x
= mktime_or_timegm(&tm
, utc
);
847 ret
= (usec_t
) x
* USEC_PER_SEC
+ x_usec
;
848 if (ret
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
852 if (ret
+ plus
< ret
) /* overflow? */
855 if (ret
> USEC_TIMESTAMP_FORMATTABLE_MAX
)
868 typedef struct ParseTimestampResult
{
871 } ParseTimestampResult
;
873 int parse_timestamp(const char *t
, usec_t
*usec
) {
874 char *last_space
, *tz
= NULL
;
875 ParseTimestampResult
*shared
, tmp
;
878 last_space
= strrchr(t
, ' ');
879 if (last_space
!= NULL
&& timezone_is_valid(last_space
+ 1, LOG_DEBUG
))
882 if (!tz
|| endswith_no_case(t
, " UTC"))
883 return parse_timestamp_impl(t
, usec
, false);
885 shared
= mmap(NULL
, sizeof *shared
, PROT_READ
|PROT_WRITE
, MAP_SHARED
|MAP_ANONYMOUS
, -1, 0);
886 if (shared
== MAP_FAILED
)
887 return negative_errno();
889 r
= safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG
|FORK_WAIT
, NULL
);
891 (void) munmap(shared
, sizeof *shared
);
897 if (setenv("TZ", tz
, 1) != 0) {
898 shared
->return_value
= negative_errno();
904 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
905 * Otherwise just cut it off. */
906 with_tz
= !STR_IN_SET(tz
, tzname
[0], tzname
[1]);
908 /* Cut off the timezone if we dont need it. */
910 t
= strndupa(t
, last_space
- t
);
912 shared
->return_value
= parse_timestamp_impl(t
, &shared
->usec
, with_tz
);
918 if (munmap(shared
, sizeof *shared
) != 0)
919 return negative_errno();
921 if (tmp
.return_value
== 0)
924 return tmp
.return_value
;
927 static char* extract_multiplier(char *p
, usec_t
*multiplier
) {
928 static const struct {
932 { "seconds", USEC_PER_SEC
},
933 { "second", USEC_PER_SEC
},
934 { "sec", USEC_PER_SEC
},
935 { "s", USEC_PER_SEC
},
936 { "minutes", USEC_PER_MINUTE
},
937 { "minute", USEC_PER_MINUTE
},
938 { "min", USEC_PER_MINUTE
},
939 { "months", USEC_PER_MONTH
},
940 { "month", USEC_PER_MONTH
},
941 { "M", USEC_PER_MONTH
},
942 { "msec", USEC_PER_MSEC
},
943 { "ms", USEC_PER_MSEC
},
944 { "m", USEC_PER_MINUTE
},
945 { "hours", USEC_PER_HOUR
},
946 { "hour", USEC_PER_HOUR
},
947 { "hr", USEC_PER_HOUR
},
948 { "h", USEC_PER_HOUR
},
949 { "days", USEC_PER_DAY
},
950 { "day", USEC_PER_DAY
},
951 { "d", USEC_PER_DAY
},
952 { "weeks", USEC_PER_WEEK
},
953 { "week", USEC_PER_WEEK
},
954 { "w", USEC_PER_WEEK
},
955 { "years", USEC_PER_YEAR
},
956 { "year", USEC_PER_YEAR
},
957 { "y", USEC_PER_YEAR
},
964 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
967 e
= startswith(p
, table
[i
].suffix
);
969 *multiplier
= table
[i
].usec
;
977 int parse_time(const char *t
, usec_t
*usec
, usec_t default_unit
) {
980 bool something
= false;
984 assert(default_unit
> 0);
988 p
+= strspn(p
, WHITESPACE
);
989 s
= startswith(p
, "infinity");
991 s
+= strspn(s
, WHITESPACE
);
995 *usec
= USEC_INFINITY
;
1000 usec_t multiplier
= default_unit
, k
;
1005 p
+= strspn(p
, WHITESPACE
);
1014 if (*p
== '-') /* Don't allow "-0" */
1018 l
= strtoll(p
, &e
, 10);
1027 /* Don't allow "0.-0", "3.+1" or "3. 1" */
1028 if (*b
== '-' || *b
== '+' || isspace(*b
))
1032 z
= strtoll(b
, &e
, 10);
1045 e
+= strspn(e
, WHITESPACE
);
1046 p
= extract_multiplier(e
, &multiplier
);
1050 k
= (usec_t
) z
* multiplier
;
1055 r
+= (usec_t
) l
* multiplier
+ k
;
1063 int parse_sec(const char *t
, usec_t
*usec
) {
1064 return parse_time(t
, usec
, USEC_PER_SEC
);
1067 int parse_sec_fix_0(const char *t
, usec_t
*usec
) {
1071 t
+= strspn(t
, WHITESPACE
);
1073 if (streq(t
, "0")) {
1074 *usec
= USEC_INFINITY
;
1078 return parse_sec(t
, usec
);
1081 int parse_nsec(const char *t
, nsec_t
*nsec
) {
1082 static const struct {
1086 { "seconds", NSEC_PER_SEC
},
1087 { "second", NSEC_PER_SEC
},
1088 { "sec", NSEC_PER_SEC
},
1089 { "s", NSEC_PER_SEC
},
1090 { "minutes", NSEC_PER_MINUTE
},
1091 { "minute", NSEC_PER_MINUTE
},
1092 { "min", NSEC_PER_MINUTE
},
1093 { "months", NSEC_PER_MONTH
},
1094 { "month", NSEC_PER_MONTH
},
1095 { "msec", NSEC_PER_MSEC
},
1096 { "ms", NSEC_PER_MSEC
},
1097 { "m", NSEC_PER_MINUTE
},
1098 { "hours", NSEC_PER_HOUR
},
1099 { "hour", NSEC_PER_HOUR
},
1100 { "hr", NSEC_PER_HOUR
},
1101 { "h", NSEC_PER_HOUR
},
1102 { "days", NSEC_PER_DAY
},
1103 { "day", NSEC_PER_DAY
},
1104 { "d", NSEC_PER_DAY
},
1105 { "weeks", NSEC_PER_WEEK
},
1106 { "week", NSEC_PER_WEEK
},
1107 { "w", NSEC_PER_WEEK
},
1108 { "years", NSEC_PER_YEAR
},
1109 { "year", NSEC_PER_YEAR
},
1110 { "y", NSEC_PER_YEAR
},
1111 { "usec", NSEC_PER_USEC
},
1112 { "us", NSEC_PER_USEC
},
1113 { "µs", NSEC_PER_USEC
},
1116 { "", 1ULL }, /* default is nsec */
1121 bool something
= false;
1128 p
+= strspn(p
, WHITESPACE
);
1129 s
= startswith(p
, "infinity");
1131 s
+= strspn(s
, WHITESPACE
);
1135 *nsec
= NSEC_INFINITY
;
1144 p
+= strspn(p
, WHITESPACE
);
1157 l
= strtoll(p
, &e
, 10);
1166 if (*b
== '-' || *b
== '+' || isspace(*b
))
1170 z
= strtoll(b
, &e
, 10);
1183 e
+= strspn(e
, WHITESPACE
);
1185 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
1186 if (startswith(e
, table
[i
].suffix
)) {
1187 nsec_t k
= (nsec_t
) z
* table
[i
].nsec
;
1192 r
+= (nsec_t
) l
* table
[i
].nsec
+ k
;
1193 p
= e
+ strlen(table
[i
].suffix
);
1199 if (i
>= ELEMENTSOF(table
))
1209 bool ntp_synced(void) {
1210 struct timex txc
= {};
1212 if (adjtimex(&txc
) < 0)
1215 if (txc
.status
& STA_UNSYNC
)
1221 int get_timezones(char ***ret
) {
1222 _cleanup_fclose_
FILE *f
= NULL
;
1223 _cleanup_strv_free_
char **zones
= NULL
;
1224 size_t n_zones
= 0, n_allocated
= 0;
1228 zones
= strv_new("UTC", NULL
);
1235 f
= fopen("/usr/share/zoneinfo/zone.tab", "re");
1239 FOREACH_LINE(l
, f
, return -errno
) {
1245 if (isempty(p
) || *p
== '#')
1248 /* Skip over country code */
1249 p
+= strcspn(p
, WHITESPACE
);
1250 p
+= strspn(p
, WHITESPACE
);
1252 /* Skip over coordinates */
1253 p
+= strcspn(p
, WHITESPACE
);
1254 p
+= strspn(p
, WHITESPACE
);
1256 /* Found timezone name */
1257 k
= strcspn(p
, WHITESPACE
);
1265 if (!GREEDY_REALLOC(zones
, n_allocated
, n_zones
+ 2)) {
1270 zones
[n_zones
++] = w
;
1271 zones
[n_zones
] = NULL
;
1276 } else if (errno
!= ENOENT
)
1279 *ret
= TAKE_PTR(zones
);
1284 bool timezone_is_valid(const char *name
, int log_level
) {
1287 _cleanup_close_
int fd
= -1;
1297 for (p
= name
; *p
; p
++) {
1298 if (!(*p
>= '0' && *p
<= '9') &&
1299 !(*p
>= 'a' && *p
<= 'z') &&
1300 !(*p
>= 'A' && *p
<= 'Z') &&
1301 !IN_SET(*p
, '-', '_', '+', '/'))
1317 if (p
- name
>= PATH_MAX
)
1320 t
= strjoina("/usr/share/zoneinfo/", name
);
1322 fd
= open(t
, O_RDONLY
|O_CLOEXEC
);
1324 log_full_errno(log_level
, errno
, "Failed to open timezone file '%s': %m", t
);
1328 r
= fd_verify_regular(fd
);
1330 log_full_errno(log_level
, r
, "Timezone file '%s' is not a regular file: %m", t
);
1334 r
= loop_read_exact(fd
, buf
, 4, false);
1336 log_full_errno(log_level
, r
, "Failed to read from timezone file '%s': %m", t
);
1340 /* Magic from tzfile(5) */
1341 if (memcmp(buf
, "TZif", 4) != 0) {
1342 log_full(log_level
, "Timezone file '%s' has wrong magic bytes", t
);
1349 bool clock_boottime_supported(void) {
1350 static int supported
= -1;
1352 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1354 if (supported
< 0) {
1357 fd
= timerfd_create(CLOCK_BOOTTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
1369 clockid_t
clock_boottime_or_monotonic(void) {
1370 if (clock_boottime_supported())
1371 return CLOCK_BOOTTIME
;
1373 return CLOCK_MONOTONIC
;
1376 bool clock_supported(clockid_t clock
) {
1381 case CLOCK_MONOTONIC
:
1382 case CLOCK_REALTIME
:
1385 case CLOCK_BOOTTIME
:
1386 return clock_boottime_supported();
1388 case CLOCK_BOOTTIME_ALARM
:
1389 if (!clock_boottime_supported())
1394 /* For everything else, check properly */
1395 return clock_gettime(clock
, &ts
) >= 0;
1399 int get_timezone(char **tz
) {
1400 _cleanup_free_
char *t
= NULL
;
1405 r
= readlink_malloc("/etc/localtime", &t
);
1407 return r
; /* returns EINVAL if not a symlink */
1409 e
= path_startswith(t
, "/usr/share/zoneinfo/");
1411 e
= path_startswith(t
, "../usr/share/zoneinfo/");
1415 if (!timezone_is_valid(e
, LOG_DEBUG
))
1426 time_t mktime_or_timegm(struct tm
*tm
, bool utc
) {
1427 return utc
? timegm(tm
) : mktime(tm
);
1430 struct tm
*localtime_or_gmtime_r(const time_t *t
, struct tm
*tm
, bool utc
) {
1431 return utc
? gmtime_r(t
, tm
) : localtime_r(t
, tm
);
1434 unsigned long usec_to_jiffies(usec_t u
) {
1435 static thread_local
unsigned long hz
= 0;
1439 r
= sysconf(_SC_CLK_TCK
);
1445 return DIV_ROUND_UP(u
, USEC_PER_SEC
/ hz
);
1448 usec_t
usec_shift_clock(usec_t x
, clockid_t from
, clockid_t to
) {
1451 if (x
== USEC_INFINITY
)
1452 return USEC_INFINITY
;
1453 if (map_clock_id(from
) == map_clock_id(to
))
1460 /* x lies in the future */
1461 return usec_add(b
, usec_sub_unsigned(x
, a
));
1463 /* x lies in the past */
1464 return usec_sub_unsigned(b
, usec_sub_unsigned(a
, x
));
1467 bool in_utc_timezone(void) {
1470 return timezone
== 0 && daylight
== 0;
1473 int time_change_fd(void) {
1475 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1476 static const struct itimerspec its
= {
1477 .it_value
.tv_sec
= TIME_T_MAX
,
1480 _cleanup_close_
int fd
;
1482 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX
));
1484 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1485 * CLOCK_MONOTONIC. */
1487 fd
= timerfd_create(CLOCK_REALTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
1491 if (timerfd_settime(fd
, TFD_TIMER_ABSTIME
|TFD_TIMER_CANCEL_ON_SET
, &its
, NULL
) < 0)