1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
15 #include <sys/timerfd.h>
16 #include <sys/timex.h>
17 #include <sys/types.h>
20 #include "alloc-util.h"
24 //#include "io-util.h"
27 #include "parse-util.h"
28 #include "path-util.h"
29 //#include "process-util.h"
30 //#include "stat-util.h"
31 #include "string-util.h"
33 #include "time-util.h"
35 static clockid_t map_clock_id(clockid_t c) {
37 /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus, clock_gettime() will
38 * fail for them. Since they are essentially the same as their non-ALARM pendants (their only difference is
39 * when timers are set on them), let's just map them accordingly. This way, we can get the correct time even on
44 case CLOCK_BOOTTIME_ALARM:
45 return CLOCK_BOOTTIME;
47 case CLOCK_REALTIME_ALARM:
48 return CLOCK_REALTIME;
55 usec_t now(clockid_t clock_id) {
58 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
60 return timespec_load(&ts);
63 #if 0 /// UNNEEDED by elogind
64 nsec_t now_nsec(clockid_t clock_id) {
67 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
69 return timespec_load_nsec(&ts);
73 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
76 ts->realtime = now(CLOCK_REALTIME);
77 ts->monotonic = now(CLOCK_MONOTONIC);
82 triple_timestamp* triple_timestamp_get(triple_timestamp *ts) {
85 ts->realtime = now(CLOCK_REALTIME);
86 ts->monotonic = now(CLOCK_MONOTONIC);
87 ts->boottime = clock_boottime_supported() ? now(CLOCK_BOOTTIME) : USEC_INFINITY;
92 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
96 if (u == USEC_INFINITY || u <= 0) {
97 ts->realtime = ts->monotonic = u;
103 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
104 ts->monotonic = usec_sub_signed(now(CLOCK_MONOTONIC), delta);
109 #if 0 /// UNNEEDED by elogind
110 triple_timestamp* triple_timestamp_from_realtime(triple_timestamp *ts, usec_t u) {
115 if (u == USEC_INFINITY || u <= 0) {
116 ts->realtime = ts->monotonic = ts->boottime = u;
121 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
122 ts->monotonic = usec_sub_signed(now(CLOCK_MONOTONIC), delta);
123 ts->boottime = clock_boottime_supported() ? usec_sub_signed(now(CLOCK_BOOTTIME), delta) : USEC_INFINITY;
128 dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
132 if (u == USEC_INFINITY) {
133 ts->realtime = ts->monotonic = USEC_INFINITY;
138 delta = (int64_t) now(CLOCK_MONOTONIC) - (int64_t) u;
139 ts->realtime = usec_sub_signed(now(CLOCK_REALTIME), delta);
144 dual_timestamp* dual_timestamp_from_boottime_or_monotonic(dual_timestamp *ts, usec_t u) {
147 if (u == USEC_INFINITY) {
148 ts->realtime = ts->monotonic = USEC_INFINITY;
152 dual_timestamp_get(ts);
153 delta = (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u;
154 ts->realtime = usec_sub_signed(ts->realtime, delta);
155 ts->monotonic = usec_sub_signed(ts->monotonic, delta);
161 usec_t triple_timestamp_by_clock(triple_timestamp *ts, clockid_t clock) {
166 case CLOCK_REALTIME_ALARM:
169 case CLOCK_MONOTONIC:
170 return ts->monotonic;
173 case CLOCK_BOOTTIME_ALARM:
177 return USEC_INFINITY;
181 usec_t timespec_load(const struct timespec *ts) {
184 if (ts->tv_sec < 0 || ts->tv_nsec < 0)
185 return USEC_INFINITY;
187 if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
188 return USEC_INFINITY;
191 (usec_t) ts->tv_sec * USEC_PER_SEC +
192 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
195 #if 0 /// UNNEEDED by elogind
196 nsec_t timespec_load_nsec(const struct timespec *ts) {
199 if (ts->tv_sec < 0 || ts->tv_nsec < 0)
200 return NSEC_INFINITY;
202 if ((nsec_t) ts->tv_sec >= (UINT64_MAX - ts->tv_nsec) / NSEC_PER_SEC)
203 return NSEC_INFINITY;
205 return (nsec_t) ts->tv_sec * NSEC_PER_SEC + (nsec_t) ts->tv_nsec;
209 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
212 if (u == USEC_INFINITY ||
213 u / USEC_PER_SEC >= TIME_T_MAX) {
214 ts->tv_sec = (time_t) -1;
215 ts->tv_nsec = (long) -1;
219 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
220 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
225 usec_t timeval_load(const struct timeval *tv) {
228 if (tv->tv_sec < 0 || tv->tv_usec < 0)
229 return USEC_INFINITY;
231 if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
232 return USEC_INFINITY;
235 (usec_t) tv->tv_sec * USEC_PER_SEC +
236 (usec_t) tv->tv_usec;
239 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
242 if (u == USEC_INFINITY ||
243 u / USEC_PER_SEC > TIME_T_MAX) {
244 tv->tv_sec = (time_t) -1;
245 tv->tv_usec = (suseconds_t) -1;
247 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
248 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
254 static char *format_timestamp_internal(
261 /* The weekdays in non-localized (English) form. We use this instead of the localized form, so that our
262 * generated timestamps may be parsed with parse_timestamp(), and always read the same. */
263 static const char * const weekdays[] = {
281 1 + 10 + /* space and date */
282 1 + 8 + /* space and time */
283 (us ? 1 + 6 : 0) + /* "." and microsecond part */
284 1 + 1 + /* space and shortest possible zone */
286 return NULL; /* Not enough space even for the shortest form. */
287 if (t <= 0 || t == USEC_INFINITY)
288 return NULL; /* Timestamp is unset */
290 /* Let's not format times with years > 9999 */
291 if (t > USEC_TIMESTAMP_FORMATTABLE_MAX)
294 sec = (time_t) (t / USEC_PER_SEC); /* Round down */
296 if (!localtime_or_gmtime_r(&sec, &tm, utc))
299 /* Start with the week day */
300 assert((size_t) tm.tm_wday < ELEMENTSOF(weekdays));
301 memcpy(buf, weekdays[tm.tm_wday], 4);
303 /* Add the main components */
304 if (strftime(buf + 3, l - 3, " %Y-%m-%d %H:%M:%S", &tm) <= 0)
305 return NULL; /* Doesn't fit */
307 /* Append the microseconds part, if that's requested */
311 return NULL; /* Microseconds part doesn't fit. */
313 sprintf(buf + n, ".%06"PRI_USEC, t % USEC_PER_SEC);
316 /* Append the timezone */
319 /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r() normally uses the
320 * obsolete "GMT" instead. */
322 return NULL; /* "UTC" doesn't fit. */
324 strcpy(buf + n, " UTC");
326 } else if (!isempty(tm.tm_zone)) {
329 /* An explicit timezone is specified, let's use it, if it fits */
330 tn = strlen(tm.tm_zone);
331 if (n + 1 + tn + 1 > l) {
332 /* The full time zone does not fit in. Yuck. */
334 if (n + 1 + _POSIX_TZNAME_MAX + 1 > l)
335 return NULL; /* Not even enough space for the POSIX minimum (of 6)? In that case, complain that it doesn't fit */
337 /* So the time zone doesn't fit in fully, but the caller passed enough space for the POSIX
338 * minimum time zone length. In this case suppress the timezone entirely, in order not to dump
339 * an overly long, hard to read string on the user. This should be safe, because the user will
340 * assume the local timezone anyway if none is shown. And so does parse_timestamp(). */
343 strcpy(buf + n, tm.tm_zone);
350 char *format_timestamp(char *buf, size_t l, usec_t t) {
351 return format_timestamp_internal(buf, l, t, false, false);
354 #if 0 /// UNNEEDED by elogind
355 char *format_timestamp_utc(char *buf, size_t l, usec_t t) {
356 return format_timestamp_internal(buf, l, t, true, false);
360 char *format_timestamp_us(char *buf, size_t l, usec_t t) {
361 return format_timestamp_internal(buf, l, t, false, true);
364 #if 0 /// UNNEEDED by elogind
365 char *format_timestamp_us_utc(char *buf, size_t l, usec_t t) {
366 return format_timestamp_internal(buf, l, t, true, true);
370 char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
374 if (t <= 0 || t == USEC_INFINITY)
377 n = now(CLOCK_REALTIME);
386 if (d >= USEC_PER_YEAR)
387 snprintf(buf, l, USEC_FMT " years " USEC_FMT " months %s",
389 (d % USEC_PER_YEAR) / USEC_PER_MONTH, s);
390 else if (d >= USEC_PER_MONTH)
391 snprintf(buf, l, USEC_FMT " months " USEC_FMT " days %s",
393 (d % USEC_PER_MONTH) / USEC_PER_DAY, s);
394 else if (d >= USEC_PER_WEEK)
395 snprintf(buf, l, USEC_FMT " weeks " USEC_FMT " days %s",
397 (d % USEC_PER_WEEK) / USEC_PER_DAY, s);
398 else if (d >= 2*USEC_PER_DAY)
399 snprintf(buf, l, USEC_FMT " days %s", d / USEC_PER_DAY, s);
400 else if (d >= 25*USEC_PER_HOUR)
401 snprintf(buf, l, "1 day " USEC_FMT "h %s",
402 (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
403 else if (d >= 6*USEC_PER_HOUR)
404 snprintf(buf, l, USEC_FMT "h %s",
405 d / USEC_PER_HOUR, s);
406 else if (d >= USEC_PER_HOUR)
407 snprintf(buf, l, USEC_FMT "h " USEC_FMT "min %s",
409 (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
410 else if (d >= 5*USEC_PER_MINUTE)
411 snprintf(buf, l, USEC_FMT "min %s",
412 d / USEC_PER_MINUTE, s);
413 else if (d >= USEC_PER_MINUTE)
414 snprintf(buf, l, USEC_FMT "min " USEC_FMT "s %s",
416 (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
417 else if (d >= USEC_PER_SEC)
418 snprintf(buf, l, USEC_FMT "s %s",
419 d / USEC_PER_SEC, s);
420 else if (d >= USEC_PER_MSEC)
421 snprintf(buf, l, USEC_FMT "ms %s",
422 d / USEC_PER_MSEC, s);
424 snprintf(buf, l, USEC_FMT"us %s",
427 snprintf(buf, l, "now");
433 char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
434 static const struct {
438 { "y", USEC_PER_YEAR },
439 { "month", USEC_PER_MONTH },
440 { "w", USEC_PER_WEEK },
441 { "d", USEC_PER_DAY },
442 { "h", USEC_PER_HOUR },
443 { "min", USEC_PER_MINUTE },
444 { "s", USEC_PER_SEC },
445 { "ms", USEC_PER_MSEC },
451 bool something = false;
456 if (t == USEC_INFINITY) {
457 strncpy(p, "infinity", l-1);
463 strncpy(p, "0", l-1);
468 /* The result of this function can be parsed with parse_sec */
470 for (i = 0; i < ELEMENTSOF(table); i++) {
479 if (t < accuracy && something)
482 if (t < table[i].usec)
488 a = t / table[i].usec;
489 b = t % table[i].usec;
491 /* Let's see if we should shows this in dot notation */
492 if (t < USEC_PER_MINUTE && b > 0) {
497 for (cc = table[i].usec; cc > 1; cc /= 10)
500 for (cc = accuracy; cc > 1; cc /= 10) {
507 "%s"USEC_FMT".%0*"PRI_USEC"%s",
519 /* No? Then let's show it normally */
530 n = MIN((size_t) k, l);
543 #if 0 /// UNNEEDED by elogind
544 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
550 if (!dual_timestamp_is_set(t))
553 fprintf(f, "%s="USEC_FMT" "USEC_FMT"\n",
559 int dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
566 pos = strspn(value, WHITESPACE);
567 if (value[pos] == '-')
569 pos += strspn(value + pos, DIGITS);
570 pos += strspn(value + pos, WHITESPACE);
571 if (value[pos] == '-')
574 r = sscanf(value, "%" PRIu64 "%" PRIu64 "%n", &a, &b, &pos);
576 log_debug("Failed to parse dual timestamp value \"%s\".", value);
580 if (value[pos] != '\0')
581 /* trailing garbage */
591 int timestamp_deserialize(const char *value, usec_t *timestamp) {
596 r = safe_atou64(value, timestamp);
598 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
603 #if 0 /// UNNEEDED by elogind
604 static int parse_timestamp_impl(const char *t, usec_t *usec, bool with_tz) {
605 static const struct {
625 const char *k, *utc = NULL, *tzn = NULL;
628 usec_t x_usec, plus = 0, minus = 0, ret;
629 int r, weekday = -1, dst = -1;
634 * 2012-09-22 16:34:22
635 * 2012-09-22 16:34 (seconds will be set to 0)
636 * 2012-09-22 (time will be set to 00:00:00)
637 * 16:34:22 (date will be set to today)
638 * 16:34 (date will be set to today, seconds to 0)
640 * yesterday (time is set to 00:00:00)
641 * today (time is set to 00:00:00)
642 * tomorrow (time is set to 00:00:00)
645 * @2147483647 (seconds since epoch)
651 if (t[0] == '@' && !with_tz)
652 return parse_sec(t + 1, usec);
654 ret = now(CLOCK_REALTIME);
660 else if (t[0] == '+') {
661 r = parse_sec(t+1, &plus);
667 } else if (t[0] == '-') {
668 r = parse_sec(t+1, &minus);
674 } else if ((k = endswith(t, " ago"))) {
675 t = strndupa(t, k - t);
677 r = parse_sec(t, &minus);
683 } else if ((k = endswith(t, " left"))) {
684 t = strndupa(t, k - t);
686 r = parse_sec(t, &plus);
693 /* See if the timestamp is suffixed with UTC */
694 utc = endswith_no_case(t, " UTC");
696 t = strndupa(t, utc - t);
698 const char *e = NULL;
703 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
704 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
705 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
706 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
707 * support arbitrary timezone specifications. */
709 for (j = 0; j <= 1; j++) {
711 if (isempty(tzname[j]))
714 e = endswith_no_case(t, tzname[j]);
725 if (IN_SET(j, 0, 1)) {
726 /* Found one of the two timezones specified. */
727 t = strndupa(t, e - t - 1);
734 x = (time_t) (ret / USEC_PER_SEC);
737 if (!localtime_or_gmtime_r(&x, &tm, utc))
744 if (streq(t, "today")) {
745 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
748 } else if (streq(t, "yesterday")) {
750 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
753 } else if (streq(t, "tomorrow")) {
755 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
759 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
762 if (!startswith_no_case(t, day_nr[i].name))
765 skip = strlen(day_nr[i].name);
769 weekday = day_nr[i].nr;
775 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
784 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
793 k = strptime(t, "%y-%m-%d %H:%M", &tm);
800 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
807 k = strptime(t, "%y-%m-%d", &tm);
809 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
814 k = strptime(t, "%Y-%m-%d", &tm);
816 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
821 k = strptime(t, "%H:%M:%S", &tm);
830 k = strptime(t, "%H:%M", &tm);
843 r = parse_fractional_part_u(&k, 6, &add);
854 if (weekday >= 0 && tm.tm_wday != weekday)
857 x = mktime_or_timegm(&tm, utc);
861 ret = (usec_t) x * USEC_PER_SEC + x_usec;
862 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
866 if (ret + plus < ret) /* overflow? */
869 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
882 typedef struct ParseTimestampResult {
885 } ParseTimestampResult;
887 int parse_timestamp(const char *t, usec_t *usec) {
888 char *last_space, *tz = NULL;
889 ParseTimestampResult *shared, tmp;
892 last_space = strrchr(t, ' ');
893 if (last_space != NULL && timezone_is_valid(last_space + 1, LOG_DEBUG))
896 if (!tz || endswith_no_case(t, " UTC"))
897 return parse_timestamp_impl(t, usec, false);
899 shared = mmap(NULL, sizeof *shared, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
900 if (shared == MAP_FAILED)
901 return negative_errno();
903 r = safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_WAIT, NULL);
905 (void) munmap(shared, sizeof *shared);
911 if (setenv("TZ", tz, 1) != 0) {
912 shared->return_value = negative_errno();
918 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
919 * Otherwise just cut it off. */
920 with_tz = !STR_IN_SET(tz, tzname[0], tzname[1]);
922 /* Cut off the timezone if we dont need it. */
924 t = strndupa(t, last_space - t);
926 shared->return_value = parse_timestamp_impl(t, &shared->usec, with_tz);
932 if (munmap(shared, sizeof *shared) != 0)
933 return negative_errno();
935 if (tmp.return_value == 0)
938 return tmp.return_value;
942 static char* extract_multiplier(char *p, usec_t *multiplier) {
943 static const struct {
947 { "seconds", USEC_PER_SEC },
948 { "second", USEC_PER_SEC },
949 { "sec", USEC_PER_SEC },
950 { "s", USEC_PER_SEC },
951 { "minutes", USEC_PER_MINUTE },
952 { "minute", USEC_PER_MINUTE },
953 { "min", USEC_PER_MINUTE },
954 { "months", USEC_PER_MONTH },
955 { "month", USEC_PER_MONTH },
956 { "M", USEC_PER_MONTH },
957 { "msec", USEC_PER_MSEC },
958 { "ms", USEC_PER_MSEC },
959 { "m", USEC_PER_MINUTE },
960 { "hours", USEC_PER_HOUR },
961 { "hour", USEC_PER_HOUR },
962 { "hr", USEC_PER_HOUR },
963 { "h", USEC_PER_HOUR },
964 { "days", USEC_PER_DAY },
965 { "day", USEC_PER_DAY },
966 { "d", USEC_PER_DAY },
967 { "weeks", USEC_PER_WEEK },
968 { "week", USEC_PER_WEEK },
969 { "w", USEC_PER_WEEK },
970 { "years", USEC_PER_YEAR },
971 { "year", USEC_PER_YEAR },
972 { "y", USEC_PER_YEAR },
979 for (i = 0; i < ELEMENTSOF(table); i++) {
982 e = startswith(p, table[i].suffix);
984 *multiplier = table[i].usec;
992 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
995 bool something = false;
999 assert(default_unit > 0);
1003 p += strspn(p, WHITESPACE);
1004 s = startswith(p, "infinity");
1006 s += strspn(s, WHITESPACE);
1010 *usec = USEC_INFINITY;
1018 usec_t multiplier = default_unit, k;
1020 p += strspn(p, WHITESPACE);
1030 l = strtoll(p, &e, 10);
1040 z = strtoll(b, &e, 10);
1055 e += strspn(e, WHITESPACE);
1056 p = extract_multiplier(e, &multiplier);
1060 k = (usec_t) z * multiplier;
1065 r += (usec_t) l * multiplier + k;
1073 int parse_sec(const char *t, usec_t *usec) {
1074 return parse_time(t, usec, USEC_PER_SEC);
1077 #if 0 /// UNNEEDED by elogind
1078 int parse_sec_fix_0(const char *t, usec_t *usec) {
1082 t += strspn(t, WHITESPACE);
1084 if (streq(t, "0")) {
1085 *usec = USEC_INFINITY;
1089 return parse_sec(t, usec);
1092 int parse_nsec(const char *t, nsec_t *nsec) {
1093 static const struct {
1097 { "seconds", NSEC_PER_SEC },
1098 { "second", NSEC_PER_SEC },
1099 { "sec", NSEC_PER_SEC },
1100 { "s", NSEC_PER_SEC },
1101 { "minutes", NSEC_PER_MINUTE },
1102 { "minute", NSEC_PER_MINUTE },
1103 { "min", NSEC_PER_MINUTE },
1104 { "months", NSEC_PER_MONTH },
1105 { "month", NSEC_PER_MONTH },
1106 { "msec", NSEC_PER_MSEC },
1107 { "ms", NSEC_PER_MSEC },
1108 { "m", NSEC_PER_MINUTE },
1109 { "hours", NSEC_PER_HOUR },
1110 { "hour", NSEC_PER_HOUR },
1111 { "hr", NSEC_PER_HOUR },
1112 { "h", NSEC_PER_HOUR },
1113 { "days", NSEC_PER_DAY },
1114 { "day", NSEC_PER_DAY },
1115 { "d", NSEC_PER_DAY },
1116 { "weeks", NSEC_PER_WEEK },
1117 { "week", NSEC_PER_WEEK },
1118 { "w", NSEC_PER_WEEK },
1119 { "years", NSEC_PER_YEAR },
1120 { "year", NSEC_PER_YEAR },
1121 { "y", NSEC_PER_YEAR },
1122 { "usec", NSEC_PER_USEC },
1123 { "us", NSEC_PER_USEC },
1124 { "µs", NSEC_PER_USEC },
1127 { "", 1ULL }, /* default is nsec */
1132 bool something = false;
1139 p += strspn(p, WHITESPACE);
1140 s = startswith(p, "infinity");
1142 s += strspn(s, WHITESPACE);
1146 *nsec = NSEC_INFINITY;
1155 p += strspn(p, WHITESPACE);
1165 l = strtoll(p, &e, 10);
1177 z = strtoll(b, &e, 10);
1192 e += strspn(e, WHITESPACE);
1194 for (i = 0; i < ELEMENTSOF(table); i++)
1195 if (startswith(e, table[i].suffix)) {
1196 nsec_t k = (nsec_t) z * table[i].nsec;
1201 r += (nsec_t) l * table[i].nsec + k;
1202 p = e + strlen(table[i].suffix);
1208 if (i >= ELEMENTSOF(table))
1218 bool ntp_synced(void) {
1219 struct timex txc = {};
1221 if (adjtimex(&txc) < 0)
1224 if (txc.status & STA_UNSYNC)
1230 int get_timezones(char ***ret) {
1231 _cleanup_fclose_ FILE *f = NULL;
1232 _cleanup_strv_free_ char **zones = NULL;
1233 size_t n_zones = 0, n_allocated = 0;
1237 zones = strv_new("UTC", NULL);
1244 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1248 FOREACH_LINE(l, f, return -errno) {
1254 if (isempty(p) || *p == '#')
1257 /* Skip over country code */
1258 p += strcspn(p, WHITESPACE);
1259 p += strspn(p, WHITESPACE);
1261 /* Skip over coordinates */
1262 p += strcspn(p, WHITESPACE);
1263 p += strspn(p, WHITESPACE);
1265 /* Found timezone name */
1266 k = strcspn(p, WHITESPACE);
1274 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1279 zones[n_zones++] = w;
1280 zones[n_zones] = NULL;
1285 } else if (errno != ENOENT)
1288 *ret = TAKE_PTR(zones);
1293 bool timezone_is_valid(const char *name, int log_level) {
1296 _cleanup_close_ int fd = -1;
1306 for (p = name; *p; p++) {
1307 if (!(*p >= '0' && *p <= '9') &&
1308 !(*p >= 'a' && *p <= 'z') &&
1309 !(*p >= 'A' && *p <= 'Z') &&
1310 !IN_SET(*p, '-', '_', '+', '/'))
1326 t = strjoina("/usr/share/zoneinfo/", name);
1328 fd = open(t, O_RDONLY|O_CLOEXEC);
1330 log_full_errno(log_level, errno, "Failed to open timezone file '%s': %m", t);
1334 r = fd_verify_regular(fd);
1336 log_full_errno(log_level, r, "Timezone file '%s' is not a regular file: %m", t);
1340 r = loop_read_exact(fd, buf, 4, false);
1342 log_full_errno(log_level, r, "Failed to read from timezone file '%s': %m", t);
1346 /* Magic from tzfile(5) */
1347 if (memcmp(buf, "TZif", 4) != 0) {
1348 log_full(log_level, "Timezone file '%s' has wrong magic bytes", t);
1356 bool clock_boottime_supported(void) {
1357 static int supported = -1;
1359 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1361 if (supported < 0) {
1364 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1376 #if 0 /// UNNEEDED by elogind
1377 clockid_t clock_boottime_or_monotonic(void) {
1378 if (clock_boottime_supported())
1379 return CLOCK_BOOTTIME;
1381 return CLOCK_MONOTONIC;
1385 #if 1 /// let's add a diagnostic push to silence -Wimplicit-fallthrough to elogind
1386 # if defined(__GNUC__) && (__GNUC__ > 6)
1387 # pragma GCC diagnostic push
1388 # pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
1391 bool clock_supported(clockid_t clock) {
1396 case CLOCK_MONOTONIC:
1397 case CLOCK_REALTIME:
1400 case CLOCK_BOOTTIME:
1401 return clock_boottime_supported();
1403 case CLOCK_BOOTTIME_ALARM:
1404 if (!clock_boottime_supported())
1409 /* For everything else, check properly */
1410 return clock_gettime(clock, &ts) >= 0;
1413 #if 1 /// end diagnostic push in elogind
1415 # pragma GCC diagnostic pop
1419 #if 0 /// UNNEEDED by elogind
1420 int get_timezone(char **tz) {
1421 _cleanup_free_ char *t = NULL;
1426 r = readlink_malloc("/etc/localtime", &t);
1428 return r; /* returns EINVAL if not a symlink */
1430 e = path_startswith(t, "/usr/share/zoneinfo/");
1432 e = path_startswith(t, "../usr/share/zoneinfo/");
1436 if (!timezone_is_valid(e, LOG_DEBUG))
1447 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1448 return utc ? timegm(tm) : mktime(tm);
1452 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1453 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1456 #if 0 /// UNNEEDED by elogind
1457 unsigned long usec_to_jiffies(usec_t u) {
1458 static thread_local unsigned long hz = 0;
1462 r = sysconf(_SC_CLK_TCK);
1468 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1471 usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
1474 if (x == USEC_INFINITY)
1475 return USEC_INFINITY;
1476 if (map_clock_id(from) == map_clock_id(to))
1483 /* x lies in the future */
1484 return usec_add(b, usec_sub_unsigned(x, a));
1486 /* x lies in the past */
1487 return usec_sub_unsigned(b, usec_sub_unsigned(a, x));
1491 bool in_utc_timezone(void) {
1494 return timezone == 0 && daylight == 0;