]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/time-util.c
pkgconfig: define variables relative to ${prefix}/${rootprefix}/${sysconfdir}
[thirdparty/systemd.git] / src / basic / time-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <ctype.h>
4 #include <errno.h>
5 #include <limits.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <sys/mman.h>
9 #include <sys/stat.h>
10 #include <sys/time.h>
11 #include <sys/timerfd.h>
12 #include <sys/timex.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15
16 #include "alloc-util.h"
17 #include "fd-util.h"
18 #include "fileio.h"
19 #include "fs-util.h"
20 #include "io-util.h"
21 #include "log.h"
22 #include "macro.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "process-util.h"
26 #include "serialize.h"
27 #include "stat-util.h"
28 #include "string-util.h"
29 #include "strv.h"
30 #include "time-util.h"
31
32 static clockid_t map_clock_id(clockid_t c) {
33
34 /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus, clock_gettime() will
35 * fail for them. Since they are essentially the same as their non-ALARM pendants (their only difference is
36 * when timers are set on them), let's just map them accordingly. This way, we can get the correct time even on
37 * those archs. */
38
39 switch (c) {
40
41 case CLOCK_BOOTTIME_ALARM:
42 return CLOCK_BOOTTIME;
43
44 case CLOCK_REALTIME_ALARM:
45 return CLOCK_REALTIME;
46
47 default:
48 return c;
49 }
50 }
51
52 usec_t now(clockid_t clock_id) {
53 struct timespec ts;
54
55 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
56
57 return timespec_load(&ts);
58 }
59
60 nsec_t now_nsec(clockid_t clock_id) {
61 struct timespec ts;
62
63 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
64
65 return timespec_load_nsec(&ts);
66 }
67
68 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
69 assert(ts);
70
71 ts->realtime = now(CLOCK_REALTIME);
72 ts->monotonic = now(CLOCK_MONOTONIC);
73
74 return ts;
75 }
76
77 triple_timestamp* triple_timestamp_get(triple_timestamp *ts) {
78 assert(ts);
79
80 ts->realtime = now(CLOCK_REALTIME);
81 ts->monotonic = now(CLOCK_MONOTONIC);
82 ts->boottime = clock_boottime_supported() ? now(CLOCK_BOOTTIME) : USEC_INFINITY;
83
84 return ts;
85 }
86
87 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
88 int64_t delta;
89 assert(ts);
90
91 if (u == USEC_INFINITY || u <= 0) {
92 ts->realtime = ts->monotonic = u;
93 return ts;
94 }
95
96 ts->realtime = u;
97
98 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
99 ts->monotonic = usec_sub_signed(now(CLOCK_MONOTONIC), delta);
100
101 return ts;
102 }
103
104 triple_timestamp* triple_timestamp_from_realtime(triple_timestamp *ts, usec_t u) {
105 int64_t delta;
106
107 assert(ts);
108
109 if (u == USEC_INFINITY || u <= 0) {
110 ts->realtime = ts->monotonic = ts->boottime = u;
111 return ts;
112 }
113
114 ts->realtime = u;
115 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
116 ts->monotonic = usec_sub_signed(now(CLOCK_MONOTONIC), delta);
117 ts->boottime = clock_boottime_supported() ? usec_sub_signed(now(CLOCK_BOOTTIME), delta) : USEC_INFINITY;
118
119 return ts;
120 }
121
122 dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
123 int64_t delta;
124 assert(ts);
125
126 if (u == USEC_INFINITY) {
127 ts->realtime = ts->monotonic = USEC_INFINITY;
128 return ts;
129 }
130
131 ts->monotonic = u;
132 delta = (int64_t) now(CLOCK_MONOTONIC) - (int64_t) u;
133 ts->realtime = usec_sub_signed(now(CLOCK_REALTIME), delta);
134
135 return ts;
136 }
137
138 dual_timestamp* dual_timestamp_from_boottime_or_monotonic(dual_timestamp *ts, usec_t u) {
139 int64_t delta;
140
141 if (u == USEC_INFINITY) {
142 ts->realtime = ts->monotonic = USEC_INFINITY;
143 return ts;
144 }
145
146 dual_timestamp_get(ts);
147 delta = (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u;
148 ts->realtime = usec_sub_signed(ts->realtime, delta);
149 ts->monotonic = usec_sub_signed(ts->monotonic, delta);
150
151 return ts;
152 }
153
154 usec_t triple_timestamp_by_clock(triple_timestamp *ts, clockid_t clock) {
155
156 switch (clock) {
157
158 case CLOCK_REALTIME:
159 case CLOCK_REALTIME_ALARM:
160 return ts->realtime;
161
162 case CLOCK_MONOTONIC:
163 return ts->monotonic;
164
165 case CLOCK_BOOTTIME:
166 case CLOCK_BOOTTIME_ALARM:
167 return ts->boottime;
168
169 default:
170 return USEC_INFINITY;
171 }
172 }
173
174 usec_t timespec_load(const struct timespec *ts) {
175 assert(ts);
176
177 if (ts->tv_sec < 0 || ts->tv_nsec < 0)
178 return USEC_INFINITY;
179
180 if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
181 return USEC_INFINITY;
182
183 return
184 (usec_t) ts->tv_sec * USEC_PER_SEC +
185 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
186 }
187
188 nsec_t timespec_load_nsec(const struct timespec *ts) {
189 assert(ts);
190
191 if (ts->tv_sec < 0 || ts->tv_nsec < 0)
192 return NSEC_INFINITY;
193
194 if ((nsec_t) ts->tv_sec >= (UINT64_MAX - ts->tv_nsec) / NSEC_PER_SEC)
195 return NSEC_INFINITY;
196
197 return (nsec_t) ts->tv_sec * NSEC_PER_SEC + (nsec_t) ts->tv_nsec;
198 }
199
200 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
201 assert(ts);
202
203 if (u == USEC_INFINITY ||
204 u / USEC_PER_SEC >= TIME_T_MAX) {
205 ts->tv_sec = (time_t) -1;
206 ts->tv_nsec = (long) -1;
207 return ts;
208 }
209
210 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
211 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
212
213 return ts;
214 }
215
216 usec_t timeval_load(const struct timeval *tv) {
217 assert(tv);
218
219 if (tv->tv_sec < 0 || tv->tv_usec < 0)
220 return USEC_INFINITY;
221
222 if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
223 return USEC_INFINITY;
224
225 return
226 (usec_t) tv->tv_sec * USEC_PER_SEC +
227 (usec_t) tv->tv_usec;
228 }
229
230 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
231 assert(tv);
232
233 if (u == USEC_INFINITY ||
234 u / USEC_PER_SEC > TIME_T_MAX) {
235 tv->tv_sec = (time_t) -1;
236 tv->tv_usec = (suseconds_t) -1;
237 } else {
238 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
239 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
240 }
241
242 return tv;
243 }
244
245 static char *format_timestamp_internal(
246 char *buf,
247 size_t l,
248 usec_t t,
249 bool utc,
250 bool us) {
251
252 /* The weekdays in non-localized (English) form. We use this instead of the localized form, so that our
253 * generated timestamps may be parsed with parse_timestamp(), and always read the same. */
254 static const char * const weekdays[] = {
255 [0] = "Sun",
256 [1] = "Mon",
257 [2] = "Tue",
258 [3] = "Wed",
259 [4] = "Thu",
260 [5] = "Fri",
261 [6] = "Sat",
262 };
263
264 struct tm tm;
265 time_t sec;
266 size_t n;
267
268 assert(buf);
269
270 if (l <
271 3 + /* week day */
272 1 + 10 + /* space and date */
273 1 + 8 + /* space and time */
274 (us ? 1 + 6 : 0) + /* "." and microsecond part */
275 1 + 1 + /* space and shortest possible zone */
276 1)
277 return NULL; /* Not enough space even for the shortest form. */
278 if (t <= 0 || t == USEC_INFINITY)
279 return NULL; /* Timestamp is unset */
280
281 /* Let's not format times with years > 9999 */
282 if (t > USEC_TIMESTAMP_FORMATTABLE_MAX) {
283 assert(l >= STRLEN("--- XXXX-XX-XX XX:XX:XX") + 1);
284 strcpy(buf, "--- XXXX-XX-XX XX:XX:XX");
285 return buf;
286 }
287
288 sec = (time_t) (t / USEC_PER_SEC); /* Round down */
289
290 if (!localtime_or_gmtime_r(&sec, &tm, utc))
291 return NULL;
292
293 /* Start with the week day */
294 assert((size_t) tm.tm_wday < ELEMENTSOF(weekdays));
295 memcpy(buf, weekdays[tm.tm_wday], 4);
296
297 /* Add the main components */
298 if (strftime(buf + 3, l - 3, " %Y-%m-%d %H:%M:%S", &tm) <= 0)
299 return NULL; /* Doesn't fit */
300
301 /* Append the microseconds part, if that's requested */
302 if (us) {
303 n = strlen(buf);
304 if (n + 8 > l)
305 return NULL; /* Microseconds part doesn't fit. */
306
307 sprintf(buf + n, ".%06"PRI_USEC, t % USEC_PER_SEC);
308 }
309
310 /* Append the timezone */
311 n = strlen(buf);
312 if (utc) {
313 /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r() normally uses the
314 * obsolete "GMT" instead. */
315 if (n + 5 > l)
316 return NULL; /* "UTC" doesn't fit. */
317
318 strcpy(buf + n, " UTC");
319
320 } else if (!isempty(tm.tm_zone)) {
321 size_t tn;
322
323 /* An explicit timezone is specified, let's use it, if it fits */
324 tn = strlen(tm.tm_zone);
325 if (n + 1 + tn + 1 > l) {
326 /* The full time zone does not fit in. Yuck. */
327
328 if (n + 1 + _POSIX_TZNAME_MAX + 1 > l)
329 return NULL; /* Not even enough space for the POSIX minimum (of 6)? In that case, complain that it doesn't fit */
330
331 /* So the time zone doesn't fit in fully, but the caller passed enough space for the POSIX
332 * minimum time zone length. In this case suppress the timezone entirely, in order not to dump
333 * an overly long, hard to read string on the user. This should be safe, because the user will
334 * assume the local timezone anyway if none is shown. And so does parse_timestamp(). */
335 } else {
336 buf[n++] = ' ';
337 strcpy(buf + n, tm.tm_zone);
338 }
339 }
340
341 return buf;
342 }
343
344 char *format_timestamp(char *buf, size_t l, usec_t t) {
345 return format_timestamp_internal(buf, l, t, false, false);
346 }
347
348 char *format_timestamp_utc(char *buf, size_t l, usec_t t) {
349 return format_timestamp_internal(buf, l, t, true, false);
350 }
351
352 char *format_timestamp_us(char *buf, size_t l, usec_t t) {
353 return format_timestamp_internal(buf, l, t, false, true);
354 }
355
356 char *format_timestamp_us_utc(char *buf, size_t l, usec_t t) {
357 return format_timestamp_internal(buf, l, t, true, true);
358 }
359
360 char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
361 const char *s;
362 usec_t n, d;
363
364 if (t <= 0 || t == USEC_INFINITY)
365 return NULL;
366
367 n = now(CLOCK_REALTIME);
368 if (n > t) {
369 d = n - t;
370 s = "ago";
371 } else {
372 d = t - n;
373 s = "left";
374 }
375
376 if (d >= USEC_PER_YEAR)
377 snprintf(buf, l, USEC_FMT " years " USEC_FMT " months %s",
378 d / USEC_PER_YEAR,
379 (d % USEC_PER_YEAR) / USEC_PER_MONTH, s);
380 else if (d >= USEC_PER_MONTH)
381 snprintf(buf, l, USEC_FMT " months " USEC_FMT " days %s",
382 d / USEC_PER_MONTH,
383 (d % USEC_PER_MONTH) / USEC_PER_DAY, s);
384 else if (d >= USEC_PER_WEEK)
385 snprintf(buf, l, USEC_FMT " weeks " USEC_FMT " days %s",
386 d / USEC_PER_WEEK,
387 (d % USEC_PER_WEEK) / USEC_PER_DAY, s);
388 else if (d >= 2*USEC_PER_DAY)
389 snprintf(buf, l, USEC_FMT " days %s", d / USEC_PER_DAY, s);
390 else if (d >= 25*USEC_PER_HOUR)
391 snprintf(buf, l, "1 day " USEC_FMT "h %s",
392 (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
393 else if (d >= 6*USEC_PER_HOUR)
394 snprintf(buf, l, USEC_FMT "h %s",
395 d / USEC_PER_HOUR, s);
396 else if (d >= USEC_PER_HOUR)
397 snprintf(buf, l, USEC_FMT "h " USEC_FMT "min %s",
398 d / USEC_PER_HOUR,
399 (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
400 else if (d >= 5*USEC_PER_MINUTE)
401 snprintf(buf, l, USEC_FMT "min %s",
402 d / USEC_PER_MINUTE, s);
403 else if (d >= USEC_PER_MINUTE)
404 snprintf(buf, l, USEC_FMT "min " USEC_FMT "s %s",
405 d / USEC_PER_MINUTE,
406 (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
407 else if (d >= USEC_PER_SEC)
408 snprintf(buf, l, USEC_FMT "s %s",
409 d / USEC_PER_SEC, s);
410 else if (d >= USEC_PER_MSEC)
411 snprintf(buf, l, USEC_FMT "ms %s",
412 d / USEC_PER_MSEC, s);
413 else if (d > 0)
414 snprintf(buf, l, USEC_FMT"us %s",
415 d, s);
416 else
417 snprintf(buf, l, "now");
418
419 buf[l-1] = 0;
420 return buf;
421 }
422
423 char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
424 static const struct {
425 const char *suffix;
426 usec_t usec;
427 } table[] = {
428 { "y", USEC_PER_YEAR },
429 { "month", USEC_PER_MONTH },
430 { "w", USEC_PER_WEEK },
431 { "d", USEC_PER_DAY },
432 { "h", USEC_PER_HOUR },
433 { "min", USEC_PER_MINUTE },
434 { "s", USEC_PER_SEC },
435 { "ms", USEC_PER_MSEC },
436 { "us", 1 },
437 };
438
439 size_t i;
440 char *p = buf;
441 bool something = false;
442
443 assert(buf);
444 assert(l > 0);
445
446 if (t == USEC_INFINITY) {
447 strncpy(p, "infinity", l-1);
448 p[l-1] = 0;
449 return p;
450 }
451
452 if (t <= 0) {
453 strncpy(p, "0", l-1);
454 p[l-1] = 0;
455 return p;
456 }
457
458 /* The result of this function can be parsed with parse_sec */
459
460 for (i = 0; i < ELEMENTSOF(table); i++) {
461 int k = 0;
462 size_t n;
463 bool done = false;
464 usec_t a, b;
465
466 if (t <= 0)
467 break;
468
469 if (t < accuracy && something)
470 break;
471
472 if (t < table[i].usec)
473 continue;
474
475 if (l <= 1)
476 break;
477
478 a = t / table[i].usec;
479 b = t % table[i].usec;
480
481 /* Let's see if we should shows this in dot notation */
482 if (t < USEC_PER_MINUTE && b > 0) {
483 usec_t cc;
484 signed char j;
485
486 j = 0;
487 for (cc = table[i].usec; cc > 1; cc /= 10)
488 j++;
489
490 for (cc = accuracy; cc > 1; cc /= 10) {
491 b /= 10;
492 j--;
493 }
494
495 if (j > 0) {
496 k = snprintf(p, l,
497 "%s"USEC_FMT".%0*"PRI_USEC"%s",
498 p > buf ? " " : "",
499 a,
500 j,
501 b,
502 table[i].suffix);
503
504 t = 0;
505 done = true;
506 }
507 }
508
509 /* No? Then let's show it normally */
510 if (!done) {
511 k = snprintf(p, l,
512 "%s"USEC_FMT"%s",
513 p > buf ? " " : "",
514 a,
515 table[i].suffix);
516
517 t = b;
518 }
519
520 n = MIN((size_t) k, l);
521
522 l -= n;
523 p += n;
524
525 something = true;
526 }
527
528 *p = 0;
529
530 return buf;
531 }
532
533 static int parse_timestamp_impl(const char *t, usec_t *usec, bool with_tz) {
534 static const struct {
535 const char *name;
536 const int nr;
537 } day_nr[] = {
538 { "Sunday", 0 },
539 { "Sun", 0 },
540 { "Monday", 1 },
541 { "Mon", 1 },
542 { "Tuesday", 2 },
543 { "Tue", 2 },
544 { "Wednesday", 3 },
545 { "Wed", 3 },
546 { "Thursday", 4 },
547 { "Thu", 4 },
548 { "Friday", 5 },
549 { "Fri", 5 },
550 { "Saturday", 6 },
551 { "Sat", 6 },
552 };
553
554 const char *k, *utc = NULL, *tzn = NULL;
555 struct tm tm, copy;
556 time_t x;
557 usec_t x_usec, plus = 0, minus = 0, ret;
558 int r, weekday = -1, dst = -1;
559 size_t i;
560
561 /* Allowed syntaxes:
562 *
563 * 2012-09-22 16:34:22
564 * 2012-09-22 16:34 (seconds will be set to 0)
565 * 2012-09-22 (time will be set to 00:00:00)
566 * 16:34:22 (date will be set to today)
567 * 16:34 (date will be set to today, seconds to 0)
568 * now
569 * yesterday (time is set to 00:00:00)
570 * today (time is set to 00:00:00)
571 * tomorrow (time is set to 00:00:00)
572 * +5min
573 * -5days
574 * @2147483647 (seconds since epoch)
575 */
576
577 assert(t);
578 assert(usec);
579
580 if (t[0] == '@' && !with_tz)
581 return parse_sec(t + 1, usec);
582
583 ret = now(CLOCK_REALTIME);
584
585 if (!with_tz) {
586 if (streq(t, "now"))
587 goto finish;
588
589 else if (t[0] == '+') {
590 r = parse_sec(t+1, &plus);
591 if (r < 0)
592 return r;
593
594 goto finish;
595
596 } else if (t[0] == '-') {
597 r = parse_sec(t+1, &minus);
598 if (r < 0)
599 return r;
600
601 goto finish;
602
603 } else if ((k = endswith(t, " ago"))) {
604 t = strndupa(t, k - t);
605
606 r = parse_sec(t, &minus);
607 if (r < 0)
608 return r;
609
610 goto finish;
611
612 } else if ((k = endswith(t, " left"))) {
613 t = strndupa(t, k - t);
614
615 r = parse_sec(t, &plus);
616 if (r < 0)
617 return r;
618
619 goto finish;
620 }
621
622 /* See if the timestamp is suffixed with UTC */
623 utc = endswith_no_case(t, " UTC");
624 if (utc)
625 t = strndupa(t, utc - t);
626 else {
627 const char *e = NULL;
628 int j;
629
630 tzset();
631
632 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
633 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
634 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
635 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
636 * support arbitrary timezone specifications. */
637
638 for (j = 0; j <= 1; j++) {
639
640 if (isempty(tzname[j]))
641 continue;
642
643 e = endswith_no_case(t, tzname[j]);
644 if (!e)
645 continue;
646 if (e == t)
647 continue;
648 if (e[-1] != ' ')
649 continue;
650
651 break;
652 }
653
654 if (IN_SET(j, 0, 1)) {
655 /* Found one of the two timezones specified. */
656 t = strndupa(t, e - t - 1);
657 dst = j;
658 tzn = tzname[j];
659 }
660 }
661 }
662
663 x = (time_t) (ret / USEC_PER_SEC);
664 x_usec = 0;
665
666 if (!localtime_or_gmtime_r(&x, &tm, utc))
667 return -EINVAL;
668
669 tm.tm_isdst = dst;
670 if (!with_tz && tzn)
671 tm.tm_zone = tzn;
672
673 if (streq(t, "today")) {
674 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
675 goto from_tm;
676
677 } else if (streq(t, "yesterday")) {
678 tm.tm_mday--;
679 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
680 goto from_tm;
681
682 } else if (streq(t, "tomorrow")) {
683 tm.tm_mday++;
684 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
685 goto from_tm;
686 }
687
688 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
689 size_t skip;
690
691 if (!startswith_no_case(t, day_nr[i].name))
692 continue;
693
694 skip = strlen(day_nr[i].name);
695 if (t[skip] != ' ')
696 continue;
697
698 weekday = day_nr[i].nr;
699 t += skip + 1;
700 break;
701 }
702
703 copy = tm;
704 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
705 if (k) {
706 if (*k == '.')
707 goto parse_usec;
708 else if (*k == 0)
709 goto from_tm;
710 }
711
712 tm = copy;
713 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
714 if (k) {
715 if (*k == '.')
716 goto parse_usec;
717 else if (*k == 0)
718 goto from_tm;
719 }
720
721 tm = copy;
722 k = strptime(t, "%y-%m-%d %H:%M", &tm);
723 if (k && *k == 0) {
724 tm.tm_sec = 0;
725 goto from_tm;
726 }
727
728 tm = copy;
729 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
730 if (k && *k == 0) {
731 tm.tm_sec = 0;
732 goto from_tm;
733 }
734
735 tm = copy;
736 k = strptime(t, "%y-%m-%d", &tm);
737 if (k && *k == 0) {
738 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
739 goto from_tm;
740 }
741
742 tm = copy;
743 k = strptime(t, "%Y-%m-%d", &tm);
744 if (k && *k == 0) {
745 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
746 goto from_tm;
747 }
748
749 tm = copy;
750 k = strptime(t, "%H:%M:%S", &tm);
751 if (k) {
752 if (*k == '.')
753 goto parse_usec;
754 else if (*k == 0)
755 goto from_tm;
756 }
757
758 tm = copy;
759 k = strptime(t, "%H:%M", &tm);
760 if (k && *k == 0) {
761 tm.tm_sec = 0;
762 goto from_tm;
763 }
764
765 return -EINVAL;
766
767 parse_usec:
768 {
769 unsigned add;
770
771 k++;
772 r = parse_fractional_part_u(&k, 6, &add);
773 if (r < 0)
774 return -EINVAL;
775
776 if (*k)
777 return -EINVAL;
778
779 x_usec = add;
780 }
781
782 from_tm:
783 if (weekday >= 0 && tm.tm_wday != weekday)
784 return -EINVAL;
785
786 x = mktime_or_timegm(&tm, utc);
787 if (x < 0)
788 return -EINVAL;
789
790 ret = (usec_t) x * USEC_PER_SEC + x_usec;
791 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
792 return -EINVAL;
793
794 finish:
795 if (ret + plus < ret) /* overflow? */
796 return -EINVAL;
797 ret += plus;
798 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
799 return -EINVAL;
800
801 if (ret >= minus)
802 ret -= minus;
803 else
804 return -EINVAL;
805
806 *usec = ret;
807
808 return 0;
809 }
810
811 typedef struct ParseTimestampResult {
812 usec_t usec;
813 int return_value;
814 } ParseTimestampResult;
815
816 int parse_timestamp(const char *t, usec_t *usec) {
817 char *last_space, *tz = NULL;
818 ParseTimestampResult *shared, tmp;
819 int r;
820
821 last_space = strrchr(t, ' ');
822 if (last_space != NULL && timezone_is_valid(last_space + 1, LOG_DEBUG))
823 tz = last_space + 1;
824
825 if (!tz || endswith_no_case(t, " UTC"))
826 return parse_timestamp_impl(t, usec, false);
827
828 shared = mmap(NULL, sizeof *shared, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
829 if (shared == MAP_FAILED)
830 return negative_errno();
831
832 r = safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_WAIT, NULL);
833 if (r < 0) {
834 (void) munmap(shared, sizeof *shared);
835 return r;
836 }
837 if (r == 0) {
838 bool with_tz = true;
839
840 if (setenv("TZ", tz, 1) != 0) {
841 shared->return_value = negative_errno();
842 _exit(EXIT_FAILURE);
843 }
844
845 tzset();
846
847 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
848 * Otherwise just cut it off. */
849 with_tz = !STR_IN_SET(tz, tzname[0], tzname[1]);
850
851 /* Cut off the timezone if we don't need it. */
852 if (with_tz)
853 t = strndupa(t, last_space - t);
854
855 shared->return_value = parse_timestamp_impl(t, &shared->usec, with_tz);
856
857 _exit(EXIT_SUCCESS);
858 }
859
860 tmp = *shared;
861 if (munmap(shared, sizeof *shared) != 0)
862 return negative_errno();
863
864 if (tmp.return_value == 0)
865 *usec = tmp.usec;
866
867 return tmp.return_value;
868 }
869
870 static const char* extract_multiplier(const char *p, usec_t *multiplier) {
871 static const struct {
872 const char *suffix;
873 usec_t usec;
874 } table[] = {
875 { "seconds", USEC_PER_SEC },
876 { "second", USEC_PER_SEC },
877 { "sec", USEC_PER_SEC },
878 { "s", USEC_PER_SEC },
879 { "minutes", USEC_PER_MINUTE },
880 { "minute", USEC_PER_MINUTE },
881 { "min", USEC_PER_MINUTE },
882 { "months", USEC_PER_MONTH },
883 { "month", USEC_PER_MONTH },
884 { "M", USEC_PER_MONTH },
885 { "msec", USEC_PER_MSEC },
886 { "ms", USEC_PER_MSEC },
887 { "m", USEC_PER_MINUTE },
888 { "hours", USEC_PER_HOUR },
889 { "hour", USEC_PER_HOUR },
890 { "hr", USEC_PER_HOUR },
891 { "h", USEC_PER_HOUR },
892 { "days", USEC_PER_DAY },
893 { "day", USEC_PER_DAY },
894 { "d", USEC_PER_DAY },
895 { "weeks", USEC_PER_WEEK },
896 { "week", USEC_PER_WEEK },
897 { "w", USEC_PER_WEEK },
898 { "years", USEC_PER_YEAR },
899 { "year", USEC_PER_YEAR },
900 { "y", USEC_PER_YEAR },
901 { "usec", 1ULL },
902 { "us", 1ULL },
903 { "µs", 1ULL },
904 };
905 size_t i;
906
907 for (i = 0; i < ELEMENTSOF(table); i++) {
908 char *e;
909
910 e = startswith(p, table[i].suffix);
911 if (e) {
912 *multiplier = table[i].usec;
913 return e;
914 }
915 }
916
917 return p;
918 }
919
920 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
921 const char *p, *s;
922 usec_t r = 0;
923 bool something = false;
924
925 assert(t);
926 assert(usec);
927 assert(default_unit > 0);
928
929 p = t;
930
931 p += strspn(p, WHITESPACE);
932 s = startswith(p, "infinity");
933 if (s) {
934 s += strspn(s, WHITESPACE);
935 if (*s != 0)
936 return -EINVAL;
937
938 *usec = USEC_INFINITY;
939 return 0;
940 }
941
942 for (;;) {
943 usec_t multiplier = default_unit, k;
944 long long l;
945 char *e;
946
947 p += strspn(p, WHITESPACE);
948
949 if (*p == 0) {
950 if (!something)
951 return -EINVAL;
952
953 break;
954 }
955
956 if (*p == '-') /* Don't allow "-0" */
957 return -ERANGE;
958
959 errno = 0;
960 l = strtoll(p, &e, 10);
961 if (errno > 0)
962 return -errno;
963 if (l < 0)
964 return -ERANGE;
965
966 if (*e == '.') {
967 p = e + 1;
968 p += strspn(p, DIGITS);
969 } else if (e == p)
970 return -EINVAL;
971 else
972 p = e;
973
974 s = extract_multiplier(p + strspn(p, WHITESPACE), &multiplier);
975 if (s == p && *s != '\0')
976 /* Don't allow '12.34.56', but accept '12.34 .56' or '12.34s.56'*/
977 return -EINVAL;
978
979 p = s;
980
981 if ((usec_t) l >= USEC_INFINITY / multiplier)
982 return -ERANGE;
983
984 k = (usec_t) l * multiplier;
985 if (k >= USEC_INFINITY - r)
986 return -ERANGE;
987
988 r += k;
989
990 something = true;
991
992 if (*e == '.') {
993 usec_t m = multiplier / 10;
994 const char *b;
995
996 for (b = e + 1; *b >= '0' && *b <= '9'; b++, m /= 10) {
997 k = (usec_t) (*b - '0') * m;
998 if (k >= USEC_INFINITY - r)
999 return -ERANGE;
1000
1001 r += k;
1002 }
1003
1004 /* Don't allow "0.-0", "3.+1", "3. 1", "3.sec" or "3.hoge"*/
1005 if (b == e + 1)
1006 return -EINVAL;
1007 }
1008 }
1009
1010 *usec = r;
1011
1012 return 0;
1013 }
1014
1015 int parse_sec(const char *t, usec_t *usec) {
1016 return parse_time(t, usec, USEC_PER_SEC);
1017 }
1018
1019 int parse_sec_fix_0(const char *t, usec_t *ret) {
1020 usec_t k;
1021 int r;
1022
1023 assert(t);
1024 assert(ret);
1025
1026 r = parse_sec(t, &k);
1027 if (r < 0)
1028 return r;
1029
1030 *ret = k == 0 ? USEC_INFINITY : k;
1031 return r;
1032 }
1033
1034 static const char* extract_nsec_multiplier(const char *p, nsec_t *multiplier) {
1035 static const struct {
1036 const char *suffix;
1037 nsec_t nsec;
1038 } table[] = {
1039 { "seconds", NSEC_PER_SEC },
1040 { "second", NSEC_PER_SEC },
1041 { "sec", NSEC_PER_SEC },
1042 { "s", NSEC_PER_SEC },
1043 { "minutes", NSEC_PER_MINUTE },
1044 { "minute", NSEC_PER_MINUTE },
1045 { "min", NSEC_PER_MINUTE },
1046 { "months", NSEC_PER_MONTH },
1047 { "month", NSEC_PER_MONTH },
1048 { "M", NSEC_PER_MONTH },
1049 { "msec", NSEC_PER_MSEC },
1050 { "ms", NSEC_PER_MSEC },
1051 { "m", NSEC_PER_MINUTE },
1052 { "hours", NSEC_PER_HOUR },
1053 { "hour", NSEC_PER_HOUR },
1054 { "hr", NSEC_PER_HOUR },
1055 { "h", NSEC_PER_HOUR },
1056 { "days", NSEC_PER_DAY },
1057 { "day", NSEC_PER_DAY },
1058 { "d", NSEC_PER_DAY },
1059 { "weeks", NSEC_PER_WEEK },
1060 { "week", NSEC_PER_WEEK },
1061 { "w", NSEC_PER_WEEK },
1062 { "years", NSEC_PER_YEAR },
1063 { "year", NSEC_PER_YEAR },
1064 { "y", NSEC_PER_YEAR },
1065 { "usec", NSEC_PER_USEC },
1066 { "us", NSEC_PER_USEC },
1067 { "µs", NSEC_PER_USEC },
1068 { "nsec", 1ULL },
1069 { "ns", 1ULL },
1070 { "", 1ULL }, /* default is nsec */
1071 };
1072 size_t i;
1073
1074 for (i = 0; i < ELEMENTSOF(table); i++) {
1075 char *e;
1076
1077 e = startswith(p, table[i].suffix);
1078 if (e) {
1079 *multiplier = table[i].nsec;
1080 return e;
1081 }
1082 }
1083
1084 return p;
1085 }
1086
1087 int parse_nsec(const char *t, nsec_t *nsec) {
1088 const char *p, *s;
1089 nsec_t r = 0;
1090 bool something = false;
1091
1092 assert(t);
1093 assert(nsec);
1094
1095 p = t;
1096
1097 p += strspn(p, WHITESPACE);
1098 s = startswith(p, "infinity");
1099 if (s) {
1100 s += strspn(s, WHITESPACE);
1101 if (*s != 0)
1102 return -EINVAL;
1103
1104 *nsec = NSEC_INFINITY;
1105 return 0;
1106 }
1107
1108 for (;;) {
1109 nsec_t multiplier = 1, k;
1110 long long l;
1111 char *e;
1112
1113 p += strspn(p, WHITESPACE);
1114
1115 if (*p == 0) {
1116 if (!something)
1117 return -EINVAL;
1118
1119 break;
1120 }
1121
1122 if (*p == '-') /* Don't allow "-0" */
1123 return -ERANGE;
1124
1125 errno = 0;
1126 l = strtoll(p, &e, 10);
1127 if (errno > 0)
1128 return -errno;
1129 if (l < 0)
1130 return -ERANGE;
1131
1132 if (*e == '.') {
1133 p = e + 1;
1134 p += strspn(p, DIGITS);
1135 } else if (e == p)
1136 return -EINVAL;
1137 else
1138 p = e;
1139
1140 s = extract_nsec_multiplier(p + strspn(p, WHITESPACE), &multiplier);
1141 if (s == p && *s != '\0')
1142 /* Don't allow '12.34.56', but accept '12.34 .56' or '12.34s.56'*/
1143 return -EINVAL;
1144
1145 p = s;
1146
1147 if ((nsec_t) l >= NSEC_INFINITY / multiplier)
1148 return -ERANGE;
1149
1150 k = (nsec_t) l * multiplier;
1151 if (k >= NSEC_INFINITY - r)
1152 return -ERANGE;
1153
1154 r += k;
1155
1156 something = true;
1157
1158 if (*e == '.') {
1159 nsec_t m = multiplier / 10;
1160 const char *b;
1161
1162 for (b = e + 1; *b >= '0' && *b <= '9'; b++, m /= 10) {
1163 k = (nsec_t) (*b - '0') * m;
1164 if (k >= NSEC_INFINITY - r)
1165 return -ERANGE;
1166
1167 r += k;
1168 }
1169
1170 /* Don't allow "0.-0", "3.+1", "3. 1", "3.sec" or "3.hoge"*/
1171 if (b == e + 1)
1172 return -EINVAL;
1173 }
1174 }
1175
1176 *nsec = r;
1177
1178 return 0;
1179 }
1180
1181 bool ntp_synced(void) {
1182 struct timex txc = {};
1183
1184 if (adjtimex(&txc) < 0)
1185 return false;
1186
1187 if (txc.status & STA_UNSYNC)
1188 return false;
1189
1190 return true;
1191 }
1192
1193 int get_timezones(char ***ret) {
1194 _cleanup_fclose_ FILE *f = NULL;
1195 _cleanup_strv_free_ char **zones = NULL;
1196 size_t n_zones = 0, n_allocated = 0;
1197 int r;
1198
1199 assert(ret);
1200
1201 zones = strv_new("UTC");
1202 if (!zones)
1203 return -ENOMEM;
1204
1205 n_allocated = 2;
1206 n_zones = 1;
1207
1208 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1209 if (f) {
1210 for (;;) {
1211 _cleanup_free_ char *line = NULL;
1212 char *p, *w;
1213 size_t k;
1214
1215 r = read_line(f, LONG_LINE_MAX, &line);
1216 if (r < 0)
1217 return r;
1218 if (r == 0)
1219 break;
1220
1221 p = strstrip(line);
1222
1223 if (isempty(p) || *p == '#')
1224 continue;
1225
1226 /* Skip over country code */
1227 p += strcspn(p, WHITESPACE);
1228 p += strspn(p, WHITESPACE);
1229
1230 /* Skip over coordinates */
1231 p += strcspn(p, WHITESPACE);
1232 p += strspn(p, WHITESPACE);
1233
1234 /* Found timezone name */
1235 k = strcspn(p, WHITESPACE);
1236 if (k <= 0)
1237 continue;
1238
1239 w = strndup(p, k);
1240 if (!w)
1241 return -ENOMEM;
1242
1243 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1244 free(w);
1245 return -ENOMEM;
1246 }
1247
1248 zones[n_zones++] = w;
1249 zones[n_zones] = NULL;
1250 }
1251
1252 strv_sort(zones);
1253
1254 } else if (errno != ENOENT)
1255 return -errno;
1256
1257 *ret = TAKE_PTR(zones);
1258
1259 return 0;
1260 }
1261
1262 bool timezone_is_valid(const char *name, int log_level) {
1263 bool slash = false;
1264 const char *p, *t;
1265 _cleanup_close_ int fd = -1;
1266 char buf[4];
1267 int r;
1268
1269 if (isempty(name))
1270 return false;
1271
1272 if (name[0] == '/')
1273 return false;
1274
1275 for (p = name; *p; p++) {
1276 if (!(*p >= '0' && *p <= '9') &&
1277 !(*p >= 'a' && *p <= 'z') &&
1278 !(*p >= 'A' && *p <= 'Z') &&
1279 !IN_SET(*p, '-', '_', '+', '/'))
1280 return false;
1281
1282 if (*p == '/') {
1283
1284 if (slash)
1285 return false;
1286
1287 slash = true;
1288 } else
1289 slash = false;
1290 }
1291
1292 if (slash)
1293 return false;
1294
1295 if (p - name >= PATH_MAX)
1296 return false;
1297
1298 t = strjoina("/usr/share/zoneinfo/", name);
1299
1300 fd = open(t, O_RDONLY|O_CLOEXEC);
1301 if (fd < 0) {
1302 log_full_errno(log_level, errno, "Failed to open timezone file '%s': %m", t);
1303 return false;
1304 }
1305
1306 r = fd_verify_regular(fd);
1307 if (r < 0) {
1308 log_full_errno(log_level, r, "Timezone file '%s' is not a regular file: %m", t);
1309 return false;
1310 }
1311
1312 r = loop_read_exact(fd, buf, 4, false);
1313 if (r < 0) {
1314 log_full_errno(log_level, r, "Failed to read from timezone file '%s': %m", t);
1315 return false;
1316 }
1317
1318 /* Magic from tzfile(5) */
1319 if (memcmp(buf, "TZif", 4) != 0) {
1320 log_full(log_level, "Timezone file '%s' has wrong magic bytes", t);
1321 return false;
1322 }
1323
1324 return true;
1325 }
1326
1327 bool clock_boottime_supported(void) {
1328 static int supported = -1;
1329
1330 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1331
1332 if (supported < 0) {
1333 int fd;
1334
1335 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1336 if (fd < 0)
1337 supported = false;
1338 else {
1339 safe_close(fd);
1340 supported = true;
1341 }
1342 }
1343
1344 return supported;
1345 }
1346
1347 clockid_t clock_boottime_or_monotonic(void) {
1348 if (clock_boottime_supported())
1349 return CLOCK_BOOTTIME;
1350 else
1351 return CLOCK_MONOTONIC;
1352 }
1353
1354 bool clock_supported(clockid_t clock) {
1355 struct timespec ts;
1356
1357 switch (clock) {
1358
1359 case CLOCK_MONOTONIC:
1360 case CLOCK_REALTIME:
1361 return true;
1362
1363 case CLOCK_BOOTTIME:
1364 return clock_boottime_supported();
1365
1366 case CLOCK_BOOTTIME_ALARM:
1367 if (!clock_boottime_supported())
1368 return false;
1369
1370 _fallthrough_;
1371 default:
1372 /* For everything else, check properly */
1373 return clock_gettime(clock, &ts) >= 0;
1374 }
1375 }
1376
1377 int get_timezone(char **tz) {
1378 _cleanup_free_ char *t = NULL;
1379 const char *e;
1380 char *z;
1381 int r;
1382
1383 r = readlink_malloc("/etc/localtime", &t);
1384 if (r < 0)
1385 return r; /* returns EINVAL if not a symlink */
1386
1387 e = path_startswith(t, "/usr/share/zoneinfo/");
1388 if (!e)
1389 e = path_startswith(t, "../usr/share/zoneinfo/");
1390 if (!e)
1391 return -EINVAL;
1392
1393 if (!timezone_is_valid(e, LOG_DEBUG))
1394 return -EINVAL;
1395
1396 z = strdup(e);
1397 if (!z)
1398 return -ENOMEM;
1399
1400 *tz = z;
1401 return 0;
1402 }
1403
1404 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1405 return utc ? timegm(tm) : mktime(tm);
1406 }
1407
1408 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1409 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1410 }
1411
1412 unsigned long usec_to_jiffies(usec_t u) {
1413 static thread_local unsigned long hz = 0;
1414 long r;
1415
1416 if (hz == 0) {
1417 r = sysconf(_SC_CLK_TCK);
1418
1419 assert(r > 0);
1420 hz = r;
1421 }
1422
1423 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1424 }
1425
1426 usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
1427 usec_t a, b;
1428
1429 if (x == USEC_INFINITY)
1430 return USEC_INFINITY;
1431 if (map_clock_id(from) == map_clock_id(to))
1432 return x;
1433
1434 a = now(from);
1435 b = now(to);
1436
1437 if (x > a)
1438 /* x lies in the future */
1439 return usec_add(b, usec_sub_unsigned(x, a));
1440 else
1441 /* x lies in the past */
1442 return usec_sub_unsigned(b, usec_sub_unsigned(a, x));
1443 }
1444
1445 bool in_utc_timezone(void) {
1446 tzset();
1447
1448 return timezone == 0 && daylight == 0;
1449 }
1450
1451 int time_change_fd(void) {
1452
1453 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1454 static const struct itimerspec its = {
1455 .it_value.tv_sec = TIME_T_MAX,
1456 };
1457
1458 _cleanup_close_ int fd;
1459
1460 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
1461
1462 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1463 * CLOCK_MONOTONIC. */
1464
1465 fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1466 if (fd < 0)
1467 return -errno;
1468
1469 if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0)
1470 return -errno;
1471
1472 return TAKE_FD(fd);
1473 }