1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/timerfd.h>
11 #include <sys/timex.h>
12 #include <sys/types.h>
15 #include "alloc-util.h"
19 //#include "io-util.h"
22 #include "parse-util.h"
23 #include "path-util.h"
24 //#include "process-util.h"
25 //#include "stat-util.h"
26 #include "string-util.h"
28 #include "time-util.h"
30 static clockid_t map_clock_id(clockid_t c) {
32 /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus, clock_gettime() will
33 * fail for them. Since they are essentially the same as their non-ALARM pendants (their only difference is
34 * when timers are set on them), let's just map them accordingly. This way, we can get the correct time even on
39 case CLOCK_BOOTTIME_ALARM:
40 return CLOCK_BOOTTIME;
42 case CLOCK_REALTIME_ALARM:
43 return CLOCK_REALTIME;
50 usec_t now(clockid_t clock_id) {
53 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
55 return timespec_load(&ts);
58 #if 0 /// UNNEEDED by elogind
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);
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 #if 0 /// UNNEEDED by elogind
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);
156 usec_t triple_timestamp_by_clock(triple_timestamp *ts, clockid_t clock) {
161 case CLOCK_REALTIME_ALARM:
164 case CLOCK_MONOTONIC:
165 return ts->monotonic;
168 case CLOCK_BOOTTIME_ALARM:
172 return USEC_INFINITY;
176 usec_t timespec_load(const struct timespec *ts) {
179 if (ts->tv_sec < 0 || ts->tv_nsec < 0)
180 return USEC_INFINITY;
182 if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
183 return USEC_INFINITY;
186 (usec_t) ts->tv_sec * USEC_PER_SEC +
187 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
190 #if 0 /// UNNEEDED by elogind
191 nsec_t timespec_load_nsec(const struct timespec *ts) {
194 if (ts->tv_sec < 0 || ts->tv_nsec < 0)
195 return NSEC_INFINITY;
197 if ((nsec_t) ts->tv_sec >= (UINT64_MAX - ts->tv_nsec) / NSEC_PER_SEC)
198 return NSEC_INFINITY;
200 return (nsec_t) ts->tv_sec * NSEC_PER_SEC + (nsec_t) ts->tv_nsec;
204 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
207 if (u == USEC_INFINITY ||
208 u / USEC_PER_SEC >= TIME_T_MAX) {
209 ts->tv_sec = (time_t) -1;
210 ts->tv_nsec = (long) -1;
214 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
215 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
220 usec_t timeval_load(const struct timeval *tv) {
223 if (tv->tv_sec < 0 || tv->tv_usec < 0)
224 return USEC_INFINITY;
226 if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
227 return USEC_INFINITY;
230 (usec_t) tv->tv_sec * USEC_PER_SEC +
231 (usec_t) tv->tv_usec;
234 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
237 if (u == USEC_INFINITY ||
238 u / USEC_PER_SEC > TIME_T_MAX) {
239 tv->tv_sec = (time_t) -1;
240 tv->tv_usec = (suseconds_t) -1;
242 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
243 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
249 static char *format_timestamp_internal(
256 /* The weekdays in non-localized (English) form. We use this instead of the localized form, so that our
257 * generated timestamps may be parsed with parse_timestamp(), and always read the same. */
258 static const char * const weekdays[] = {
276 1 + 10 + /* space and date */
277 1 + 8 + /* space and time */
278 (us ? 1 + 6 : 0) + /* "." and microsecond part */
279 1 + 1 + /* space and shortest possible zone */
281 return NULL; /* Not enough space even for the shortest form. */
282 if (t <= 0 || t == USEC_INFINITY)
283 return NULL; /* Timestamp is unset */
285 /* Let's not format times with years > 9999 */
286 if (t > USEC_TIMESTAMP_FORMATTABLE_MAX) {
287 assert(l >= strlen("--- XXXX-XX-XX XX:XX:XX") + 1);
288 strcpy(buf, "--- XXXX-XX-XX XX:XX:XX");
292 sec = (time_t) (t / USEC_PER_SEC); /* Round down */
294 if (!localtime_or_gmtime_r(&sec, &tm, utc))
297 /* Start with the week day */
298 assert((size_t) tm.tm_wday < ELEMENTSOF(weekdays));
299 memcpy(buf, weekdays[tm.tm_wday], 4);
301 /* Add the main components */
302 if (strftime(buf + 3, l - 3, " %Y-%m-%d %H:%M:%S", &tm) <= 0)
303 return NULL; /* Doesn't fit */
305 /* Append the microseconds part, if that's requested */
309 return NULL; /* Microseconds part doesn't fit. */
311 sprintf(buf + n, ".%06"PRI_USEC, t % USEC_PER_SEC);
314 /* Append the timezone */
317 /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r() normally uses the
318 * obsolete "GMT" instead. */
320 return NULL; /* "UTC" doesn't fit. */
322 strcpy(buf + n, " UTC");
324 } else if (!isempty(tm.tm_zone)) {
327 /* An explicit timezone is specified, let's use it, if it fits */
328 tn = strlen(tm.tm_zone);
329 if (n + 1 + tn + 1 > l) {
330 /* The full time zone does not fit in. Yuck. */
332 if (n + 1 + _POSIX_TZNAME_MAX + 1 > l)
333 return NULL; /* Not even enough space for the POSIX minimum (of 6)? In that case, complain that it doesn't fit */
335 /* So the time zone doesn't fit in fully, but the caller passed enough space for the POSIX
336 * minimum time zone length. In this case suppress the timezone entirely, in order not to dump
337 * an overly long, hard to read string on the user. This should be safe, because the user will
338 * assume the local timezone anyway if none is shown. And so does parse_timestamp(). */
341 strcpy(buf + n, tm.tm_zone);
348 char *format_timestamp(char *buf, size_t l, usec_t t) {
349 return format_timestamp_internal(buf, l, t, false, false);
352 #if 0 /// UNNEEDED by elogind
353 char *format_timestamp_utc(char *buf, size_t l, usec_t t) {
354 return format_timestamp_internal(buf, l, t, true, false);
358 char *format_timestamp_us(char *buf, size_t l, usec_t t) {
359 return format_timestamp_internal(buf, l, t, false, true);
362 #if 0 /// UNNEEDED by elogind
363 char *format_timestamp_us_utc(char *buf, size_t l, usec_t t) {
364 return format_timestamp_internal(buf, l, t, true, true);
368 char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
372 if (t <= 0 || t == USEC_INFINITY)
375 n = now(CLOCK_REALTIME);
384 if (d >= USEC_PER_YEAR)
385 snprintf(buf, l, USEC_FMT " years " USEC_FMT " months %s",
387 (d % USEC_PER_YEAR) / USEC_PER_MONTH, s);
388 else if (d >= USEC_PER_MONTH)
389 snprintf(buf, l, USEC_FMT " months " USEC_FMT " days %s",
391 (d % USEC_PER_MONTH) / USEC_PER_DAY, s);
392 else if (d >= USEC_PER_WEEK)
393 snprintf(buf, l, USEC_FMT " weeks " USEC_FMT " days %s",
395 (d % USEC_PER_WEEK) / USEC_PER_DAY, s);
396 else if (d >= 2*USEC_PER_DAY)
397 snprintf(buf, l, USEC_FMT " days %s", d / USEC_PER_DAY, s);
398 else if (d >= 25*USEC_PER_HOUR)
399 snprintf(buf, l, "1 day " USEC_FMT "h %s",
400 (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
401 else if (d >= 6*USEC_PER_HOUR)
402 snprintf(buf, l, USEC_FMT "h %s",
403 d / USEC_PER_HOUR, s);
404 else if (d >= USEC_PER_HOUR)
405 snprintf(buf, l, USEC_FMT "h " USEC_FMT "min %s",
407 (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
408 else if (d >= 5*USEC_PER_MINUTE)
409 snprintf(buf, l, USEC_FMT "min %s",
410 d / USEC_PER_MINUTE, s);
411 else if (d >= USEC_PER_MINUTE)
412 snprintf(buf, l, USEC_FMT "min " USEC_FMT "s %s",
414 (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
415 else if (d >= USEC_PER_SEC)
416 snprintf(buf, l, USEC_FMT "s %s",
417 d / USEC_PER_SEC, s);
418 else if (d >= USEC_PER_MSEC)
419 snprintf(buf, l, USEC_FMT "ms %s",
420 d / USEC_PER_MSEC, s);
422 snprintf(buf, l, USEC_FMT"us %s",
425 snprintf(buf, l, "now");
431 char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
432 static const struct {
436 { "y", USEC_PER_YEAR },
437 { "month", USEC_PER_MONTH },
438 { "w", USEC_PER_WEEK },
439 { "d", USEC_PER_DAY },
440 { "h", USEC_PER_HOUR },
441 { "min", USEC_PER_MINUTE },
442 { "s", USEC_PER_SEC },
443 { "ms", USEC_PER_MSEC },
449 bool something = false;
454 if (t == USEC_INFINITY) {
455 strncpy(p, "infinity", l-1);
461 strncpy(p, "0", l-1);
466 /* The result of this function can be parsed with parse_sec */
468 for (i = 0; i < ELEMENTSOF(table); i++) {
477 if (t < accuracy && something)
480 if (t < table[i].usec)
486 a = t / table[i].usec;
487 b = t % table[i].usec;
489 /* Let's see if we should shows this in dot notation */
490 if (t < USEC_PER_MINUTE && b > 0) {
495 for (cc = table[i].usec; cc > 1; cc /= 10)
498 for (cc = accuracy; cc > 1; cc /= 10) {
505 "%s"USEC_FMT".%0*"PRI_USEC"%s",
517 /* No? Then let's show it normally */
528 n = MIN((size_t) k, l);
541 #if 0 /// UNNEEDED by elogind
542 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
548 if (!dual_timestamp_is_set(t))
551 fprintf(f, "%s="USEC_FMT" "USEC_FMT"\n",
557 int dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
564 pos = strspn(value, WHITESPACE);
565 if (value[pos] == '-')
567 pos += strspn(value + pos, DIGITS);
568 pos += strspn(value + pos, WHITESPACE);
569 if (value[pos] == '-')
572 r = sscanf(value, "%" PRIu64 "%" PRIu64 "%n", &a, &b, &pos);
574 log_debug("Failed to parse dual timestamp value \"%s\".", value);
578 if (value[pos] != '\0')
579 /* trailing garbage */
589 int timestamp_deserialize(const char *value, usec_t *timestamp) {
594 r = safe_atou64(value, timestamp);
596 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
601 #if 0 /// UNNEEDED by elogind
602 static int parse_timestamp_impl(const char *t, usec_t *usec, bool with_tz) {
603 static const struct {
623 const char *k, *utc = NULL, *tzn = NULL;
626 usec_t x_usec, plus = 0, minus = 0, ret;
627 int r, weekday = -1, dst = -1;
632 * 2012-09-22 16:34:22
633 * 2012-09-22 16:34 (seconds will be set to 0)
634 * 2012-09-22 (time will be set to 00:00:00)
635 * 16:34:22 (date will be set to today)
636 * 16:34 (date will be set to today, seconds to 0)
638 * yesterday (time is set to 00:00:00)
639 * today (time is set to 00:00:00)
640 * tomorrow (time is set to 00:00:00)
643 * @2147483647 (seconds since epoch)
649 if (t[0] == '@' && !with_tz)
650 return parse_sec(t + 1, usec);
652 ret = now(CLOCK_REALTIME);
658 else if (t[0] == '+') {
659 r = parse_sec(t+1, &plus);
665 } else if (t[0] == '-') {
666 r = parse_sec(t+1, &minus);
672 } else if ((k = endswith(t, " ago"))) {
673 t = strndupa(t, k - t);
675 r = parse_sec(t, &minus);
681 } else if ((k = endswith(t, " left"))) {
682 t = strndupa(t, k - t);
684 r = parse_sec(t, &plus);
691 /* See if the timestamp is suffixed with UTC */
692 utc = endswith_no_case(t, " UTC");
694 t = strndupa(t, utc - t);
696 const char *e = NULL;
701 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
702 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
703 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
704 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
705 * support arbitrary timezone specifications. */
707 for (j = 0; j <= 1; j++) {
709 if (isempty(tzname[j]))
712 e = endswith_no_case(t, tzname[j]);
723 if (IN_SET(j, 0, 1)) {
724 /* Found one of the two timezones specified. */
725 t = strndupa(t, e - t - 1);
732 x = (time_t) (ret / USEC_PER_SEC);
735 if (!localtime_or_gmtime_r(&x, &tm, utc))
742 if (streq(t, "today")) {
743 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
746 } else if (streq(t, "yesterday")) {
748 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
751 } else if (streq(t, "tomorrow")) {
753 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
757 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
760 if (!startswith_no_case(t, day_nr[i].name))
763 skip = strlen(day_nr[i].name);
767 weekday = day_nr[i].nr;
773 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
782 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
791 k = strptime(t, "%y-%m-%d %H:%M", &tm);
798 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
805 k = strptime(t, "%y-%m-%d", &tm);
807 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
812 k = strptime(t, "%Y-%m-%d", &tm);
814 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
819 k = strptime(t, "%H:%M:%S", &tm);
828 k = strptime(t, "%H:%M", &tm);
841 r = parse_fractional_part_u(&k, 6, &add);
852 if (weekday >= 0 && tm.tm_wday != weekday)
855 x = mktime_or_timegm(&tm, utc);
859 ret = (usec_t) x * USEC_PER_SEC + x_usec;
860 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
864 if (ret + plus < ret) /* overflow? */
867 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
880 typedef struct ParseTimestampResult {
883 } ParseTimestampResult;
885 int parse_timestamp(const char *t, usec_t *usec) {
886 char *last_space, *tz = NULL;
887 ParseTimestampResult *shared, tmp;
890 last_space = strrchr(t, ' ');
891 if (last_space != NULL && timezone_is_valid(last_space + 1, LOG_DEBUG))
894 if (!tz || endswith_no_case(t, " UTC"))
895 return parse_timestamp_impl(t, usec, false);
897 shared = mmap(NULL, sizeof *shared, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
898 if (shared == MAP_FAILED)
899 return negative_errno();
901 r = safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_WAIT, NULL);
903 (void) munmap(shared, sizeof *shared);
909 if (setenv("TZ", tz, 1) != 0) {
910 shared->return_value = negative_errno();
916 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
917 * Otherwise just cut it off. */
918 with_tz = !STR_IN_SET(tz, tzname[0], tzname[1]);
920 /* Cut off the timezone if we dont need it. */
922 t = strndupa(t, last_space - t);
924 shared->return_value = parse_timestamp_impl(t, &shared->usec, with_tz);
930 if (munmap(shared, sizeof *shared) != 0)
931 return negative_errno();
933 if (tmp.return_value == 0)
936 return tmp.return_value;
940 static char* extract_multiplier(char *p, usec_t *multiplier) {
941 static const struct {
945 { "seconds", USEC_PER_SEC },
946 { "second", USEC_PER_SEC },
947 { "sec", USEC_PER_SEC },
948 { "s", USEC_PER_SEC },
949 { "minutes", USEC_PER_MINUTE },
950 { "minute", USEC_PER_MINUTE },
951 { "min", USEC_PER_MINUTE },
952 { "months", USEC_PER_MONTH },
953 { "month", USEC_PER_MONTH },
954 { "M", USEC_PER_MONTH },
955 { "msec", USEC_PER_MSEC },
956 { "ms", USEC_PER_MSEC },
957 { "m", USEC_PER_MINUTE },
958 { "hours", USEC_PER_HOUR },
959 { "hour", USEC_PER_HOUR },
960 { "hr", USEC_PER_HOUR },
961 { "h", USEC_PER_HOUR },
962 { "days", USEC_PER_DAY },
963 { "day", USEC_PER_DAY },
964 { "d", USEC_PER_DAY },
965 { "weeks", USEC_PER_WEEK },
966 { "week", USEC_PER_WEEK },
967 { "w", USEC_PER_WEEK },
968 { "years", USEC_PER_YEAR },
969 { "year", USEC_PER_YEAR },
970 { "y", USEC_PER_YEAR },
977 for (i = 0; i < ELEMENTSOF(table); i++) {
980 e = startswith(p, table[i].suffix);
982 *multiplier = table[i].usec;
990 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
993 bool something = false;
997 assert(default_unit > 0);
1001 p += strspn(p, WHITESPACE);
1002 s = startswith(p, "infinity");
1004 s += strspn(s, WHITESPACE);
1008 *usec = USEC_INFINITY;
1016 usec_t multiplier = default_unit, k;
1018 p += strspn(p, WHITESPACE);
1028 l = strtoll(p, &e, 10);
1038 z = strtoll(b, &e, 10);
1053 e += strspn(e, WHITESPACE);
1054 p = extract_multiplier(e, &multiplier);
1058 k = (usec_t) z * multiplier;
1063 r += (usec_t) l * multiplier + k;
1071 int parse_sec(const char *t, usec_t *usec) {
1072 return parse_time(t, usec, USEC_PER_SEC);
1075 #if 0 /// UNNEEDED by elogind
1076 int parse_sec_fix_0(const char *t, usec_t *usec) {
1080 t += strspn(t, WHITESPACE);
1082 if (streq(t, "0")) {
1083 *usec = USEC_INFINITY;
1087 return parse_sec(t, usec);
1090 int parse_nsec(const char *t, nsec_t *nsec) {
1091 static const struct {
1095 { "seconds", NSEC_PER_SEC },
1096 { "second", NSEC_PER_SEC },
1097 { "sec", NSEC_PER_SEC },
1098 { "s", NSEC_PER_SEC },
1099 { "minutes", NSEC_PER_MINUTE },
1100 { "minute", NSEC_PER_MINUTE },
1101 { "min", NSEC_PER_MINUTE },
1102 { "months", NSEC_PER_MONTH },
1103 { "month", NSEC_PER_MONTH },
1104 { "msec", NSEC_PER_MSEC },
1105 { "ms", NSEC_PER_MSEC },
1106 { "m", NSEC_PER_MINUTE },
1107 { "hours", NSEC_PER_HOUR },
1108 { "hour", NSEC_PER_HOUR },
1109 { "hr", NSEC_PER_HOUR },
1110 { "h", NSEC_PER_HOUR },
1111 { "days", NSEC_PER_DAY },
1112 { "day", NSEC_PER_DAY },
1113 { "d", NSEC_PER_DAY },
1114 { "weeks", NSEC_PER_WEEK },
1115 { "week", NSEC_PER_WEEK },
1116 { "w", NSEC_PER_WEEK },
1117 { "years", NSEC_PER_YEAR },
1118 { "year", NSEC_PER_YEAR },
1119 { "y", NSEC_PER_YEAR },
1120 { "usec", NSEC_PER_USEC },
1121 { "us", NSEC_PER_USEC },
1122 { "µs", NSEC_PER_USEC },
1125 { "", 1ULL }, /* default is nsec */
1130 bool something = false;
1137 p += strspn(p, WHITESPACE);
1138 s = startswith(p, "infinity");
1140 s += strspn(s, WHITESPACE);
1144 *nsec = NSEC_INFINITY;
1153 p += strspn(p, WHITESPACE);
1163 l = strtoll(p, &e, 10);
1175 z = strtoll(b, &e, 10);
1190 e += strspn(e, WHITESPACE);
1192 for (i = 0; i < ELEMENTSOF(table); i++)
1193 if (startswith(e, table[i].suffix)) {
1194 nsec_t k = (nsec_t) z * table[i].nsec;
1199 r += (nsec_t) l * table[i].nsec + k;
1200 p = e + strlen(table[i].suffix);
1206 if (i >= ELEMENTSOF(table))
1216 bool ntp_synced(void) {
1217 struct timex txc = {};
1219 if (adjtimex(&txc) < 0)
1222 if (txc.status & STA_UNSYNC)
1228 int get_timezones(char ***ret) {
1229 _cleanup_fclose_ FILE *f = NULL;
1230 _cleanup_strv_free_ char **zones = NULL;
1231 size_t n_zones = 0, n_allocated = 0;
1235 zones = strv_new("UTC", NULL);
1242 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1246 FOREACH_LINE(l, f, return -errno) {
1252 if (isempty(p) || *p == '#')
1255 /* Skip over country code */
1256 p += strcspn(p, WHITESPACE);
1257 p += strspn(p, WHITESPACE);
1259 /* Skip over coordinates */
1260 p += strcspn(p, WHITESPACE);
1261 p += strspn(p, WHITESPACE);
1263 /* Found timezone name */
1264 k = strcspn(p, WHITESPACE);
1272 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1277 zones[n_zones++] = w;
1278 zones[n_zones] = NULL;
1283 } else if (errno != ENOENT)
1286 *ret = TAKE_PTR(zones);
1291 bool timezone_is_valid(const char *name, int log_level) {
1294 _cleanup_close_ int fd = -1;
1304 for (p = name; *p; p++) {
1305 if (!(*p >= '0' && *p <= '9') &&
1306 !(*p >= 'a' && *p <= 'z') &&
1307 !(*p >= 'A' && *p <= 'Z') &&
1308 !IN_SET(*p, '-', '_', '+', '/'))
1324 if (p - name >= PATH_MAX)
1327 t = strjoina("/usr/share/zoneinfo/", name);
1329 fd = open(t, O_RDONLY|O_CLOEXEC);
1331 log_full_errno(log_level, errno, "Failed to open timezone file '%s': %m", t);
1335 r = fd_verify_regular(fd);
1337 log_full_errno(log_level, r, "Timezone file '%s' is not a regular file: %m", t);
1341 r = loop_read_exact(fd, buf, 4, false);
1343 log_full_errno(log_level, r, "Failed to read from timezone file '%s': %m", t);
1347 /* Magic from tzfile(5) */
1348 if (memcmp(buf, "TZif", 4) != 0) {
1349 log_full(log_level, "Timezone file '%s' has wrong magic bytes", t);
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())
1410 /* For everything else, check properly */
1411 return clock_gettime(clock, &ts) >= 0;
1414 #if 1 /// end diagnostic push in elogind
1416 # pragma GCC diagnostic pop
1420 #if 0 /// UNNEEDED by elogind
1421 int get_timezone(char **tz) {
1422 _cleanup_free_ char *t = NULL;
1427 r = readlink_malloc("/etc/localtime", &t);
1429 return r; /* returns EINVAL if not a symlink */
1431 e = path_startswith(t, "/usr/share/zoneinfo/");
1433 e = path_startswith(t, "../usr/share/zoneinfo/");
1437 if (!timezone_is_valid(e, LOG_DEBUG))
1448 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1449 return utc ? timegm(tm) : mktime(tm);
1453 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1454 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1457 #if 0 /// UNNEEDED by elogind
1458 unsigned long usec_to_jiffies(usec_t u) {
1459 static thread_local unsigned long hz = 0;
1463 r = sysconf(_SC_CLK_TCK);
1469 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1472 usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
1475 if (x == USEC_INFINITY)
1476 return USEC_INFINITY;
1477 if (map_clock_id(from) == map_clock_id(to))
1484 /* x lies in the future */
1485 return usec_add(b, usec_sub_unsigned(x, a));
1487 /* x lies in the past */
1488 return usec_sub_unsigned(b, usec_sub_unsigned(a, x));
1492 bool in_utc_timezone(void) {
1495 return timezone == 0 && daylight == 0;
1498 int time_change_fd(void) {
1500 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1501 static const struct itimerspec its = {
1502 .it_value.tv_sec = TIME_T_MAX,
1505 _cleanup_close_ int fd;
1507 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
1509 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1510 * CLOCK_MONOTONIC. */
1512 fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1516 if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0)