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) {
292 assert(l >= strlen("--- XXXX-XX-XX XX:XX:XX") + 1);
293 strcpy(buf, "--- XXXX-XX-XX XX:XX:XX");
297 sec = (time_t) (t / USEC_PER_SEC); /* Round down */
299 if (!localtime_or_gmtime_r(&sec, &tm, utc))
302 /* Start with the week day */
303 assert((size_t) tm.tm_wday < ELEMENTSOF(weekdays));
304 memcpy(buf, weekdays[tm.tm_wday], 4);
306 /* Add the main components */
307 if (strftime(buf + 3, l - 3, " %Y-%m-%d %H:%M:%S", &tm) <= 0)
308 return NULL; /* Doesn't fit */
310 /* Append the microseconds part, if that's requested */
314 return NULL; /* Microseconds part doesn't fit. */
316 sprintf(buf + n, ".%06"PRI_USEC, t % USEC_PER_SEC);
319 /* Append the timezone */
322 /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r() normally uses the
323 * obsolete "GMT" instead. */
325 return NULL; /* "UTC" doesn't fit. */
327 strcpy(buf + n, " UTC");
329 } else if (!isempty(tm.tm_zone)) {
332 /* An explicit timezone is specified, let's use it, if it fits */
333 tn = strlen(tm.tm_zone);
334 if (n + 1 + tn + 1 > l) {
335 /* The full time zone does not fit in. Yuck. */
337 if (n + 1 + _POSIX_TZNAME_MAX + 1 > l)
338 return NULL; /* Not even enough space for the POSIX minimum (of 6)? In that case, complain that it doesn't fit */
340 /* So the time zone doesn't fit in fully, but the caller passed enough space for the POSIX
341 * minimum time zone length. In this case suppress the timezone entirely, in order not to dump
342 * an overly long, hard to read string on the user. This should be safe, because the user will
343 * assume the local timezone anyway if none is shown. And so does parse_timestamp(). */
346 strcpy(buf + n, tm.tm_zone);
353 char *format_timestamp(char *buf, size_t l, usec_t t) {
354 return format_timestamp_internal(buf, l, t, false, false);
357 #if 0 /// UNNEEDED by elogind
358 char *format_timestamp_utc(char *buf, size_t l, usec_t t) {
359 return format_timestamp_internal(buf, l, t, true, false);
363 char *format_timestamp_us(char *buf, size_t l, usec_t t) {
364 return format_timestamp_internal(buf, l, t, false, true);
367 #if 0 /// UNNEEDED by elogind
368 char *format_timestamp_us_utc(char *buf, size_t l, usec_t t) {
369 return format_timestamp_internal(buf, l, t, true, true);
373 char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
377 if (t <= 0 || t == USEC_INFINITY)
380 n = now(CLOCK_REALTIME);
389 if (d >= USEC_PER_YEAR)
390 snprintf(buf, l, USEC_FMT " years " USEC_FMT " months %s",
392 (d % USEC_PER_YEAR) / USEC_PER_MONTH, s);
393 else if (d >= USEC_PER_MONTH)
394 snprintf(buf, l, USEC_FMT " months " USEC_FMT " days %s",
396 (d % USEC_PER_MONTH) / USEC_PER_DAY, s);
397 else if (d >= USEC_PER_WEEK)
398 snprintf(buf, l, USEC_FMT " weeks " USEC_FMT " days %s",
400 (d % USEC_PER_WEEK) / USEC_PER_DAY, s);
401 else if (d >= 2*USEC_PER_DAY)
402 snprintf(buf, l, USEC_FMT " days %s", d / USEC_PER_DAY, s);
403 else if (d >= 25*USEC_PER_HOUR)
404 snprintf(buf, l, "1 day " USEC_FMT "h %s",
405 (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
406 else if (d >= 6*USEC_PER_HOUR)
407 snprintf(buf, l, USEC_FMT "h %s",
408 d / USEC_PER_HOUR, s);
409 else if (d >= USEC_PER_HOUR)
410 snprintf(buf, l, USEC_FMT "h " USEC_FMT "min %s",
412 (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
413 else if (d >= 5*USEC_PER_MINUTE)
414 snprintf(buf, l, USEC_FMT "min %s",
415 d / USEC_PER_MINUTE, s);
416 else if (d >= USEC_PER_MINUTE)
417 snprintf(buf, l, USEC_FMT "min " USEC_FMT "s %s",
419 (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
420 else if (d >= USEC_PER_SEC)
421 snprintf(buf, l, USEC_FMT "s %s",
422 d / USEC_PER_SEC, s);
423 else if (d >= USEC_PER_MSEC)
424 snprintf(buf, l, USEC_FMT "ms %s",
425 d / USEC_PER_MSEC, s);
427 snprintf(buf, l, USEC_FMT"us %s",
430 snprintf(buf, l, "now");
436 char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
437 static const struct {
441 { "y", USEC_PER_YEAR },
442 { "month", USEC_PER_MONTH },
443 { "w", USEC_PER_WEEK },
444 { "d", USEC_PER_DAY },
445 { "h", USEC_PER_HOUR },
446 { "min", USEC_PER_MINUTE },
447 { "s", USEC_PER_SEC },
448 { "ms", USEC_PER_MSEC },
454 bool something = false;
459 if (t == USEC_INFINITY) {
460 strncpy(p, "infinity", l-1);
466 strncpy(p, "0", l-1);
471 /* The result of this function can be parsed with parse_sec */
473 for (i = 0; i < ELEMENTSOF(table); i++) {
482 if (t < accuracy && something)
485 if (t < table[i].usec)
491 a = t / table[i].usec;
492 b = t % table[i].usec;
494 /* Let's see if we should shows this in dot notation */
495 if (t < USEC_PER_MINUTE && b > 0) {
500 for (cc = table[i].usec; cc > 1; cc /= 10)
503 for (cc = accuracy; cc > 1; cc /= 10) {
510 "%s"USEC_FMT".%0*"PRI_USEC"%s",
522 /* No? Then let's show it normally */
533 n = MIN((size_t) k, l);
546 #if 0 /// UNNEEDED by elogind
547 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
553 if (!dual_timestamp_is_set(t))
556 fprintf(f, "%s="USEC_FMT" "USEC_FMT"\n",
562 int dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
569 pos = strspn(value, WHITESPACE);
570 if (value[pos] == '-')
572 pos += strspn(value + pos, DIGITS);
573 pos += strspn(value + pos, WHITESPACE);
574 if (value[pos] == '-')
577 r = sscanf(value, "%" PRIu64 "%" PRIu64 "%n", &a, &b, &pos);
579 log_debug("Failed to parse dual timestamp value \"%s\".", value);
583 if (value[pos] != '\0')
584 /* trailing garbage */
594 int timestamp_deserialize(const char *value, usec_t *timestamp) {
599 r = safe_atou64(value, timestamp);
601 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
606 #if 0 /// UNNEEDED by elogind
607 static int parse_timestamp_impl(const char *t, usec_t *usec, bool with_tz) {
608 static const struct {
628 const char *k, *utc = NULL, *tzn = NULL;
631 usec_t x_usec, plus = 0, minus = 0, ret;
632 int r, weekday = -1, dst = -1;
637 * 2012-09-22 16:34:22
638 * 2012-09-22 16:34 (seconds will be set to 0)
639 * 2012-09-22 (time will be set to 00:00:00)
640 * 16:34:22 (date will be set to today)
641 * 16:34 (date will be set to today, seconds to 0)
643 * yesterday (time is set to 00:00:00)
644 * today (time is set to 00:00:00)
645 * tomorrow (time is set to 00:00:00)
648 * @2147483647 (seconds since epoch)
654 if (t[0] == '@' && !with_tz)
655 return parse_sec(t + 1, usec);
657 ret = now(CLOCK_REALTIME);
663 else if (t[0] == '+') {
664 r = parse_sec(t+1, &plus);
670 } else if (t[0] == '-') {
671 r = parse_sec(t+1, &minus);
677 } else if ((k = endswith(t, " ago"))) {
678 t = strndupa(t, k - t);
680 r = parse_sec(t, &minus);
686 } else if ((k = endswith(t, " left"))) {
687 t = strndupa(t, k - t);
689 r = parse_sec(t, &plus);
696 /* See if the timestamp is suffixed with UTC */
697 utc = endswith_no_case(t, " UTC");
699 t = strndupa(t, utc - t);
701 const char *e = NULL;
706 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
707 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
708 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
709 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
710 * support arbitrary timezone specifications. */
712 for (j = 0; j <= 1; j++) {
714 if (isempty(tzname[j]))
717 e = endswith_no_case(t, tzname[j]);
728 if (IN_SET(j, 0, 1)) {
729 /* Found one of the two timezones specified. */
730 t = strndupa(t, e - t - 1);
737 x = (time_t) (ret / USEC_PER_SEC);
740 if (!localtime_or_gmtime_r(&x, &tm, utc))
747 if (streq(t, "today")) {
748 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
751 } else if (streq(t, "yesterday")) {
753 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
756 } else if (streq(t, "tomorrow")) {
758 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
762 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
765 if (!startswith_no_case(t, day_nr[i].name))
768 skip = strlen(day_nr[i].name);
772 weekday = day_nr[i].nr;
778 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
787 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
796 k = strptime(t, "%y-%m-%d %H:%M", &tm);
803 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
810 k = strptime(t, "%y-%m-%d", &tm);
812 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
817 k = strptime(t, "%Y-%m-%d", &tm);
819 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
824 k = strptime(t, "%H:%M:%S", &tm);
833 k = strptime(t, "%H:%M", &tm);
846 r = parse_fractional_part_u(&k, 6, &add);
857 if (weekday >= 0 && tm.tm_wday != weekday)
860 x = mktime_or_timegm(&tm, utc);
864 ret = (usec_t) x * USEC_PER_SEC + x_usec;
865 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
869 if (ret + plus < ret) /* overflow? */
872 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
885 typedef struct ParseTimestampResult {
888 } ParseTimestampResult;
890 int parse_timestamp(const char *t, usec_t *usec) {
891 char *last_space, *tz = NULL;
892 ParseTimestampResult *shared, tmp;
895 last_space = strrchr(t, ' ');
896 if (last_space != NULL && timezone_is_valid(last_space + 1, LOG_DEBUG))
899 if (!tz || endswith_no_case(t, " UTC"))
900 return parse_timestamp_impl(t, usec, false);
902 shared = mmap(NULL, sizeof *shared, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
903 if (shared == MAP_FAILED)
904 return negative_errno();
906 r = safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_WAIT, NULL);
908 (void) munmap(shared, sizeof *shared);
914 if (setenv("TZ", tz, 1) != 0) {
915 shared->return_value = negative_errno();
921 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
922 * Otherwise just cut it off. */
923 with_tz = !STR_IN_SET(tz, tzname[0], tzname[1]);
925 /* Cut off the timezone if we dont need it. */
927 t = strndupa(t, last_space - t);
929 shared->return_value = parse_timestamp_impl(t, &shared->usec, with_tz);
935 if (munmap(shared, sizeof *shared) != 0)
936 return negative_errno();
938 if (tmp.return_value == 0)
941 return tmp.return_value;
945 static char* extract_multiplier(char *p, usec_t *multiplier) {
946 static const struct {
950 { "seconds", USEC_PER_SEC },
951 { "second", USEC_PER_SEC },
952 { "sec", USEC_PER_SEC },
953 { "s", USEC_PER_SEC },
954 { "minutes", USEC_PER_MINUTE },
955 { "minute", USEC_PER_MINUTE },
956 { "min", USEC_PER_MINUTE },
957 { "months", USEC_PER_MONTH },
958 { "month", USEC_PER_MONTH },
959 { "M", USEC_PER_MONTH },
960 { "msec", USEC_PER_MSEC },
961 { "ms", USEC_PER_MSEC },
962 { "m", USEC_PER_MINUTE },
963 { "hours", USEC_PER_HOUR },
964 { "hour", USEC_PER_HOUR },
965 { "hr", USEC_PER_HOUR },
966 { "h", USEC_PER_HOUR },
967 { "days", USEC_PER_DAY },
968 { "day", USEC_PER_DAY },
969 { "d", USEC_PER_DAY },
970 { "weeks", USEC_PER_WEEK },
971 { "week", USEC_PER_WEEK },
972 { "w", USEC_PER_WEEK },
973 { "years", USEC_PER_YEAR },
974 { "year", USEC_PER_YEAR },
975 { "y", USEC_PER_YEAR },
982 for (i = 0; i < ELEMENTSOF(table); i++) {
985 e = startswith(p, table[i].suffix);
987 *multiplier = table[i].usec;
995 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
998 bool something = false;
1002 assert(default_unit > 0);
1006 p += strspn(p, WHITESPACE);
1007 s = startswith(p, "infinity");
1009 s += strspn(s, WHITESPACE);
1013 *usec = USEC_INFINITY;
1021 usec_t multiplier = default_unit, k;
1023 p += strspn(p, WHITESPACE);
1033 l = strtoll(p, &e, 10);
1043 z = strtoll(b, &e, 10);
1058 e += strspn(e, WHITESPACE);
1059 p = extract_multiplier(e, &multiplier);
1063 k = (usec_t) z * multiplier;
1068 r += (usec_t) l * multiplier + k;
1076 int parse_sec(const char *t, usec_t *usec) {
1077 return parse_time(t, usec, USEC_PER_SEC);
1080 #if 0 /// UNNEEDED by elogind
1081 int parse_sec_fix_0(const char *t, usec_t *usec) {
1085 t += strspn(t, WHITESPACE);
1087 if (streq(t, "0")) {
1088 *usec = USEC_INFINITY;
1092 return parse_sec(t, usec);
1095 int parse_nsec(const char *t, nsec_t *nsec) {
1096 static const struct {
1100 { "seconds", NSEC_PER_SEC },
1101 { "second", NSEC_PER_SEC },
1102 { "sec", NSEC_PER_SEC },
1103 { "s", NSEC_PER_SEC },
1104 { "minutes", NSEC_PER_MINUTE },
1105 { "minute", NSEC_PER_MINUTE },
1106 { "min", NSEC_PER_MINUTE },
1107 { "months", NSEC_PER_MONTH },
1108 { "month", NSEC_PER_MONTH },
1109 { "msec", NSEC_PER_MSEC },
1110 { "ms", NSEC_PER_MSEC },
1111 { "m", NSEC_PER_MINUTE },
1112 { "hours", NSEC_PER_HOUR },
1113 { "hour", NSEC_PER_HOUR },
1114 { "hr", NSEC_PER_HOUR },
1115 { "h", NSEC_PER_HOUR },
1116 { "days", NSEC_PER_DAY },
1117 { "day", NSEC_PER_DAY },
1118 { "d", NSEC_PER_DAY },
1119 { "weeks", NSEC_PER_WEEK },
1120 { "week", NSEC_PER_WEEK },
1121 { "w", NSEC_PER_WEEK },
1122 { "years", NSEC_PER_YEAR },
1123 { "year", NSEC_PER_YEAR },
1124 { "y", NSEC_PER_YEAR },
1125 { "usec", NSEC_PER_USEC },
1126 { "us", NSEC_PER_USEC },
1127 { "µs", NSEC_PER_USEC },
1130 { "", 1ULL }, /* default is nsec */
1135 bool something = false;
1142 p += strspn(p, WHITESPACE);
1143 s = startswith(p, "infinity");
1145 s += strspn(s, WHITESPACE);
1149 *nsec = NSEC_INFINITY;
1158 p += strspn(p, WHITESPACE);
1168 l = strtoll(p, &e, 10);
1180 z = strtoll(b, &e, 10);
1195 e += strspn(e, WHITESPACE);
1197 for (i = 0; i < ELEMENTSOF(table); i++)
1198 if (startswith(e, table[i].suffix)) {
1199 nsec_t k = (nsec_t) z * table[i].nsec;
1204 r += (nsec_t) l * table[i].nsec + k;
1205 p = e + strlen(table[i].suffix);
1211 if (i >= ELEMENTSOF(table))
1221 bool ntp_synced(void) {
1222 struct timex txc = {};
1224 if (adjtimex(&txc) < 0)
1227 if (txc.status & STA_UNSYNC)
1233 int get_timezones(char ***ret) {
1234 _cleanup_fclose_ FILE *f = NULL;
1235 _cleanup_strv_free_ char **zones = NULL;
1236 size_t n_zones = 0, n_allocated = 0;
1240 zones = strv_new("UTC", NULL);
1247 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1251 FOREACH_LINE(l, f, return -errno) {
1257 if (isempty(p) || *p == '#')
1260 /* Skip over country code */
1261 p += strcspn(p, WHITESPACE);
1262 p += strspn(p, WHITESPACE);
1264 /* Skip over coordinates */
1265 p += strcspn(p, WHITESPACE);
1266 p += strspn(p, WHITESPACE);
1268 /* Found timezone name */
1269 k = strcspn(p, WHITESPACE);
1277 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1282 zones[n_zones++] = w;
1283 zones[n_zones] = NULL;
1288 } else if (errno != ENOENT)
1291 *ret = TAKE_PTR(zones);
1296 bool timezone_is_valid(const char *name, int log_level) {
1299 _cleanup_close_ int fd = -1;
1309 for (p = name; *p; p++) {
1310 if (!(*p >= '0' && *p <= '9') &&
1311 !(*p >= 'a' && *p <= 'z') &&
1312 !(*p >= 'A' && *p <= 'Z') &&
1313 !IN_SET(*p, '-', '_', '+', '/'))
1329 if (p - name >= PATH_MAX)
1332 t = strjoina("/usr/share/zoneinfo/", name);
1334 fd = open(t, O_RDONLY|O_CLOEXEC);
1336 log_full_errno(log_level, errno, "Failed to open timezone file '%s': %m", t);
1340 r = fd_verify_regular(fd);
1342 log_full_errno(log_level, r, "Timezone file '%s' is not a regular file: %m", t);
1346 r = loop_read_exact(fd, buf, 4, false);
1348 log_full_errno(log_level, r, "Failed to read from timezone file '%s': %m", t);
1352 /* Magic from tzfile(5) */
1353 if (memcmp(buf, "TZif", 4) != 0) {
1354 log_full(log_level, "Timezone file '%s' has wrong magic bytes", t);
1362 bool clock_boottime_supported(void) {
1363 static int supported = -1;
1365 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1367 if (supported < 0) {
1370 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1382 #if 0 /// UNNEEDED by elogind
1383 clockid_t clock_boottime_or_monotonic(void) {
1384 if (clock_boottime_supported())
1385 return CLOCK_BOOTTIME;
1387 return CLOCK_MONOTONIC;
1391 #if 1 /// let's add a diagnostic push to silence -Wimplicit-fallthrough to elogind
1392 # if defined(__GNUC__) && (__GNUC__ > 6)
1393 # pragma GCC diagnostic push
1394 # pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
1397 bool clock_supported(clockid_t clock) {
1402 case CLOCK_MONOTONIC:
1403 case CLOCK_REALTIME:
1406 case CLOCK_BOOTTIME:
1407 return clock_boottime_supported();
1409 case CLOCK_BOOTTIME_ALARM:
1410 if (!clock_boottime_supported())
1415 /* For everything else, check properly */
1416 return clock_gettime(clock, &ts) >= 0;
1419 #if 1 /// end diagnostic push in elogind
1421 # pragma GCC diagnostic pop
1425 #if 0 /// UNNEEDED by elogind
1426 int get_timezone(char **tz) {
1427 _cleanup_free_ char *t = NULL;
1432 r = readlink_malloc("/etc/localtime", &t);
1434 return r; /* returns EINVAL if not a symlink */
1436 e = path_startswith(t, "/usr/share/zoneinfo/");
1438 e = path_startswith(t, "../usr/share/zoneinfo/");
1442 if (!timezone_is_valid(e, LOG_DEBUG))
1453 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1454 return utc ? timegm(tm) : mktime(tm);
1458 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1459 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1462 #if 0 /// UNNEEDED by elogind
1463 unsigned long usec_to_jiffies(usec_t u) {
1464 static thread_local unsigned long hz = 0;
1468 r = sysconf(_SC_CLK_TCK);
1474 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1477 usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
1480 if (x == USEC_INFINITY)
1481 return USEC_INFINITY;
1482 if (map_clock_id(from) == map_clock_id(to))
1489 /* x lies in the future */
1490 return usec_add(b, usec_sub_unsigned(x, a));
1492 /* x lies in the past */
1493 return usec_sub_unsigned(b, usec_sub_unsigned(a, x));
1497 bool in_utc_timezone(void) {
1500 return timezone == 0 && daylight == 0;
1503 int time_change_fd(void) {
1505 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1506 static const struct itimerspec its = {
1507 .it_value.tv_sec = TIME_T_MAX,
1510 _cleanup_close_ int fd;
1512 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
1514 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1515 * CLOCK_MONOTONIC. */
1517 fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1521 if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0)