2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
26 #include <sys/timerfd.h>
27 #include <sys/timex.h>
28 #include <sys/types.h>
31 #include "alloc-util.h"
37 #include "parse-util.h"
38 #include "path-util.h"
39 #include "string-util.h"
41 #include "time-util.h"
43 #if 0 /// UNNEEDED by elogind
44 static nsec_t timespec_load_nsec(const struct timespec *ts);
47 static clockid_t map_clock_id(clockid_t c) {
49 /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus, clock_gettime() will
50 * fail for them. Since they are essentially the same as their non-ALARM pendants (their only difference is
51 * when timers are set on them), let's just map them accordingly. This way, we can get the correct time even on
56 case CLOCK_BOOTTIME_ALARM:
57 return CLOCK_BOOTTIME;
59 case CLOCK_REALTIME_ALARM:
60 return CLOCK_REALTIME;
67 usec_t now(clockid_t clock_id) {
70 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
72 return timespec_load(&ts);
75 #if 0 /// UNNEEDED by elogind
76 nsec_t now_nsec(clockid_t clock_id) {
79 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
81 return timespec_load_nsec(&ts);
85 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
88 ts->realtime = now(CLOCK_REALTIME);
89 ts->monotonic = now(CLOCK_MONOTONIC);
94 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
98 if (u == USEC_INFINITY || u <= 0) {
99 ts->realtime = ts->monotonic = u;
105 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
106 ts->monotonic = usec_sub(now(CLOCK_MONOTONIC), delta);
111 #if 0 /// UNNEEDED by elogind
112 dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
116 if (u == USEC_INFINITY) {
117 ts->realtime = ts->monotonic = USEC_INFINITY;
122 delta = (int64_t) now(CLOCK_MONOTONIC) - (int64_t) u;
123 ts->realtime = usec_sub(now(CLOCK_REALTIME), delta);
128 dual_timestamp* dual_timestamp_from_boottime_or_monotonic(dual_timestamp *ts, usec_t u) {
131 if (u == USEC_INFINITY) {
132 ts->realtime = ts->monotonic = USEC_INFINITY;
136 dual_timestamp_get(ts);
137 delta = (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u;
138 ts->realtime = usec_sub(ts->realtime, delta);
139 ts->monotonic = usec_sub(ts->monotonic, delta);
145 usec_t timespec_load(const struct timespec *ts) {
148 if (ts->tv_sec == (time_t) -1 && ts->tv_nsec == (long) -1)
149 return USEC_INFINITY;
151 if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
152 return USEC_INFINITY;
155 (usec_t) ts->tv_sec * USEC_PER_SEC +
156 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
159 #if 0 /// UNNEEDED by elogind
160 static nsec_t timespec_load_nsec(const struct timespec *ts) {
163 if (ts->tv_sec == (time_t) -1 && ts->tv_nsec == (long) -1)
164 return NSEC_INFINITY;
166 if ((nsec_t) ts->tv_sec >= (UINT64_MAX - ts->tv_nsec) / NSEC_PER_SEC)
167 return NSEC_INFINITY;
169 return (nsec_t) ts->tv_sec * NSEC_PER_SEC + (nsec_t) ts->tv_nsec;
173 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
176 if (u == USEC_INFINITY) {
177 ts->tv_sec = (time_t) -1;
178 ts->tv_nsec = (long) -1;
182 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
183 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
188 usec_t timeval_load(const struct timeval *tv) {
191 if (tv->tv_sec == (time_t) -1 &&
192 tv->tv_usec == (suseconds_t) -1)
193 return USEC_INFINITY;
195 if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
196 return USEC_INFINITY;
199 (usec_t) tv->tv_sec * USEC_PER_SEC +
200 (usec_t) tv->tv_usec;
203 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
206 if (u == USEC_INFINITY) {
207 tv->tv_sec = (time_t) -1;
208 tv->tv_usec = (suseconds_t) -1;
210 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
211 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
217 static char *format_timestamp_internal(char *buf, size_t l, usec_t t,
226 if (t <= 0 || t == USEC_INFINITY)
229 sec = (time_t) (t / USEC_PER_SEC);
230 localtime_or_gmtime_r(&sec, &tm, utc);
233 k = strftime(buf, l, "%a %Y-%m-%d %H:%M:%S", &tm);
235 k = strftime(buf, l, "%a %Y-%m-%d %H:%M:%S %Z", &tm);
240 snprintf(buf + strlen(buf), l - strlen(buf), ".%06llu", (unsigned long long) (t % USEC_PER_SEC));
241 if (strftime(buf + strlen(buf), l - strlen(buf), " %Z", &tm) <= 0)
248 char *format_timestamp(char *buf, size_t l, usec_t t) {
249 return format_timestamp_internal(buf, l, t, false, false);
252 #if 0 /// UNNEEDED by elogind
253 char *format_timestamp_utc(char *buf, size_t l, usec_t t) {
254 return format_timestamp_internal(buf, l, t, true, false);
258 char *format_timestamp_us(char *buf, size_t l, usec_t t) {
259 return format_timestamp_internal(buf, l, t, false, true);
262 #if 0 /// UNNEEDED by elogind
263 char *format_timestamp_us_utc(char *buf, size_t l, usec_t t) {
264 return format_timestamp_internal(buf, l, t, true, true);
268 char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
272 if (t <= 0 || t == USEC_INFINITY)
275 n = now(CLOCK_REALTIME);
284 if (d >= USEC_PER_YEAR)
285 snprintf(buf, l, USEC_FMT " years " USEC_FMT " months %s",
287 (d % USEC_PER_YEAR) / USEC_PER_MONTH, s);
288 else if (d >= USEC_PER_MONTH)
289 snprintf(buf, l, USEC_FMT " months " USEC_FMT " days %s",
291 (d % USEC_PER_MONTH) / USEC_PER_DAY, s);
292 else if (d >= USEC_PER_WEEK)
293 snprintf(buf, l, USEC_FMT " weeks " USEC_FMT " days %s",
295 (d % USEC_PER_WEEK) / USEC_PER_DAY, s);
296 else if (d >= 2*USEC_PER_DAY)
297 snprintf(buf, l, USEC_FMT " days %s", d / USEC_PER_DAY, s);
298 else if (d >= 25*USEC_PER_HOUR)
299 snprintf(buf, l, "1 day " USEC_FMT "h %s",
300 (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
301 else if (d >= 6*USEC_PER_HOUR)
302 snprintf(buf, l, USEC_FMT "h %s",
303 d / USEC_PER_HOUR, s);
304 else if (d >= USEC_PER_HOUR)
305 snprintf(buf, l, USEC_FMT "h " USEC_FMT "min %s",
307 (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
308 else if (d >= 5*USEC_PER_MINUTE)
309 snprintf(buf, l, USEC_FMT "min %s",
310 d / USEC_PER_MINUTE, s);
311 else if (d >= USEC_PER_MINUTE)
312 snprintf(buf, l, USEC_FMT "min " USEC_FMT "s %s",
314 (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
315 else if (d >= USEC_PER_SEC)
316 snprintf(buf, l, USEC_FMT "s %s",
317 d / USEC_PER_SEC, s);
318 else if (d >= USEC_PER_MSEC)
319 snprintf(buf, l, USEC_FMT "ms %s",
320 d / USEC_PER_MSEC, s);
322 snprintf(buf, l, USEC_FMT"us %s",
325 snprintf(buf, l, "now");
331 char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
332 static const struct {
336 { "y", USEC_PER_YEAR },
337 { "month", USEC_PER_MONTH },
338 { "w", USEC_PER_WEEK },
339 { "d", USEC_PER_DAY },
340 { "h", USEC_PER_HOUR },
341 { "min", USEC_PER_MINUTE },
342 { "s", USEC_PER_SEC },
343 { "ms", USEC_PER_MSEC },
349 bool something = false;
354 if (t == USEC_INFINITY) {
355 strncpy(p, "infinity", l-1);
361 strncpy(p, "0", l-1);
366 /* The result of this function can be parsed with parse_sec */
368 for (i = 0; i < ELEMENTSOF(table); i++) {
377 if (t < accuracy && something)
380 if (t < table[i].usec)
386 a = t / table[i].usec;
387 b = t % table[i].usec;
389 /* Let's see if we should shows this in dot notation */
390 if (t < USEC_PER_MINUTE && b > 0) {
395 for (cc = table[i].usec; cc > 1; cc /= 10)
398 for (cc = accuracy; cc > 1; cc /= 10) {
405 "%s"USEC_FMT".%0*llu%s",
409 (unsigned long long) b,
417 /* No? Then let's show it normally */
428 n = MIN((size_t) k, l);
441 #if 0 /// UNNEEDED by elogind
442 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
448 if (!dual_timestamp_is_set(t))
451 fprintf(f, "%s="USEC_FMT" "USEC_FMT"\n",
457 int dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
458 unsigned long long a, b;
463 if (sscanf(value, "%llu %llu", &a, &b) != 2) {
464 log_debug("Failed to parse dual timestamp value \"%s\": %m", value);
475 int timestamp_deserialize(const char *value, usec_t *timestamp) {
480 r = safe_atou64(value, timestamp);
482 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
487 #if 0 /// UNNEEDED by elogind
488 int parse_timestamp(const char *t, usec_t *usec) {
489 static const struct {
513 usec_t x_usec, plus = 0, minus = 0, ret;
520 * 2012-09-22 16:34:22
521 * 2012-09-22 16:34 (seconds will be set to 0)
522 * 2012-09-22 (time will be set to 00:00:00)
523 * 16:34:22 (date will be set to today)
524 * 16:34 (date will be set to today, seconds to 0)
526 * yesterday (time is set to 00:00:00)
527 * today (time is set to 00:00:00)
528 * tomorrow (time is set to 00:00:00)
531 * @2147483647 (seconds since epoch)
539 return parse_sec(t + 1, usec);
541 ret = now(CLOCK_REALTIME);
546 else if (t[0] == '+') {
547 r = parse_sec(t+1, &plus);
553 } else if (t[0] == '-') {
554 r = parse_sec(t+1, &minus);
560 } else if ((k = endswith(t, " ago"))) {
561 t = strndupa(t, k - t);
563 r = parse_sec(t, &minus);
569 } else if ((k = endswith(t, " left"))) {
570 t = strndupa(t, k - t);
572 r = parse_sec(t, &plus);
579 utc = endswith_no_case(t, " UTC");
581 t = strndupa(t, utc - t);
583 x = ret / USEC_PER_SEC;
586 assert_se(localtime_or_gmtime_r(&x, &tm, utc));
589 if (streq(t, "today")) {
590 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
593 } else if (streq(t, "yesterday")) {
595 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
598 } else if (streq(t, "tomorrow")) {
600 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
605 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
608 if (!startswith_no_case(t, day_nr[i].name))
611 skip = strlen(day_nr[i].name);
615 weekday = day_nr[i].nr;
621 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
630 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
639 k = strptime(t, "%y-%m-%d %H:%M", &tm);
646 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
653 k = strptime(t, "%y-%m-%d", &tm);
655 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
660 k = strptime(t, "%Y-%m-%d", &tm);
662 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
667 k = strptime(t, "%H:%M:%S", &tm);
676 k = strptime(t, "%H:%M", &tm);
689 r = parse_fractional_part_u(&k, 6, &add);
701 x = mktime_or_timegm(&tm, utc);
702 if (x == (time_t) -1)
705 if (weekday >= 0 && tm.tm_wday != weekday)
708 ret = (usec_t) x * USEC_PER_SEC + x_usec;
723 static char* extract_multiplier(char *p, usec_t *multiplier) {
724 static const struct {
728 { "seconds", USEC_PER_SEC },
729 { "second", USEC_PER_SEC },
730 { "sec", USEC_PER_SEC },
731 { "s", USEC_PER_SEC },
732 { "minutes", USEC_PER_MINUTE },
733 { "minute", USEC_PER_MINUTE },
734 { "min", USEC_PER_MINUTE },
735 { "months", USEC_PER_MONTH },
736 { "month", USEC_PER_MONTH },
737 { "M", USEC_PER_MONTH },
738 { "msec", USEC_PER_MSEC },
739 { "ms", USEC_PER_MSEC },
740 { "m", USEC_PER_MINUTE },
741 { "hours", USEC_PER_HOUR },
742 { "hour", USEC_PER_HOUR },
743 { "hr", USEC_PER_HOUR },
744 { "h", USEC_PER_HOUR },
745 { "days", USEC_PER_DAY },
746 { "day", USEC_PER_DAY },
747 { "d", USEC_PER_DAY },
748 { "weeks", USEC_PER_WEEK },
749 { "week", USEC_PER_WEEK },
750 { "w", USEC_PER_WEEK },
751 { "years", USEC_PER_YEAR },
752 { "year", USEC_PER_YEAR },
753 { "y", USEC_PER_YEAR },
759 for (i = 0; i < ELEMENTSOF(table); i++) {
762 e = startswith(p, table[i].suffix);
764 *multiplier = table[i].usec;
772 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
775 bool something = false;
779 assert(default_unit > 0);
783 p += strspn(p, WHITESPACE);
784 s = startswith(p, "infinity");
786 s += strspn(s, WHITESPACE);
790 *usec = USEC_INFINITY;
798 usec_t multiplier = default_unit, k;
800 p += strspn(p, WHITESPACE);
810 l = strtoll(p, &e, 10);
820 z = strtoll(b, &e, 10);
835 e += strspn(e, WHITESPACE);
836 p = extract_multiplier(e, &multiplier);
840 k = (usec_t) z * multiplier;
845 r += (usec_t) l * multiplier + k;
853 int parse_sec(const char *t, usec_t *usec) {
854 return parse_time(t, usec, USEC_PER_SEC);
857 #if 0 /// UNNEEDED by elogind
858 int parse_nsec(const char *t, nsec_t *nsec) {
859 static const struct {
863 { "seconds", NSEC_PER_SEC },
864 { "second", NSEC_PER_SEC },
865 { "sec", NSEC_PER_SEC },
866 { "s", NSEC_PER_SEC },
867 { "minutes", NSEC_PER_MINUTE },
868 { "minute", NSEC_PER_MINUTE },
869 { "min", NSEC_PER_MINUTE },
870 { "months", NSEC_PER_MONTH },
871 { "month", NSEC_PER_MONTH },
872 { "msec", NSEC_PER_MSEC },
873 { "ms", NSEC_PER_MSEC },
874 { "m", NSEC_PER_MINUTE },
875 { "hours", NSEC_PER_HOUR },
876 { "hour", NSEC_PER_HOUR },
877 { "hr", NSEC_PER_HOUR },
878 { "h", NSEC_PER_HOUR },
879 { "days", NSEC_PER_DAY },
880 { "day", NSEC_PER_DAY },
881 { "d", NSEC_PER_DAY },
882 { "weeks", NSEC_PER_WEEK },
883 { "week", NSEC_PER_WEEK },
884 { "w", NSEC_PER_WEEK },
885 { "years", NSEC_PER_YEAR },
886 { "year", NSEC_PER_YEAR },
887 { "y", NSEC_PER_YEAR },
888 { "usec", NSEC_PER_USEC },
889 { "us", NSEC_PER_USEC },
892 { "", 1ULL }, /* default is nsec */
897 bool something = false;
904 p += strspn(p, WHITESPACE);
905 s = startswith(p, "infinity");
907 s += strspn(s, WHITESPACE);
911 *nsec = NSEC_INFINITY;
920 p += strspn(p, WHITESPACE);
930 l = strtoll(p, &e, 10);
942 z = strtoll(b, &e, 10);
957 e += strspn(e, WHITESPACE);
959 for (i = 0; i < ELEMENTSOF(table); i++)
960 if (startswith(e, table[i].suffix)) {
961 nsec_t k = (nsec_t) z * table[i].nsec;
966 r += (nsec_t) l * table[i].nsec + k;
967 p = e + strlen(table[i].suffix);
973 if (i >= ELEMENTSOF(table))
983 bool ntp_synced(void) {
984 struct timex txc = {};
986 if (adjtimex(&txc) < 0)
989 if (txc.status & STA_UNSYNC)
995 int get_timezones(char ***ret) {
996 _cleanup_fclose_ FILE *f = NULL;
997 _cleanup_strv_free_ char **zones = NULL;
998 size_t n_zones = 0, n_allocated = 0;
1002 zones = strv_new("UTC", NULL);
1009 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1013 FOREACH_LINE(l, f, return -errno) {
1019 if (isempty(p) || *p == '#')
1022 /* Skip over country code */
1023 p += strcspn(p, WHITESPACE);
1024 p += strspn(p, WHITESPACE);
1026 /* Skip over coordinates */
1027 p += strcspn(p, WHITESPACE);
1028 p += strspn(p, WHITESPACE);
1030 /* Found timezone name */
1031 k = strcspn(p, WHITESPACE);
1039 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1044 zones[n_zones++] = w;
1045 zones[n_zones] = NULL;
1050 } else if (errno != ENOENT)
1059 bool timezone_is_valid(const char *name) {
1070 for (p = name; *p; p++) {
1071 if (!(*p >= '0' && *p <= '9') &&
1072 !(*p >= 'a' && *p <= 'z') &&
1073 !(*p >= 'A' && *p <= 'Z') &&
1074 !(*p == '-' || *p == '_' || *p == '+' || *p == '/'))
1090 t = strjoina("/usr/share/zoneinfo/", name);
1091 if (stat(t, &st) < 0)
1094 if (!S_ISREG(st.st_mode))
1101 bool clock_boottime_supported(void) {
1102 static int supported = -1;
1104 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1106 if (supported < 0) {
1109 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1121 #if 0 /// UNNEEDED by elogind
1122 clockid_t clock_boottime_or_monotonic(void) {
1123 if (clock_boottime_supported())
1124 return CLOCK_BOOTTIME;
1126 return CLOCK_MONOTONIC;
1129 int get_timezone(char **tz) {
1130 _cleanup_free_ char *t = NULL;
1135 r = readlink_malloc("/etc/localtime", &t);
1137 return r; /* returns EINVAL if not a symlink */
1139 e = path_startswith(t, "/usr/share/zoneinfo/");
1141 e = path_startswith(t, "../usr/share/zoneinfo/");
1145 if (!timezone_is_valid(e))
1156 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1157 return utc ? timegm(tm) : mktime(tm);
1161 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1162 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1165 #if 0 /// UNNEEDED by elogind
1166 unsigned long usec_to_jiffies(usec_t u) {
1167 static thread_local unsigned long hz = 0;
1171 r = sysconf(_SC_CLK_TCK);
1174 hz = (unsigned long) r;
1177 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);