]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/time-util.c
Merge pull request #11827 from keszybz/pkgconfig-variables
[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 "missing_timerfd.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "process-util.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 int parse_sec_def_infinity(const char *t, usec_t *ret) {
1035 t += strspn(t, WHITESPACE);
1036 if (isempty(t)) {
1037 *ret = USEC_INFINITY;
1038 return 0;
1039 }
1040 return parse_sec(t, ret);
1041 }
1042
1043 static const char* extract_nsec_multiplier(const char *p, nsec_t *multiplier) {
1044 static const struct {
1045 const char *suffix;
1046 nsec_t nsec;
1047 } table[] = {
1048 { "seconds", NSEC_PER_SEC },
1049 { "second", NSEC_PER_SEC },
1050 { "sec", NSEC_PER_SEC },
1051 { "s", NSEC_PER_SEC },
1052 { "minutes", NSEC_PER_MINUTE },
1053 { "minute", NSEC_PER_MINUTE },
1054 { "min", NSEC_PER_MINUTE },
1055 { "months", NSEC_PER_MONTH },
1056 { "month", NSEC_PER_MONTH },
1057 { "M", NSEC_PER_MONTH },
1058 { "msec", NSEC_PER_MSEC },
1059 { "ms", NSEC_PER_MSEC },
1060 { "m", NSEC_PER_MINUTE },
1061 { "hours", NSEC_PER_HOUR },
1062 { "hour", NSEC_PER_HOUR },
1063 { "hr", NSEC_PER_HOUR },
1064 { "h", NSEC_PER_HOUR },
1065 { "days", NSEC_PER_DAY },
1066 { "day", NSEC_PER_DAY },
1067 { "d", NSEC_PER_DAY },
1068 { "weeks", NSEC_PER_WEEK },
1069 { "week", NSEC_PER_WEEK },
1070 { "w", NSEC_PER_WEEK },
1071 { "years", NSEC_PER_YEAR },
1072 { "year", NSEC_PER_YEAR },
1073 { "y", NSEC_PER_YEAR },
1074 { "usec", NSEC_PER_USEC },
1075 { "us", NSEC_PER_USEC },
1076 { "µs", NSEC_PER_USEC },
1077 { "nsec", 1ULL },
1078 { "ns", 1ULL },
1079 { "", 1ULL }, /* default is nsec */
1080 };
1081 size_t i;
1082
1083 for (i = 0; i < ELEMENTSOF(table); i++) {
1084 char *e;
1085
1086 e = startswith(p, table[i].suffix);
1087 if (e) {
1088 *multiplier = table[i].nsec;
1089 return e;
1090 }
1091 }
1092
1093 return p;
1094 }
1095
1096 int parse_nsec(const char *t, nsec_t *nsec) {
1097 const char *p, *s;
1098 nsec_t r = 0;
1099 bool something = false;
1100
1101 assert(t);
1102 assert(nsec);
1103
1104 p = t;
1105
1106 p += strspn(p, WHITESPACE);
1107 s = startswith(p, "infinity");
1108 if (s) {
1109 s += strspn(s, WHITESPACE);
1110 if (*s != 0)
1111 return -EINVAL;
1112
1113 *nsec = NSEC_INFINITY;
1114 return 0;
1115 }
1116
1117 for (;;) {
1118 nsec_t multiplier = 1, k;
1119 long long l;
1120 char *e;
1121
1122 p += strspn(p, WHITESPACE);
1123
1124 if (*p == 0) {
1125 if (!something)
1126 return -EINVAL;
1127
1128 break;
1129 }
1130
1131 if (*p == '-') /* Don't allow "-0" */
1132 return -ERANGE;
1133
1134 errno = 0;
1135 l = strtoll(p, &e, 10);
1136 if (errno > 0)
1137 return -errno;
1138 if (l < 0)
1139 return -ERANGE;
1140
1141 if (*e == '.') {
1142 p = e + 1;
1143 p += strspn(p, DIGITS);
1144 } else if (e == p)
1145 return -EINVAL;
1146 else
1147 p = e;
1148
1149 s = extract_nsec_multiplier(p + strspn(p, WHITESPACE), &multiplier);
1150 if (s == p && *s != '\0')
1151 /* Don't allow '12.34.56', but accept '12.34 .56' or '12.34s.56'*/
1152 return -EINVAL;
1153
1154 p = s;
1155
1156 if ((nsec_t) l >= NSEC_INFINITY / multiplier)
1157 return -ERANGE;
1158
1159 k = (nsec_t) l * multiplier;
1160 if (k >= NSEC_INFINITY - r)
1161 return -ERANGE;
1162
1163 r += k;
1164
1165 something = true;
1166
1167 if (*e == '.') {
1168 nsec_t m = multiplier / 10;
1169 const char *b;
1170
1171 for (b = e + 1; *b >= '0' && *b <= '9'; b++, m /= 10) {
1172 k = (nsec_t) (*b - '0') * m;
1173 if (k >= NSEC_INFINITY - r)
1174 return -ERANGE;
1175
1176 r += k;
1177 }
1178
1179 /* Don't allow "0.-0", "3.+1", "3. 1", "3.sec" or "3.hoge"*/
1180 if (b == e + 1)
1181 return -EINVAL;
1182 }
1183 }
1184
1185 *nsec = r;
1186
1187 return 0;
1188 }
1189
1190 bool ntp_synced(void) {
1191 struct timex txc = {};
1192
1193 if (adjtimex(&txc) < 0)
1194 return false;
1195
1196 if (txc.status & STA_UNSYNC)
1197 return false;
1198
1199 return true;
1200 }
1201
1202 int get_timezones(char ***ret) {
1203 _cleanup_fclose_ FILE *f = NULL;
1204 _cleanup_strv_free_ char **zones = NULL;
1205 size_t n_zones = 0, n_allocated = 0;
1206 int r;
1207
1208 assert(ret);
1209
1210 zones = strv_new("UTC");
1211 if (!zones)
1212 return -ENOMEM;
1213
1214 n_allocated = 2;
1215 n_zones = 1;
1216
1217 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1218 if (f) {
1219 for (;;) {
1220 _cleanup_free_ char *line = NULL;
1221 char *p, *w;
1222 size_t k;
1223
1224 r = read_line(f, LONG_LINE_MAX, &line);
1225 if (r < 0)
1226 return r;
1227 if (r == 0)
1228 break;
1229
1230 p = strstrip(line);
1231
1232 if (isempty(p) || *p == '#')
1233 continue;
1234
1235 /* Skip over country code */
1236 p += strcspn(p, WHITESPACE);
1237 p += strspn(p, WHITESPACE);
1238
1239 /* Skip over coordinates */
1240 p += strcspn(p, WHITESPACE);
1241 p += strspn(p, WHITESPACE);
1242
1243 /* Found timezone name */
1244 k = strcspn(p, WHITESPACE);
1245 if (k <= 0)
1246 continue;
1247
1248 w = strndup(p, k);
1249 if (!w)
1250 return -ENOMEM;
1251
1252 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1253 free(w);
1254 return -ENOMEM;
1255 }
1256
1257 zones[n_zones++] = w;
1258 zones[n_zones] = NULL;
1259 }
1260
1261 strv_sort(zones);
1262
1263 } else if (errno != ENOENT)
1264 return -errno;
1265
1266 *ret = TAKE_PTR(zones);
1267
1268 return 0;
1269 }
1270
1271 bool timezone_is_valid(const char *name, int log_level) {
1272 bool slash = false;
1273 const char *p, *t;
1274 _cleanup_close_ int fd = -1;
1275 char buf[4];
1276 int r;
1277
1278 if (isempty(name))
1279 return false;
1280
1281 if (name[0] == '/')
1282 return false;
1283
1284 for (p = name; *p; p++) {
1285 if (!(*p >= '0' && *p <= '9') &&
1286 !(*p >= 'a' && *p <= 'z') &&
1287 !(*p >= 'A' && *p <= 'Z') &&
1288 !IN_SET(*p, '-', '_', '+', '/'))
1289 return false;
1290
1291 if (*p == '/') {
1292
1293 if (slash)
1294 return false;
1295
1296 slash = true;
1297 } else
1298 slash = false;
1299 }
1300
1301 if (slash)
1302 return false;
1303
1304 if (p - name >= PATH_MAX)
1305 return false;
1306
1307 t = strjoina("/usr/share/zoneinfo/", name);
1308
1309 fd = open(t, O_RDONLY|O_CLOEXEC);
1310 if (fd < 0) {
1311 log_full_errno(log_level, errno, "Failed to open timezone file '%s': %m", t);
1312 return false;
1313 }
1314
1315 r = fd_verify_regular(fd);
1316 if (r < 0) {
1317 log_full_errno(log_level, r, "Timezone file '%s' is not a regular file: %m", t);
1318 return false;
1319 }
1320
1321 r = loop_read_exact(fd, buf, 4, false);
1322 if (r < 0) {
1323 log_full_errno(log_level, r, "Failed to read from timezone file '%s': %m", t);
1324 return false;
1325 }
1326
1327 /* Magic from tzfile(5) */
1328 if (memcmp(buf, "TZif", 4) != 0) {
1329 log_full(log_level, "Timezone file '%s' has wrong magic bytes", t);
1330 return false;
1331 }
1332
1333 return true;
1334 }
1335
1336 bool clock_boottime_supported(void) {
1337 static int supported = -1;
1338
1339 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1340
1341 if (supported < 0) {
1342 int fd;
1343
1344 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1345 if (fd < 0)
1346 supported = false;
1347 else {
1348 safe_close(fd);
1349 supported = true;
1350 }
1351 }
1352
1353 return supported;
1354 }
1355
1356 clockid_t clock_boottime_or_monotonic(void) {
1357 if (clock_boottime_supported())
1358 return CLOCK_BOOTTIME;
1359 else
1360 return CLOCK_MONOTONIC;
1361 }
1362
1363 bool clock_supported(clockid_t clock) {
1364 struct timespec ts;
1365
1366 switch (clock) {
1367
1368 case CLOCK_MONOTONIC:
1369 case CLOCK_REALTIME:
1370 return true;
1371
1372 case CLOCK_BOOTTIME:
1373 return clock_boottime_supported();
1374
1375 case CLOCK_BOOTTIME_ALARM:
1376 if (!clock_boottime_supported())
1377 return false;
1378
1379 _fallthrough_;
1380 default:
1381 /* For everything else, check properly */
1382 return clock_gettime(clock, &ts) >= 0;
1383 }
1384 }
1385
1386 int get_timezone(char **tz) {
1387 _cleanup_free_ char *t = NULL;
1388 const char *e;
1389 char *z;
1390 int r;
1391
1392 r = readlink_malloc("/etc/localtime", &t);
1393 if (r < 0)
1394 return r; /* returns EINVAL if not a symlink */
1395
1396 e = PATH_STARTSWITH_SET(t, "/usr/share/zoneinfo/", "../usr/share/zoneinfo/");
1397 if (!e)
1398 return -EINVAL;
1399
1400 if (!timezone_is_valid(e, LOG_DEBUG))
1401 return -EINVAL;
1402
1403 z = strdup(e);
1404 if (!z)
1405 return -ENOMEM;
1406
1407 *tz = z;
1408 return 0;
1409 }
1410
1411 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1412 return utc ? timegm(tm) : mktime(tm);
1413 }
1414
1415 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1416 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1417 }
1418
1419 unsigned long usec_to_jiffies(usec_t u) {
1420 static thread_local unsigned long hz = 0;
1421 long r;
1422
1423 if (hz == 0) {
1424 r = sysconf(_SC_CLK_TCK);
1425
1426 assert(r > 0);
1427 hz = r;
1428 }
1429
1430 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1431 }
1432
1433 usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
1434 usec_t a, b;
1435
1436 if (x == USEC_INFINITY)
1437 return USEC_INFINITY;
1438 if (map_clock_id(from) == map_clock_id(to))
1439 return x;
1440
1441 a = now(from);
1442 b = now(to);
1443
1444 if (x > a)
1445 /* x lies in the future */
1446 return usec_add(b, usec_sub_unsigned(x, a));
1447 else
1448 /* x lies in the past */
1449 return usec_sub_unsigned(b, usec_sub_unsigned(a, x));
1450 }
1451
1452 bool in_utc_timezone(void) {
1453 tzset();
1454
1455 return timezone == 0 && daylight == 0;
1456 }
1457
1458 int time_change_fd(void) {
1459
1460 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1461 static const struct itimerspec its = {
1462 .it_value.tv_sec = TIME_T_MAX,
1463 };
1464
1465 _cleanup_close_ int fd;
1466
1467 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
1468
1469 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1470 * CLOCK_MONOTONIC. */
1471
1472 fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1473 if (fd < 0)
1474 return -errno;
1475
1476 if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0)
1477 return -errno;
1478
1479 return TAKE_FD(fd);
1480 }