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