2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
27 #include <sys/timerfd.h>
28 #include <sys/timex.h>
29 #include <sys/types.h>
32 #include "alloc-util.h"
38 #include "parse-util.h"
39 #include "path-util.h"
40 #include "string-util.h"
42 #include "time-util.h"
44 static clockid_t map_clock_id(clockid_t c) {
46 /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus, clock_gettime() will
47 * fail for them. Since they are essentially the same as their non-ALARM pendants (their only difference is
48 * when timers are set on them), let's just map them accordingly. This way, we can get the correct time even on
53 case CLOCK_BOOTTIME_ALARM:
54 return CLOCK_BOOTTIME;
56 case CLOCK_REALTIME_ALARM:
57 return CLOCK_REALTIME;
64 usec_t now(clockid_t clock_id) {
67 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
69 return timespec_load(&ts);
72 #if 0 /// UNNEEDED by elogind
73 nsec_t now_nsec(clockid_t clock_id) {
76 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
78 return timespec_load_nsec(&ts);
82 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
85 ts->realtime = now(CLOCK_REALTIME);
86 ts->monotonic = now(CLOCK_MONOTONIC);
91 triple_timestamp* triple_timestamp_get(triple_timestamp *ts) {
94 ts->realtime = now(CLOCK_REALTIME);
95 ts->monotonic = now(CLOCK_MONOTONIC);
96 ts->boottime = clock_boottime_supported() ? now(CLOCK_BOOTTIME) : USEC_INFINITY;
101 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
105 if (u == USEC_INFINITY || u <= 0) {
106 ts->realtime = ts->monotonic = u;
112 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
113 ts->monotonic = usec_sub_signed(now(CLOCK_MONOTONIC), delta);
118 #if 0 /// UNNEEDED by elogind
119 triple_timestamp* triple_timestamp_from_realtime(triple_timestamp *ts, usec_t u) {
124 if (u == USEC_INFINITY || u <= 0) {
125 ts->realtime = ts->monotonic = ts->boottime = u;
130 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
131 ts->monotonic = usec_sub_signed(now(CLOCK_MONOTONIC), delta);
132 ts->boottime = clock_boottime_supported() ? usec_sub_signed(now(CLOCK_BOOTTIME), delta) : USEC_INFINITY;
137 dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
141 if (u == USEC_INFINITY) {
142 ts->realtime = ts->monotonic = USEC_INFINITY;
147 delta = (int64_t) now(CLOCK_MONOTONIC) - (int64_t) u;
148 ts->realtime = usec_sub_signed(now(CLOCK_REALTIME), delta);
153 dual_timestamp* dual_timestamp_from_boottime_or_monotonic(dual_timestamp *ts, usec_t u) {
156 if (u == USEC_INFINITY) {
157 ts->realtime = ts->monotonic = USEC_INFINITY;
161 dual_timestamp_get(ts);
162 delta = (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u;
163 ts->realtime = usec_sub_signed(ts->realtime, delta);
164 ts->monotonic = usec_sub_signed(ts->monotonic, delta);
170 usec_t triple_timestamp_by_clock(triple_timestamp *ts, clockid_t clock) {
175 case CLOCK_REALTIME_ALARM:
178 case CLOCK_MONOTONIC:
179 return ts->monotonic;
182 case CLOCK_BOOTTIME_ALARM:
186 return USEC_INFINITY;
190 usec_t timespec_load(const struct timespec *ts) {
193 if (ts->tv_sec < 0 || ts->tv_nsec < 0)
194 return USEC_INFINITY;
196 if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
197 return USEC_INFINITY;
200 (usec_t) ts->tv_sec * USEC_PER_SEC +
201 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
204 #if 0 /// UNNEEDED by elogind
205 nsec_t timespec_load_nsec(const struct timespec *ts) {
208 if (ts->tv_sec < 0 || ts->tv_nsec < 0)
209 return NSEC_INFINITY;
211 if ((nsec_t) ts->tv_sec >= (UINT64_MAX - ts->tv_nsec) / NSEC_PER_SEC)
212 return NSEC_INFINITY;
214 return (nsec_t) ts->tv_sec * NSEC_PER_SEC + (nsec_t) ts->tv_nsec;
218 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
221 if (u == USEC_INFINITY ||
222 u / USEC_PER_SEC >= TIME_T_MAX) {
223 ts->tv_sec = (time_t) -1;
224 ts->tv_nsec = (long) -1;
228 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
229 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
234 usec_t timeval_load(const struct timeval *tv) {
237 if (tv->tv_sec < 0 || tv->tv_usec < 0)
238 return USEC_INFINITY;
240 if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
241 return USEC_INFINITY;
244 (usec_t) tv->tv_sec * USEC_PER_SEC +
245 (usec_t) tv->tv_usec;
248 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
251 if (u == USEC_INFINITY ||
252 u / USEC_PER_SEC > TIME_T_MAX) {
253 tv->tv_sec = (time_t) -1;
254 tv->tv_usec = (suseconds_t) -1;
256 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
257 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
263 static char *format_timestamp_internal(
270 /* The weekdays in non-localized (English) form. We use this instead of the localized form, so that our
271 * generated timestamps may be parsed with parse_timestamp(), and always read the same. */
272 static const char * const weekdays[] = {
290 1 + 10 + /* space and date */
291 1 + 8 + /* space and time */
292 (us ? 1 + 6 : 0) + /* "." and microsecond part */
293 1 + 1 + /* space and shortest possible zone */
295 return NULL; /* Not enough space even for the shortest form. */
296 if (t <= 0 || t == USEC_INFINITY)
297 return NULL; /* Timestamp is unset */
299 /* Let's not format times with years > 9999 */
300 if (t > USEC_TIMESTAMP_FORMATTABLE_MAX)
303 sec = (time_t) (t / USEC_PER_SEC); /* Round down */
305 if (!localtime_or_gmtime_r(&sec, &tm, utc))
308 /* Start with the week day */
309 assert((size_t) tm.tm_wday < ELEMENTSOF(weekdays));
310 memcpy(buf, weekdays[tm.tm_wday], 4);
312 /* Add the main components */
313 if (strftime(buf + 3, l - 3, " %Y-%m-%d %H:%M:%S", &tm) <= 0)
314 return NULL; /* Doesn't fit */
316 /* Append the microseconds part, if that's requested */
320 return NULL; /* Microseconds part doesn't fit. */
322 sprintf(buf + n, ".%06"PRI_USEC, t % USEC_PER_SEC);
325 /* Append the timezone */
328 /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r() normally uses the
329 * obsolete "GMT" instead. */
331 return NULL; /* "UTC" doesn't fit. */
333 strcpy(buf + n, " UTC");
335 } else if (!isempty(tm.tm_zone)) {
338 /* An explicit timezone is specified, let's use it, if it fits */
339 tn = strlen(tm.tm_zone);
340 if (n + 1 + tn + 1 > l) {
341 /* The full time zone does not fit in. Yuck. */
343 if (n + 1 + _POSIX_TZNAME_MAX + 1 > l)
344 return NULL; /* Not even enough space for the POSIX minimum (of 6)? In that case, complain that it doesn't fit */
346 /* So the time zone doesn't fit in fully, but the caller passed enough space for the POSIX
347 * minimum time zone length. In this case suppress the timezone entirely, in order not to dump
348 * an overly long, hard to read string on the user. This should be safe, because the user will
349 * assume the local timezone anyway if none is shown. And so does parse_timestamp(). */
352 strcpy(buf + n, tm.tm_zone);
359 char *format_timestamp(char *buf, size_t l, usec_t t) {
360 return format_timestamp_internal(buf, l, t, false, false);
363 #if 0 /// UNNEEDED by elogind
364 char *format_timestamp_utc(char *buf, size_t l, usec_t t) {
365 return format_timestamp_internal(buf, l, t, true, false);
369 char *format_timestamp_us(char *buf, size_t l, usec_t t) {
370 return format_timestamp_internal(buf, l, t, false, true);
373 #if 0 /// UNNEEDED by elogind
374 char *format_timestamp_us_utc(char *buf, size_t l, usec_t t) {
375 return format_timestamp_internal(buf, l, t, true, true);
379 char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
383 if (t <= 0 || t == USEC_INFINITY)
386 n = now(CLOCK_REALTIME);
395 if (d >= USEC_PER_YEAR)
396 snprintf(buf, l, USEC_FMT " years " USEC_FMT " months %s",
398 (d % USEC_PER_YEAR) / USEC_PER_MONTH, s);
399 else if (d >= USEC_PER_MONTH)
400 snprintf(buf, l, USEC_FMT " months " USEC_FMT " days %s",
402 (d % USEC_PER_MONTH) / USEC_PER_DAY, s);
403 else if (d >= USEC_PER_WEEK)
404 snprintf(buf, l, USEC_FMT " weeks " USEC_FMT " days %s",
406 (d % USEC_PER_WEEK) / USEC_PER_DAY, s);
407 else if (d >= 2*USEC_PER_DAY)
408 snprintf(buf, l, USEC_FMT " days %s", d / USEC_PER_DAY, s);
409 else if (d >= 25*USEC_PER_HOUR)
410 snprintf(buf, l, "1 day " USEC_FMT "h %s",
411 (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
412 else if (d >= 6*USEC_PER_HOUR)
413 snprintf(buf, l, USEC_FMT "h %s",
414 d / USEC_PER_HOUR, s);
415 else if (d >= USEC_PER_HOUR)
416 snprintf(buf, l, USEC_FMT "h " USEC_FMT "min %s",
418 (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
419 else if (d >= 5*USEC_PER_MINUTE)
420 snprintf(buf, l, USEC_FMT "min %s",
421 d / USEC_PER_MINUTE, s);
422 else if (d >= USEC_PER_MINUTE)
423 snprintf(buf, l, USEC_FMT "min " USEC_FMT "s %s",
425 (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
426 else if (d >= USEC_PER_SEC)
427 snprintf(buf, l, USEC_FMT "s %s",
428 d / USEC_PER_SEC, s);
429 else if (d >= USEC_PER_MSEC)
430 snprintf(buf, l, USEC_FMT "ms %s",
431 d / USEC_PER_MSEC, s);
433 snprintf(buf, l, USEC_FMT"us %s",
436 snprintf(buf, l, "now");
442 char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
443 static const struct {
447 { "y", USEC_PER_YEAR },
448 { "month", USEC_PER_MONTH },
449 { "w", USEC_PER_WEEK },
450 { "d", USEC_PER_DAY },
451 { "h", USEC_PER_HOUR },
452 { "min", USEC_PER_MINUTE },
453 { "s", USEC_PER_SEC },
454 { "ms", USEC_PER_MSEC },
460 bool something = false;
465 if (t == USEC_INFINITY) {
466 strncpy(p, "infinity", l-1);
472 strncpy(p, "0", l-1);
477 /* The result of this function can be parsed with parse_sec */
479 for (i = 0; i < ELEMENTSOF(table); i++) {
488 if (t < accuracy && something)
491 if (t < table[i].usec)
497 a = t / table[i].usec;
498 b = t % table[i].usec;
500 /* Let's see if we should shows this in dot notation */
501 if (t < USEC_PER_MINUTE && b > 0) {
506 for (cc = table[i].usec; cc > 1; cc /= 10)
509 for (cc = accuracy; cc > 1; cc /= 10) {
516 "%s"USEC_FMT".%0*"PRI_USEC"%s",
528 /* No? Then let's show it normally */
539 n = MIN((size_t) k, l);
552 #if 0 /// UNNEEDED by elogind
553 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
559 if (!dual_timestamp_is_set(t))
562 fprintf(f, "%s="USEC_FMT" "USEC_FMT"\n",
568 int dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
575 pos = strspn(value, WHITESPACE);
576 if (value[pos] == '-')
578 pos += strspn(value + pos, DIGITS);
579 pos += strspn(value + pos, WHITESPACE);
580 if (value[pos] == '-')
583 r = sscanf(value, "%" PRIu64 "%" PRIu64 "%n", &a, &b, &pos);
585 log_debug("Failed to parse dual timestamp value \"%s\".", value);
589 if (value[pos] != '\0')
590 /* trailing garbage */
600 int timestamp_deserialize(const char *value, usec_t *timestamp) {
605 r = safe_atou64(value, timestamp);
607 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
612 #if 0 /// UNNEEDED by elogind
613 static int parse_timestamp_impl(const char *t, usec_t *usec, bool with_tz) {
614 static const struct {
634 const char *k, *utc = NULL, *tzn = NULL;
637 usec_t x_usec, plus = 0, minus = 0, ret;
638 int r, weekday = -1, dst = -1;
644 * 2012-09-22 16:34:22
645 * 2012-09-22 16:34 (seconds will be set to 0)
646 * 2012-09-22 (time will be set to 00:00:00)
647 * 16:34:22 (date will be set to today)
648 * 16:34 (date will be set to today, seconds to 0)
650 * yesterday (time is set to 00:00:00)
651 * today (time is set to 00:00:00)
652 * tomorrow (time is set to 00:00:00)
655 * @2147483647 (seconds since epoch)
662 if (t[0] == '@' && !with_tz)
663 return parse_sec(t + 1, usec);
665 ret = now(CLOCK_REALTIME);
671 else if (t[0] == '+') {
672 r = parse_sec(t+1, &plus);
678 } else if (t[0] == '-') {
679 r = parse_sec(t+1, &minus);
685 } else if ((k = endswith(t, " ago"))) {
686 t = strndupa(t, k - t);
688 r = parse_sec(t, &minus);
694 } else if ((k = endswith(t, " left"))) {
695 t = strndupa(t, k - t);
697 r = parse_sec(t, &plus);
704 /* See if the timestamp is suffixed with UTC */
705 utc = endswith_no_case(t, " UTC");
707 t = strndupa(t, utc - t);
709 const char *e = NULL;
714 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
715 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
716 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
717 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
718 * support arbitrary timezone specifications. */
720 for (j = 0; j <= 1; j++) {
722 if (isempty(tzname[j]))
725 e = endswith_no_case(t, tzname[j]);
736 if (IN_SET(j, 0, 1)) {
737 /* Found one of the two timezones specified. */
738 t = strndupa(t, e - t - 1);
745 x = (time_t) (ret / USEC_PER_SEC);
748 if (!localtime_or_gmtime_r(&x, &tm, utc))
755 if (streq(t, "today")) {
756 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
759 } else if (streq(t, "yesterday")) {
761 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
764 } else if (streq(t, "tomorrow")) {
766 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
770 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
773 if (!startswith_no_case(t, day_nr[i].name))
776 skip = strlen(day_nr[i].name);
780 weekday = day_nr[i].nr;
786 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
795 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
804 k = strptime(t, "%y-%m-%d %H:%M", &tm);
811 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
818 k = strptime(t, "%y-%m-%d", &tm);
820 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
825 k = strptime(t, "%Y-%m-%d", &tm);
827 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
832 k = strptime(t, "%H:%M:%S", &tm);
841 k = strptime(t, "%H:%M", &tm);
854 r = parse_fractional_part_u(&k, 6, &add);
865 if (weekday >= 0 && tm.tm_wday != weekday)
868 x = mktime_or_timegm(&tm, utc);
872 ret = (usec_t) x * USEC_PER_SEC + x_usec;
873 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
877 if (ret + plus < ret) /* overflow? */
880 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
893 typedef struct ParseTimestampResult {
896 } ParseTimestampResult;
898 int parse_timestamp(const char *t, usec_t *usec) {
899 char *last_space, *tz = NULL;
900 ParseTimestampResult *shared, tmp;
904 last_space = strrchr(t, ' ');
905 if (last_space != NULL && timezone_is_valid(last_space + 1))
908 if (tz == NULL || endswith_no_case(t, " UTC"))
909 return parse_timestamp_impl(t, usec, false);
911 shared = mmap(NULL, sizeof *shared, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
912 if (shared == MAP_FAILED)
913 return negative_errno();
918 int fork_errno = errno;
919 (void) munmap(shared, sizeof *shared);
926 if (setenv("TZ", tz, 1) != 0) {
927 shared->return_value = negative_errno();
933 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
934 * Otherwise just cut it off */
935 with_tz = !STR_IN_SET(tz, tzname[0], tzname[1]);
937 /*cut off the timezone if we dont need it*/
939 t = strndupa(t, last_space - t);
941 shared->return_value = parse_timestamp_impl(t, &shared->usec, with_tz);
946 r = wait_for_terminate(pid, NULL);
948 (void) munmap(shared, sizeof *shared);
953 if (munmap(shared, sizeof *shared) != 0)
954 return negative_errno();
956 if (tmp.return_value == 0)
959 return tmp.return_value;
963 static char* extract_multiplier(char *p, usec_t *multiplier) {
964 static const struct {
968 { "seconds", USEC_PER_SEC },
969 { "second", USEC_PER_SEC },
970 { "sec", USEC_PER_SEC },
971 { "s", USEC_PER_SEC },
972 { "minutes", USEC_PER_MINUTE },
973 { "minute", USEC_PER_MINUTE },
974 { "min", USEC_PER_MINUTE },
975 { "months", USEC_PER_MONTH },
976 { "month", USEC_PER_MONTH },
977 { "M", USEC_PER_MONTH },
978 { "msec", USEC_PER_MSEC },
979 { "ms", USEC_PER_MSEC },
980 { "m", USEC_PER_MINUTE },
981 { "hours", USEC_PER_HOUR },
982 { "hour", USEC_PER_HOUR },
983 { "hr", USEC_PER_HOUR },
984 { "h", USEC_PER_HOUR },
985 { "days", USEC_PER_DAY },
986 { "day", USEC_PER_DAY },
987 { "d", USEC_PER_DAY },
988 { "weeks", USEC_PER_WEEK },
989 { "week", USEC_PER_WEEK },
990 { "w", USEC_PER_WEEK },
991 { "years", USEC_PER_YEAR },
992 { "year", USEC_PER_YEAR },
993 { "y", USEC_PER_YEAR },
1000 for (i = 0; i < ELEMENTSOF(table); i++) {
1003 e = startswith(p, table[i].suffix);
1005 *multiplier = table[i].usec;
1013 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
1016 bool something = false;
1020 assert(default_unit > 0);
1024 p += strspn(p, WHITESPACE);
1025 s = startswith(p, "infinity");
1027 s += strspn(s, WHITESPACE);
1031 *usec = USEC_INFINITY;
1039 usec_t multiplier = default_unit, k;
1041 p += strspn(p, WHITESPACE);
1051 l = strtoll(p, &e, 10);
1061 z = strtoll(b, &e, 10);
1076 e += strspn(e, WHITESPACE);
1077 p = extract_multiplier(e, &multiplier);
1081 k = (usec_t) z * multiplier;
1086 r += (usec_t) l * multiplier + k;
1094 int parse_sec(const char *t, usec_t *usec) {
1095 return parse_time(t, usec, USEC_PER_SEC);
1098 #if 0 /// UNNEEDED by elogind
1099 int parse_sec_fix_0(const char *t, usec_t *usec) {
1103 t += strspn(t, WHITESPACE);
1105 if (streq(t, "0")) {
1106 *usec = USEC_INFINITY;
1110 return parse_sec(t, usec);
1113 int parse_nsec(const char *t, nsec_t *nsec) {
1114 static const struct {
1118 { "seconds", NSEC_PER_SEC },
1119 { "second", NSEC_PER_SEC },
1120 { "sec", NSEC_PER_SEC },
1121 { "s", NSEC_PER_SEC },
1122 { "minutes", NSEC_PER_MINUTE },
1123 { "minute", NSEC_PER_MINUTE },
1124 { "min", NSEC_PER_MINUTE },
1125 { "months", NSEC_PER_MONTH },
1126 { "month", NSEC_PER_MONTH },
1127 { "msec", NSEC_PER_MSEC },
1128 { "ms", NSEC_PER_MSEC },
1129 { "m", NSEC_PER_MINUTE },
1130 { "hours", NSEC_PER_HOUR },
1131 { "hour", NSEC_PER_HOUR },
1132 { "hr", NSEC_PER_HOUR },
1133 { "h", NSEC_PER_HOUR },
1134 { "days", NSEC_PER_DAY },
1135 { "day", NSEC_PER_DAY },
1136 { "d", NSEC_PER_DAY },
1137 { "weeks", NSEC_PER_WEEK },
1138 { "week", NSEC_PER_WEEK },
1139 { "w", NSEC_PER_WEEK },
1140 { "years", NSEC_PER_YEAR },
1141 { "year", NSEC_PER_YEAR },
1142 { "y", NSEC_PER_YEAR },
1143 { "usec", NSEC_PER_USEC },
1144 { "us", NSEC_PER_USEC },
1145 { "µs", NSEC_PER_USEC },
1148 { "", 1ULL }, /* default is nsec */
1153 bool something = false;
1160 p += strspn(p, WHITESPACE);
1161 s = startswith(p, "infinity");
1163 s += strspn(s, WHITESPACE);
1167 *nsec = NSEC_INFINITY;
1176 p += strspn(p, WHITESPACE);
1186 l = strtoll(p, &e, 10);
1198 z = strtoll(b, &e, 10);
1213 e += strspn(e, WHITESPACE);
1215 for (i = 0; i < ELEMENTSOF(table); i++)
1216 if (startswith(e, table[i].suffix)) {
1217 nsec_t k = (nsec_t) z * table[i].nsec;
1222 r += (nsec_t) l * table[i].nsec + k;
1223 p = e + strlen(table[i].suffix);
1229 if (i >= ELEMENTSOF(table))
1239 bool ntp_synced(void) {
1240 struct timex txc = {};
1242 if (adjtimex(&txc) < 0)
1245 if (txc.status & STA_UNSYNC)
1251 int get_timezones(char ***ret) {
1252 _cleanup_fclose_ FILE *f = NULL;
1253 _cleanup_strv_free_ char **zones = NULL;
1254 size_t n_zones = 0, n_allocated = 0;
1258 zones = strv_new("UTC", NULL);
1265 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1269 FOREACH_LINE(l, f, return -errno) {
1275 if (isempty(p) || *p == '#')
1278 /* Skip over country code */
1279 p += strcspn(p, WHITESPACE);
1280 p += strspn(p, WHITESPACE);
1282 /* Skip over coordinates */
1283 p += strcspn(p, WHITESPACE);
1284 p += strspn(p, WHITESPACE);
1286 /* Found timezone name */
1287 k = strcspn(p, WHITESPACE);
1295 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1300 zones[n_zones++] = w;
1301 zones[n_zones] = NULL;
1306 } else if (errno != ENOENT)
1315 bool timezone_is_valid(const char *name) {
1326 for (p = name; *p; p++) {
1327 if (!(*p >= '0' && *p <= '9') &&
1328 !(*p >= 'a' && *p <= 'z') &&
1329 !(*p >= 'A' && *p <= 'Z') &&
1330 !IN_SET(*p, '-', '_', '+', '/'))
1346 t = strjoina("/usr/share/zoneinfo/", name);
1347 if (stat(t, &st) < 0)
1350 if (!S_ISREG(st.st_mode))
1357 bool clock_boottime_supported(void) {
1358 static int supported = -1;
1360 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1362 if (supported < 0) {
1365 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1377 #if 0 /// UNNEEDED by elogind
1378 clockid_t clock_boottime_or_monotonic(void) {
1379 if (clock_boottime_supported())
1380 return CLOCK_BOOTTIME;
1382 return CLOCK_MONOTONIC;
1386 #if 1 /// let's add a diagnostic push to silence -Wimplicit-fallthrough to elogind
1387 # if defined(__GNUC__) && (__GNUC__ > 6)
1388 # pragma GCC diagnostic push
1389 # pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
1392 bool clock_supported(clockid_t clock) {
1397 case CLOCK_MONOTONIC:
1398 case CLOCK_REALTIME:
1401 case CLOCK_BOOTTIME:
1402 return clock_boottime_supported();
1404 case CLOCK_BOOTTIME_ALARM:
1405 if (!clock_boottime_supported())
1411 /* For everything else, check properly */
1412 return clock_gettime(clock, &ts) >= 0;
1415 #if 1 /// end diagnostic push in elogind
1417 # pragma GCC diagnostic pop
1421 #if 0 /// UNNEEDED by elogind
1422 int get_timezone(char **tz) {
1423 _cleanup_free_ char *t = NULL;
1428 r = readlink_malloc("/etc/localtime", &t);
1430 return r; /* returns EINVAL if not a symlink */
1432 e = path_startswith(t, "/usr/share/zoneinfo/");
1434 e = path_startswith(t, "../usr/share/zoneinfo/");
1438 if (!timezone_is_valid(e))
1449 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1450 return utc ? timegm(tm) : mktime(tm);
1454 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1455 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1458 #if 0 /// UNNEEDED by elogind
1459 unsigned long usec_to_jiffies(usec_t u) {
1460 static thread_local unsigned long hz = 0;
1464 r = sysconf(_SC_CLK_TCK);
1470 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1473 usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
1476 if (x == USEC_INFINITY)
1477 return USEC_INFINITY;
1478 if (map_clock_id(from) == map_clock_id(to))
1485 /* x lies in the future */
1486 return usec_add(b, usec_sub_unsigned(x, a));
1488 /* x lies in the past */
1489 return usec_sub_unsigned(b, usec_sub_unsigned(a, x));