1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2010 Lennart Poettering
13 #include <sys/timerfd.h>
14 #include <sys/timex.h>
15 #include <sys/types.h>
18 #include "alloc-util.h"
22 //#include "io-util.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 //#include "process-util.h"
28 //#include "stat-util.h"
29 #include "string-util.h"
31 #include "time-util.h"
33 static clockid_t map_clock_id(clockid_t c) {
35 /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus, clock_gettime() will
36 * fail for them. Since they are essentially the same as their non-ALARM pendants (their only difference is
37 * when timers are set on them), let's just map them accordingly. This way, we can get the correct time even on
42 case CLOCK_BOOTTIME_ALARM:
43 return CLOCK_BOOTTIME;
45 case CLOCK_REALTIME_ALARM:
46 return CLOCK_REALTIME;
53 usec_t now(clockid_t clock_id) {
56 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
58 return timespec_load(&ts);
61 #if 0 /// UNNEEDED by elogind
62 nsec_t now_nsec(clockid_t clock_id) {
65 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
67 return timespec_load_nsec(&ts);
71 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
74 ts->realtime = now(CLOCK_REALTIME);
75 ts->monotonic = now(CLOCK_MONOTONIC);
80 triple_timestamp* triple_timestamp_get(triple_timestamp *ts) {
83 ts->realtime = now(CLOCK_REALTIME);
84 ts->monotonic = now(CLOCK_MONOTONIC);
85 ts->boottime = clock_boottime_supported() ? now(CLOCK_BOOTTIME) : USEC_INFINITY;
90 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
94 if (u == USEC_INFINITY || u <= 0) {
95 ts->realtime = ts->monotonic = u;
101 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
102 ts->monotonic = usec_sub_signed(now(CLOCK_MONOTONIC), delta);
107 #if 0 /// UNNEEDED by elogind
108 triple_timestamp* triple_timestamp_from_realtime(triple_timestamp *ts, usec_t u) {
113 if (u == USEC_INFINITY || u <= 0) {
114 ts->realtime = ts->monotonic = ts->boottime = u;
119 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
120 ts->monotonic = usec_sub_signed(now(CLOCK_MONOTONIC), delta);
121 ts->boottime = clock_boottime_supported() ? usec_sub_signed(now(CLOCK_BOOTTIME), delta) : USEC_INFINITY;
126 dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
130 if (u == USEC_INFINITY) {
131 ts->realtime = ts->monotonic = USEC_INFINITY;
136 delta = (int64_t) now(CLOCK_MONOTONIC) - (int64_t) u;
137 ts->realtime = usec_sub_signed(now(CLOCK_REALTIME), delta);
142 dual_timestamp* dual_timestamp_from_boottime_or_monotonic(dual_timestamp *ts, usec_t u) {
145 if (u == USEC_INFINITY) {
146 ts->realtime = ts->monotonic = USEC_INFINITY;
150 dual_timestamp_get(ts);
151 delta = (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u;
152 ts->realtime = usec_sub_signed(ts->realtime, delta);
153 ts->monotonic = usec_sub_signed(ts->monotonic, delta);
159 usec_t triple_timestamp_by_clock(triple_timestamp *ts, clockid_t clock) {
164 case CLOCK_REALTIME_ALARM:
167 case CLOCK_MONOTONIC:
168 return ts->monotonic;
171 case CLOCK_BOOTTIME_ALARM:
175 return USEC_INFINITY;
179 usec_t timespec_load(const struct timespec *ts) {
182 if (ts->tv_sec < 0 || ts->tv_nsec < 0)
183 return USEC_INFINITY;
185 if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
186 return USEC_INFINITY;
189 (usec_t) ts->tv_sec * USEC_PER_SEC +
190 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
193 #if 0 /// UNNEEDED by elogind
194 nsec_t timespec_load_nsec(const struct timespec *ts) {
197 if (ts->tv_sec < 0 || ts->tv_nsec < 0)
198 return NSEC_INFINITY;
200 if ((nsec_t) ts->tv_sec >= (UINT64_MAX - ts->tv_nsec) / NSEC_PER_SEC)
201 return NSEC_INFINITY;
203 return (nsec_t) ts->tv_sec * NSEC_PER_SEC + (nsec_t) ts->tv_nsec;
207 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
210 if (u == USEC_INFINITY ||
211 u / USEC_PER_SEC >= TIME_T_MAX) {
212 ts->tv_sec = (time_t) -1;
213 ts->tv_nsec = (long) -1;
217 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
218 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
223 usec_t timeval_load(const struct timeval *tv) {
226 if (tv->tv_sec < 0 || tv->tv_usec < 0)
227 return USEC_INFINITY;
229 if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
230 return USEC_INFINITY;
233 (usec_t) tv->tv_sec * USEC_PER_SEC +
234 (usec_t) tv->tv_usec;
237 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
240 if (u == USEC_INFINITY ||
241 u / USEC_PER_SEC > TIME_T_MAX) {
242 tv->tv_sec = (time_t) -1;
243 tv->tv_usec = (suseconds_t) -1;
245 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
246 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
252 static char *format_timestamp_internal(
259 /* The weekdays in non-localized (English) form. We use this instead of the localized form, so that our
260 * generated timestamps may be parsed with parse_timestamp(), and always read the same. */
261 static const char * const weekdays[] = {
279 1 + 10 + /* space and date */
280 1 + 8 + /* space and time */
281 (us ? 1 + 6 : 0) + /* "." and microsecond part */
282 1 + 1 + /* space and shortest possible zone */
284 return NULL; /* Not enough space even for the shortest form. */
285 if (t <= 0 || t == USEC_INFINITY)
286 return NULL; /* Timestamp is unset */
288 /* Let's not format times with years > 9999 */
289 if (t > USEC_TIMESTAMP_FORMATTABLE_MAX) {
290 assert(l >= strlen("--- XXXX-XX-XX XX:XX:XX") + 1);
291 strcpy(buf, "--- XXXX-XX-XX XX:XX:XX");
295 sec = (time_t) (t / USEC_PER_SEC); /* Round down */
297 if (!localtime_or_gmtime_r(&sec, &tm, utc))
300 /* Start with the week day */
301 assert((size_t) tm.tm_wday < ELEMENTSOF(weekdays));
302 memcpy(buf, weekdays[tm.tm_wday], 4);
304 /* Add the main components */
305 if (strftime(buf + 3, l - 3, " %Y-%m-%d %H:%M:%S", &tm) <= 0)
306 return NULL; /* Doesn't fit */
308 /* Append the microseconds part, if that's requested */
312 return NULL; /* Microseconds part doesn't fit. */
314 sprintf(buf + n, ".%06"PRI_USEC, t % USEC_PER_SEC);
317 /* Append the timezone */
320 /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r() normally uses the
321 * obsolete "GMT" instead. */
323 return NULL; /* "UTC" doesn't fit. */
325 strcpy(buf + n, " UTC");
327 } else if (!isempty(tm.tm_zone)) {
330 /* An explicit timezone is specified, let's use it, if it fits */
331 tn = strlen(tm.tm_zone);
332 if (n + 1 + tn + 1 > l) {
333 /* The full time zone does not fit in. Yuck. */
335 if (n + 1 + _POSIX_TZNAME_MAX + 1 > l)
336 return NULL; /* Not even enough space for the POSIX minimum (of 6)? In that case, complain that it doesn't fit */
338 /* So the time zone doesn't fit in fully, but the caller passed enough space for the POSIX
339 * minimum time zone length. In this case suppress the timezone entirely, in order not to dump
340 * an overly long, hard to read string on the user. This should be safe, because the user will
341 * assume the local timezone anyway if none is shown. And so does parse_timestamp(). */
344 strcpy(buf + n, tm.tm_zone);
351 char *format_timestamp(char *buf, size_t l, usec_t t) {
352 return format_timestamp_internal(buf, l, t, false, false);
355 #if 0 /// UNNEEDED by elogind
356 char *format_timestamp_utc(char *buf, size_t l, usec_t t) {
357 return format_timestamp_internal(buf, l, t, true, false);
361 char *format_timestamp_us(char *buf, size_t l, usec_t t) {
362 return format_timestamp_internal(buf, l, t, false, true);
365 #if 0 /// UNNEEDED by elogind
366 char *format_timestamp_us_utc(char *buf, size_t l, usec_t t) {
367 return format_timestamp_internal(buf, l, t, true, true);
371 char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
375 if (t <= 0 || t == USEC_INFINITY)
378 n = now(CLOCK_REALTIME);
387 if (d >= USEC_PER_YEAR)
388 snprintf(buf, l, USEC_FMT " years " USEC_FMT " months %s",
390 (d % USEC_PER_YEAR) / USEC_PER_MONTH, s);
391 else if (d >= USEC_PER_MONTH)
392 snprintf(buf, l, USEC_FMT " months " USEC_FMT " days %s",
394 (d % USEC_PER_MONTH) / USEC_PER_DAY, s);
395 else if (d >= USEC_PER_WEEK)
396 snprintf(buf, l, USEC_FMT " weeks " USEC_FMT " days %s",
398 (d % USEC_PER_WEEK) / USEC_PER_DAY, s);
399 else if (d >= 2*USEC_PER_DAY)
400 snprintf(buf, l, USEC_FMT " days %s", d / USEC_PER_DAY, s);
401 else if (d >= 25*USEC_PER_HOUR)
402 snprintf(buf, l, "1 day " USEC_FMT "h %s",
403 (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
404 else if (d >= 6*USEC_PER_HOUR)
405 snprintf(buf, l, USEC_FMT "h %s",
406 d / USEC_PER_HOUR, s);
407 else if (d >= USEC_PER_HOUR)
408 snprintf(buf, l, USEC_FMT "h " USEC_FMT "min %s",
410 (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
411 else if (d >= 5*USEC_PER_MINUTE)
412 snprintf(buf, l, USEC_FMT "min %s",
413 d / USEC_PER_MINUTE, s);
414 else if (d >= USEC_PER_MINUTE)
415 snprintf(buf, l, USEC_FMT "min " USEC_FMT "s %s",
417 (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
418 else if (d >= USEC_PER_SEC)
419 snprintf(buf, l, USEC_FMT "s %s",
420 d / USEC_PER_SEC, s);
421 else if (d >= USEC_PER_MSEC)
422 snprintf(buf, l, USEC_FMT "ms %s",
423 d / USEC_PER_MSEC, s);
425 snprintf(buf, l, USEC_FMT"us %s",
428 snprintf(buf, l, "now");
434 char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
435 static const struct {
439 { "y", USEC_PER_YEAR },
440 { "month", USEC_PER_MONTH },
441 { "w", USEC_PER_WEEK },
442 { "d", USEC_PER_DAY },
443 { "h", USEC_PER_HOUR },
444 { "min", USEC_PER_MINUTE },
445 { "s", USEC_PER_SEC },
446 { "ms", USEC_PER_MSEC },
452 bool something = false;
457 if (t == USEC_INFINITY) {
458 strncpy(p, "infinity", l-1);
464 strncpy(p, "0", l-1);
469 /* The result of this function can be parsed with parse_sec */
471 for (i = 0; i < ELEMENTSOF(table); i++) {
480 if (t < accuracy && something)
483 if (t < table[i].usec)
489 a = t / table[i].usec;
490 b = t % table[i].usec;
492 /* Let's see if we should shows this in dot notation */
493 if (t < USEC_PER_MINUTE && b > 0) {
498 for (cc = table[i].usec; cc > 1; cc /= 10)
501 for (cc = accuracy; cc > 1; cc /= 10) {
508 "%s"USEC_FMT".%0*"PRI_USEC"%s",
520 /* No? Then let's show it normally */
531 n = MIN((size_t) k, l);
544 #if 0 /// UNNEEDED by elogind
545 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
551 if (!dual_timestamp_is_set(t))
554 fprintf(f, "%s="USEC_FMT" "USEC_FMT"\n",
560 int dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
567 pos = strspn(value, WHITESPACE);
568 if (value[pos] == '-')
570 pos += strspn(value + pos, DIGITS);
571 pos += strspn(value + pos, WHITESPACE);
572 if (value[pos] == '-')
575 r = sscanf(value, "%" PRIu64 "%" PRIu64 "%n", &a, &b, &pos);
577 log_debug("Failed to parse dual timestamp value \"%s\".", value);
581 if (value[pos] != '\0')
582 /* trailing garbage */
592 int timestamp_deserialize(const char *value, usec_t *timestamp) {
597 r = safe_atou64(value, timestamp);
599 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
604 #if 0 /// UNNEEDED by elogind
605 static int parse_timestamp_impl(const char *t, usec_t *usec, bool with_tz) {
606 static const struct {
626 const char *k, *utc = NULL, *tzn = NULL;
629 usec_t x_usec, plus = 0, minus = 0, ret;
630 int r, weekday = -1, dst = -1;
635 * 2012-09-22 16:34:22
636 * 2012-09-22 16:34 (seconds will be set to 0)
637 * 2012-09-22 (time will be set to 00:00:00)
638 * 16:34:22 (date will be set to today)
639 * 16:34 (date will be set to today, seconds to 0)
641 * yesterday (time is set to 00:00:00)
642 * today (time is set to 00:00:00)
643 * tomorrow (time is set to 00:00:00)
646 * @2147483647 (seconds since epoch)
652 if (t[0] == '@' && !with_tz)
653 return parse_sec(t + 1, usec);
655 ret = now(CLOCK_REALTIME);
661 else if (t[0] == '+') {
662 r = parse_sec(t+1, &plus);
668 } else if (t[0] == '-') {
669 r = parse_sec(t+1, &minus);
675 } else if ((k = endswith(t, " ago"))) {
676 t = strndupa(t, k - t);
678 r = parse_sec(t, &minus);
684 } else if ((k = endswith(t, " left"))) {
685 t = strndupa(t, k - t);
687 r = parse_sec(t, &plus);
694 /* See if the timestamp is suffixed with UTC */
695 utc = endswith_no_case(t, " UTC");
697 t = strndupa(t, utc - t);
699 const char *e = NULL;
704 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
705 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
706 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
707 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
708 * support arbitrary timezone specifications. */
710 for (j = 0; j <= 1; j++) {
712 if (isempty(tzname[j]))
715 e = endswith_no_case(t, tzname[j]);
726 if (IN_SET(j, 0, 1)) {
727 /* Found one of the two timezones specified. */
728 t = strndupa(t, e - t - 1);
735 x = (time_t) (ret / USEC_PER_SEC);
738 if (!localtime_or_gmtime_r(&x, &tm, utc))
745 if (streq(t, "today")) {
746 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
749 } else if (streq(t, "yesterday")) {
751 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
754 } else if (streq(t, "tomorrow")) {
756 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
760 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
763 if (!startswith_no_case(t, day_nr[i].name))
766 skip = strlen(day_nr[i].name);
770 weekday = day_nr[i].nr;
776 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
785 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
794 k = strptime(t, "%y-%m-%d %H:%M", &tm);
801 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
808 k = strptime(t, "%y-%m-%d", &tm);
810 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
815 k = strptime(t, "%Y-%m-%d", &tm);
817 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
822 k = strptime(t, "%H:%M:%S", &tm);
831 k = strptime(t, "%H:%M", &tm);
844 r = parse_fractional_part_u(&k, 6, &add);
855 if (weekday >= 0 && tm.tm_wday != weekday)
858 x = mktime_or_timegm(&tm, utc);
862 ret = (usec_t) x * USEC_PER_SEC + x_usec;
863 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
867 if (ret + plus < ret) /* overflow? */
870 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
883 typedef struct ParseTimestampResult {
886 } ParseTimestampResult;
888 int parse_timestamp(const char *t, usec_t *usec) {
889 char *last_space, *tz = NULL;
890 ParseTimestampResult *shared, tmp;
893 last_space = strrchr(t, ' ');
894 if (last_space != NULL && timezone_is_valid(last_space + 1, LOG_DEBUG))
897 if (!tz || endswith_no_case(t, " UTC"))
898 return parse_timestamp_impl(t, usec, false);
900 shared = mmap(NULL, sizeof *shared, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
901 if (shared == MAP_FAILED)
902 return negative_errno();
904 r = safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_WAIT, NULL);
906 (void) munmap(shared, sizeof *shared);
912 if (setenv("TZ", tz, 1) != 0) {
913 shared->return_value = negative_errno();
919 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
920 * Otherwise just cut it off. */
921 with_tz = !STR_IN_SET(tz, tzname[0], tzname[1]);
923 /* Cut off the timezone if we dont need it. */
925 t = strndupa(t, last_space - t);
927 shared->return_value = parse_timestamp_impl(t, &shared->usec, with_tz);
933 if (munmap(shared, sizeof *shared) != 0)
934 return negative_errno();
936 if (tmp.return_value == 0)
939 return tmp.return_value;
943 static char* extract_multiplier(char *p, usec_t *multiplier) {
944 static const struct {
948 { "seconds", USEC_PER_SEC },
949 { "second", USEC_PER_SEC },
950 { "sec", USEC_PER_SEC },
951 { "s", USEC_PER_SEC },
952 { "minutes", USEC_PER_MINUTE },
953 { "minute", USEC_PER_MINUTE },
954 { "min", USEC_PER_MINUTE },
955 { "months", USEC_PER_MONTH },
956 { "month", USEC_PER_MONTH },
957 { "M", USEC_PER_MONTH },
958 { "msec", USEC_PER_MSEC },
959 { "ms", USEC_PER_MSEC },
960 { "m", USEC_PER_MINUTE },
961 { "hours", USEC_PER_HOUR },
962 { "hour", USEC_PER_HOUR },
963 { "hr", USEC_PER_HOUR },
964 { "h", USEC_PER_HOUR },
965 { "days", USEC_PER_DAY },
966 { "day", USEC_PER_DAY },
967 { "d", USEC_PER_DAY },
968 { "weeks", USEC_PER_WEEK },
969 { "week", USEC_PER_WEEK },
970 { "w", USEC_PER_WEEK },
971 { "years", USEC_PER_YEAR },
972 { "year", USEC_PER_YEAR },
973 { "y", USEC_PER_YEAR },
980 for (i = 0; i < ELEMENTSOF(table); i++) {
983 e = startswith(p, table[i].suffix);
985 *multiplier = table[i].usec;
993 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
996 bool something = false;
1000 assert(default_unit > 0);
1004 p += strspn(p, WHITESPACE);
1005 s = startswith(p, "infinity");
1007 s += strspn(s, WHITESPACE);
1011 *usec = USEC_INFINITY;
1019 usec_t multiplier = default_unit, k;
1021 p += strspn(p, WHITESPACE);
1031 l = strtoll(p, &e, 10);
1041 z = strtoll(b, &e, 10);
1056 e += strspn(e, WHITESPACE);
1057 p = extract_multiplier(e, &multiplier);
1061 k = (usec_t) z * multiplier;
1066 r += (usec_t) l * multiplier + k;
1074 int parse_sec(const char *t, usec_t *usec) {
1075 return parse_time(t, usec, USEC_PER_SEC);
1078 #if 0 /// UNNEEDED by elogind
1079 int parse_sec_fix_0(const char *t, usec_t *usec) {
1083 t += strspn(t, WHITESPACE);
1085 if (streq(t, "0")) {
1086 *usec = USEC_INFINITY;
1090 return parse_sec(t, usec);
1093 int parse_nsec(const char *t, nsec_t *nsec) {
1094 static const struct {
1098 { "seconds", NSEC_PER_SEC },
1099 { "second", NSEC_PER_SEC },
1100 { "sec", NSEC_PER_SEC },
1101 { "s", NSEC_PER_SEC },
1102 { "minutes", NSEC_PER_MINUTE },
1103 { "minute", NSEC_PER_MINUTE },
1104 { "min", NSEC_PER_MINUTE },
1105 { "months", NSEC_PER_MONTH },
1106 { "month", NSEC_PER_MONTH },
1107 { "msec", NSEC_PER_MSEC },
1108 { "ms", NSEC_PER_MSEC },
1109 { "m", NSEC_PER_MINUTE },
1110 { "hours", NSEC_PER_HOUR },
1111 { "hour", NSEC_PER_HOUR },
1112 { "hr", NSEC_PER_HOUR },
1113 { "h", NSEC_PER_HOUR },
1114 { "days", NSEC_PER_DAY },
1115 { "day", NSEC_PER_DAY },
1116 { "d", NSEC_PER_DAY },
1117 { "weeks", NSEC_PER_WEEK },
1118 { "week", NSEC_PER_WEEK },
1119 { "w", NSEC_PER_WEEK },
1120 { "years", NSEC_PER_YEAR },
1121 { "year", NSEC_PER_YEAR },
1122 { "y", NSEC_PER_YEAR },
1123 { "usec", NSEC_PER_USEC },
1124 { "us", NSEC_PER_USEC },
1125 { "µs", NSEC_PER_USEC },
1128 { "", 1ULL }, /* default is nsec */
1133 bool something = false;
1140 p += strspn(p, WHITESPACE);
1141 s = startswith(p, "infinity");
1143 s += strspn(s, WHITESPACE);
1147 *nsec = NSEC_INFINITY;
1156 p += strspn(p, WHITESPACE);
1166 l = strtoll(p, &e, 10);
1178 z = strtoll(b, &e, 10);
1193 e += strspn(e, WHITESPACE);
1195 for (i = 0; i < ELEMENTSOF(table); i++)
1196 if (startswith(e, table[i].suffix)) {
1197 nsec_t k = (nsec_t) z * table[i].nsec;
1202 r += (nsec_t) l * table[i].nsec + k;
1203 p = e + strlen(table[i].suffix);
1209 if (i >= ELEMENTSOF(table))
1219 bool ntp_synced(void) {
1220 struct timex txc = {};
1222 if (adjtimex(&txc) < 0)
1225 if (txc.status & STA_UNSYNC)
1231 int get_timezones(char ***ret) {
1232 _cleanup_fclose_ FILE *f = NULL;
1233 _cleanup_strv_free_ char **zones = NULL;
1234 size_t n_zones = 0, n_allocated = 0;
1238 zones = strv_new("UTC", NULL);
1245 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1249 FOREACH_LINE(l, f, return -errno) {
1255 if (isempty(p) || *p == '#')
1258 /* Skip over country code */
1259 p += strcspn(p, WHITESPACE);
1260 p += strspn(p, WHITESPACE);
1262 /* Skip over coordinates */
1263 p += strcspn(p, WHITESPACE);
1264 p += strspn(p, WHITESPACE);
1266 /* Found timezone name */
1267 k = strcspn(p, WHITESPACE);
1275 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1280 zones[n_zones++] = w;
1281 zones[n_zones] = NULL;
1286 } else if (errno != ENOENT)
1289 *ret = TAKE_PTR(zones);
1294 bool timezone_is_valid(const char *name, int log_level) {
1297 _cleanup_close_ int fd = -1;
1307 for (p = name; *p; p++) {
1308 if (!(*p >= '0' && *p <= '9') &&
1309 !(*p >= 'a' && *p <= 'z') &&
1310 !(*p >= 'A' && *p <= 'Z') &&
1311 !IN_SET(*p, '-', '_', '+', '/'))
1327 if (p - name >= PATH_MAX)
1330 t = strjoina("/usr/share/zoneinfo/", name);
1332 fd = open(t, O_RDONLY|O_CLOEXEC);
1334 log_full_errno(log_level, errno, "Failed to open timezone file '%s': %m", t);
1338 r = fd_verify_regular(fd);
1340 log_full_errno(log_level, r, "Timezone file '%s' is not a regular file: %m", t);
1344 r = loop_read_exact(fd, buf, 4, false);
1346 log_full_errno(log_level, r, "Failed to read from timezone file '%s': %m", t);
1350 /* Magic from tzfile(5) */
1351 if (memcmp(buf, "TZif", 4) != 0) {
1352 log_full(log_level, "Timezone file '%s' has wrong magic bytes", t);
1360 bool clock_boottime_supported(void) {
1361 static int supported = -1;
1363 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1365 if (supported < 0) {
1368 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1380 #if 0 /// UNNEEDED by elogind
1381 clockid_t clock_boottime_or_monotonic(void) {
1382 if (clock_boottime_supported())
1383 return CLOCK_BOOTTIME;
1385 return CLOCK_MONOTONIC;
1389 #if 1 /// let's add a diagnostic push to silence -Wimplicit-fallthrough to elogind
1390 # if defined(__GNUC__) && (__GNUC__ > 6)
1391 # pragma GCC diagnostic push
1392 # pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
1395 bool clock_supported(clockid_t clock) {
1400 case CLOCK_MONOTONIC:
1401 case CLOCK_REALTIME:
1404 case CLOCK_BOOTTIME:
1405 return clock_boottime_supported();
1407 case CLOCK_BOOTTIME_ALARM:
1408 if (!clock_boottime_supported())
1413 /* For everything else, check properly */
1414 return clock_gettime(clock, &ts) >= 0;
1417 #if 1 /// end diagnostic push in elogind
1419 # pragma GCC diagnostic pop
1423 #if 0 /// UNNEEDED by elogind
1424 int get_timezone(char **tz) {
1425 _cleanup_free_ char *t = NULL;
1430 r = readlink_malloc("/etc/localtime", &t);
1432 return r; /* returns EINVAL if not a symlink */
1434 e = path_startswith(t, "/usr/share/zoneinfo/");
1436 e = path_startswith(t, "../usr/share/zoneinfo/");
1440 if (!timezone_is_valid(e, LOG_DEBUG))
1451 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1452 return utc ? timegm(tm) : mktime(tm);
1456 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1457 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1460 #if 0 /// UNNEEDED by elogind
1461 unsigned long usec_to_jiffies(usec_t u) {
1462 static thread_local unsigned long hz = 0;
1466 r = sysconf(_SC_CLK_TCK);
1472 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1475 usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
1478 if (x == USEC_INFINITY)
1479 return USEC_INFINITY;
1480 if (map_clock_id(from) == map_clock_id(to))
1487 /* x lies in the future */
1488 return usec_add(b, usec_sub_unsigned(x, a));
1490 /* x lies in the past */
1491 return usec_sub_unsigned(b, usec_sub_unsigned(a, x));
1495 bool in_utc_timezone(void) {
1498 return timezone == 0 && daylight == 0;
1501 int time_change_fd(void) {
1503 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1504 static const struct itimerspec its = {
1505 .it_value.tv_sec = TIME_T_MAX,
1508 _cleanup_close_ int fd;
1510 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
1512 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1513 * CLOCK_MONOTONIC. */
1515 fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1519 if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0)