]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/time-util.c
core: rework serialization
[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 "def.h"
18 #include "fd-util.h"
19 #include "fileio.h"
20 #include "fs-util.h"
21 #include "io-util.h"
22 #include "log.h"
23 #include "macro.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "process-util.h"
27 #include "serialize.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 static int parse_timestamp_impl(const char *t, usec_t *usec, bool with_tz) {
535 static const struct {
536 const char *name;
537 const int nr;
538 } day_nr[] = {
539 { "Sunday", 0 },
540 { "Sun", 0 },
541 { "Monday", 1 },
542 { "Mon", 1 },
543 { "Tuesday", 2 },
544 { "Tue", 2 },
545 { "Wednesday", 3 },
546 { "Wed", 3 },
547 { "Thursday", 4 },
548 { "Thu", 4 },
549 { "Friday", 5 },
550 { "Fri", 5 },
551 { "Saturday", 6 },
552 { "Sat", 6 },
553 };
554
555 const char *k, *utc = NULL, *tzn = NULL;
556 struct tm tm, copy;
557 time_t x;
558 usec_t x_usec, plus = 0, minus = 0, ret;
559 int r, weekday = -1, dst = -1;
560 size_t i;
561
562 /* Allowed syntaxes:
563 *
564 * 2012-09-22 16:34:22
565 * 2012-09-22 16:34 (seconds will be set to 0)
566 * 2012-09-22 (time will be set to 00:00:00)
567 * 16:34:22 (date will be set to today)
568 * 16:34 (date will be set to today, seconds to 0)
569 * now
570 * yesterday (time is set to 00:00:00)
571 * today (time is set to 00:00:00)
572 * tomorrow (time is set to 00:00:00)
573 * +5min
574 * -5days
575 * @2147483647 (seconds since epoch)
576 */
577
578 assert(t);
579 assert(usec);
580
581 if (t[0] == '@' && !with_tz)
582 return parse_sec(t + 1, usec);
583
584 ret = now(CLOCK_REALTIME);
585
586 if (!with_tz) {
587 if (streq(t, "now"))
588 goto finish;
589
590 else if (t[0] == '+') {
591 r = parse_sec(t+1, &plus);
592 if (r < 0)
593 return r;
594
595 goto finish;
596
597 } else if (t[0] == '-') {
598 r = parse_sec(t+1, &minus);
599 if (r < 0)
600 return r;
601
602 goto finish;
603
604 } else if ((k = endswith(t, " ago"))) {
605 t = strndupa(t, k - t);
606
607 r = parse_sec(t, &minus);
608 if (r < 0)
609 return r;
610
611 goto finish;
612
613 } else if ((k = endswith(t, " left"))) {
614 t = strndupa(t, k - t);
615
616 r = parse_sec(t, &plus);
617 if (r < 0)
618 return r;
619
620 goto finish;
621 }
622
623 /* See if the timestamp is suffixed with UTC */
624 utc = endswith_no_case(t, " UTC");
625 if (utc)
626 t = strndupa(t, utc - t);
627 else {
628 const char *e = NULL;
629 int j;
630
631 tzset();
632
633 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
634 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
635 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
636 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
637 * support arbitrary timezone specifications. */
638
639 for (j = 0; j <= 1; j++) {
640
641 if (isempty(tzname[j]))
642 continue;
643
644 e = endswith_no_case(t, tzname[j]);
645 if (!e)
646 continue;
647 if (e == t)
648 continue;
649 if (e[-1] != ' ')
650 continue;
651
652 break;
653 }
654
655 if (IN_SET(j, 0, 1)) {
656 /* Found one of the two timezones specified. */
657 t = strndupa(t, e - t - 1);
658 dst = j;
659 tzn = tzname[j];
660 }
661 }
662 }
663
664 x = (time_t) (ret / USEC_PER_SEC);
665 x_usec = 0;
666
667 if (!localtime_or_gmtime_r(&x, &tm, utc))
668 return -EINVAL;
669
670 tm.tm_isdst = dst;
671 if (!with_tz && tzn)
672 tm.tm_zone = tzn;
673
674 if (streq(t, "today")) {
675 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
676 goto from_tm;
677
678 } else if (streq(t, "yesterday")) {
679 tm.tm_mday--;
680 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
681 goto from_tm;
682
683 } else if (streq(t, "tomorrow")) {
684 tm.tm_mday++;
685 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
686 goto from_tm;
687 }
688
689 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
690 size_t skip;
691
692 if (!startswith_no_case(t, day_nr[i].name))
693 continue;
694
695 skip = strlen(day_nr[i].name);
696 if (t[skip] != ' ')
697 continue;
698
699 weekday = day_nr[i].nr;
700 t += skip + 1;
701 break;
702 }
703
704 copy = tm;
705 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
706 if (k) {
707 if (*k == '.')
708 goto parse_usec;
709 else if (*k == 0)
710 goto from_tm;
711 }
712
713 tm = copy;
714 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
715 if (k) {
716 if (*k == '.')
717 goto parse_usec;
718 else if (*k == 0)
719 goto from_tm;
720 }
721
722 tm = copy;
723 k = strptime(t, "%y-%m-%d %H:%M", &tm);
724 if (k && *k == 0) {
725 tm.tm_sec = 0;
726 goto from_tm;
727 }
728
729 tm = copy;
730 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
731 if (k && *k == 0) {
732 tm.tm_sec = 0;
733 goto from_tm;
734 }
735
736 tm = copy;
737 k = strptime(t, "%y-%m-%d", &tm);
738 if (k && *k == 0) {
739 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
740 goto from_tm;
741 }
742
743 tm = copy;
744 k = strptime(t, "%Y-%m-%d", &tm);
745 if (k && *k == 0) {
746 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
747 goto from_tm;
748 }
749
750 tm = copy;
751 k = strptime(t, "%H:%M:%S", &tm);
752 if (k) {
753 if (*k == '.')
754 goto parse_usec;
755 else if (*k == 0)
756 goto from_tm;
757 }
758
759 tm = copy;
760 k = strptime(t, "%H:%M", &tm);
761 if (k && *k == 0) {
762 tm.tm_sec = 0;
763 goto from_tm;
764 }
765
766 return -EINVAL;
767
768 parse_usec:
769 {
770 unsigned add;
771
772 k++;
773 r = parse_fractional_part_u(&k, 6, &add);
774 if (r < 0)
775 return -EINVAL;
776
777 if (*k)
778 return -EINVAL;
779
780 x_usec = add;
781 }
782
783 from_tm:
784 if (weekday >= 0 && tm.tm_wday != weekday)
785 return -EINVAL;
786
787 x = mktime_or_timegm(&tm, utc);
788 if (x < 0)
789 return -EINVAL;
790
791 ret = (usec_t) x * USEC_PER_SEC + x_usec;
792 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
793 return -EINVAL;
794
795 finish:
796 if (ret + plus < ret) /* overflow? */
797 return -EINVAL;
798 ret += plus;
799 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
800 return -EINVAL;
801
802 if (ret >= minus)
803 ret -= minus;
804 else
805 return -EINVAL;
806
807 *usec = ret;
808
809 return 0;
810 }
811
812 typedef struct ParseTimestampResult {
813 usec_t usec;
814 int return_value;
815 } ParseTimestampResult;
816
817 int parse_timestamp(const char *t, usec_t *usec) {
818 char *last_space, *tz = NULL;
819 ParseTimestampResult *shared, tmp;
820 int r;
821
822 last_space = strrchr(t, ' ');
823 if (last_space != NULL && timezone_is_valid(last_space + 1, LOG_DEBUG))
824 tz = last_space + 1;
825
826 if (!tz || endswith_no_case(t, " UTC"))
827 return parse_timestamp_impl(t, usec, false);
828
829 shared = mmap(NULL, sizeof *shared, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
830 if (shared == MAP_FAILED)
831 return negative_errno();
832
833 r = safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_WAIT, NULL);
834 if (r < 0) {
835 (void) munmap(shared, sizeof *shared);
836 return r;
837 }
838 if (r == 0) {
839 bool with_tz = true;
840
841 if (setenv("TZ", tz, 1) != 0) {
842 shared->return_value = negative_errno();
843 _exit(EXIT_FAILURE);
844 }
845
846 tzset();
847
848 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
849 * Otherwise just cut it off. */
850 with_tz = !STR_IN_SET(tz, tzname[0], tzname[1]);
851
852 /* Cut off the timezone if we don't need it. */
853 if (with_tz)
854 t = strndupa(t, last_space - t);
855
856 shared->return_value = parse_timestamp_impl(t, &shared->usec, with_tz);
857
858 _exit(EXIT_SUCCESS);
859 }
860
861 tmp = *shared;
862 if (munmap(shared, sizeof *shared) != 0)
863 return negative_errno();
864
865 if (tmp.return_value == 0)
866 *usec = tmp.usec;
867
868 return tmp.return_value;
869 }
870
871 static char* extract_multiplier(char *p, usec_t *multiplier) {
872 static const struct {
873 const char *suffix;
874 usec_t usec;
875 } table[] = {
876 { "seconds", USEC_PER_SEC },
877 { "second", USEC_PER_SEC },
878 { "sec", USEC_PER_SEC },
879 { "s", USEC_PER_SEC },
880 { "minutes", USEC_PER_MINUTE },
881 { "minute", USEC_PER_MINUTE },
882 { "min", USEC_PER_MINUTE },
883 { "months", USEC_PER_MONTH },
884 { "month", USEC_PER_MONTH },
885 { "M", USEC_PER_MONTH },
886 { "msec", USEC_PER_MSEC },
887 { "ms", USEC_PER_MSEC },
888 { "m", USEC_PER_MINUTE },
889 { "hours", USEC_PER_HOUR },
890 { "hour", USEC_PER_HOUR },
891 { "hr", USEC_PER_HOUR },
892 { "h", USEC_PER_HOUR },
893 { "days", USEC_PER_DAY },
894 { "day", USEC_PER_DAY },
895 { "d", USEC_PER_DAY },
896 { "weeks", USEC_PER_WEEK },
897 { "week", USEC_PER_WEEK },
898 { "w", USEC_PER_WEEK },
899 { "years", USEC_PER_YEAR },
900 { "year", USEC_PER_YEAR },
901 { "y", USEC_PER_YEAR },
902 { "usec", 1ULL },
903 { "us", 1ULL },
904 { "µs", 1ULL },
905 };
906 size_t i;
907
908 for (i = 0; i < ELEMENTSOF(table); i++) {
909 char *e;
910
911 e = startswith(p, table[i].suffix);
912 if (e) {
913 *multiplier = table[i].usec;
914 return e;
915 }
916 }
917
918 return p;
919 }
920
921 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
922 const char *p, *s;
923 usec_t r = 0;
924 bool something = false;
925
926 assert(t);
927 assert(usec);
928 assert(default_unit > 0);
929
930 p = t;
931
932 p += strspn(p, WHITESPACE);
933 s = startswith(p, "infinity");
934 if (s) {
935 s += strspn(s, WHITESPACE);
936 if (*s != 0)
937 return -EINVAL;
938
939 *usec = USEC_INFINITY;
940 return 0;
941 }
942
943 for (;;) {
944 usec_t multiplier = default_unit, k;
945 long long l, z = 0;
946 unsigned n = 0;
947 char *e;
948
949 p += strspn(p, WHITESPACE);
950
951 if (*p == 0) {
952 if (!something)
953 return -EINVAL;
954
955 break;
956 }
957
958 if (*p == '-') /* Don't allow "-0" */
959 return -ERANGE;
960
961 errno = 0;
962 l = strtoll(p, &e, 10);
963 if (errno > 0)
964 return -errno;
965 if (l < 0)
966 return -ERANGE;
967
968 if (*e == '.') {
969 char *b = e + 1;
970
971 /* Don't allow "0.-0", "3.+1" or "3. 1" */
972 if (IN_SET(*b, '-', '+') || isspace(*b))
973 return -EINVAL;
974
975 errno = 0;
976 z = strtoll(b, &e, 10);
977 if (errno > 0)
978 return -errno;
979 if (z < 0)
980 return -ERANGE;
981 if (e == b)
982 return -EINVAL;
983
984 n = e - b;
985
986 } else if (e == p)
987 return -EINVAL;
988
989 e += strspn(e, WHITESPACE);
990 p = extract_multiplier(e, &multiplier);
991
992 something = true;
993
994
995 k = ((usec_t) -1) / multiplier;
996 if ((usec_t) l + 1 >= k || (usec_t) z >= k)
997 return -ERANGE;
998
999 k = (usec_t) z * multiplier;
1000
1001 for (; n > 0; n--)
1002 k /= 10;
1003
1004 k += (usec_t) l * multiplier;
1005 if (k >= ((usec_t) -1) - r)
1006 return -ERANGE;
1007
1008 r += k;
1009 }
1010
1011 *usec = r;
1012
1013 return 0;
1014 }
1015
1016 int parse_sec(const char *t, usec_t *usec) {
1017 return parse_time(t, usec, USEC_PER_SEC);
1018 }
1019
1020 int parse_sec_fix_0(const char *t, usec_t *ret) {
1021 usec_t k;
1022 int r;
1023
1024 assert(t);
1025 assert(ret);
1026
1027 r = parse_sec(t, &k);
1028 if (r < 0)
1029 return r;
1030
1031 *ret = k == 0 ? USEC_INFINITY : k;
1032 return r;
1033 }
1034
1035 int parse_nsec(const char *t, nsec_t *nsec) {
1036 static const struct {
1037 const char *suffix;
1038 nsec_t nsec;
1039 } table[] = {
1040 { "seconds", NSEC_PER_SEC },
1041 { "second", NSEC_PER_SEC },
1042 { "sec", NSEC_PER_SEC },
1043 { "s", NSEC_PER_SEC },
1044 { "minutes", NSEC_PER_MINUTE },
1045 { "minute", NSEC_PER_MINUTE },
1046 { "min", NSEC_PER_MINUTE },
1047 { "months", NSEC_PER_MONTH },
1048 { "month", 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
1073 const char *p, *s;
1074 nsec_t r = 0;
1075 bool something = false;
1076
1077 assert(t);
1078 assert(nsec);
1079
1080 p = t;
1081
1082 p += strspn(p, WHITESPACE);
1083 s = startswith(p, "infinity");
1084 if (s) {
1085 s += strspn(s, WHITESPACE);
1086 if (*s != 0)
1087 return -EINVAL;
1088
1089 *nsec = NSEC_INFINITY;
1090 return 0;
1091 }
1092
1093 for (;;) {
1094 long long l, z = 0;
1095 size_t n = 0, i;
1096 char *e;
1097
1098 p += strspn(p, WHITESPACE);
1099
1100 if (*p == 0) {
1101 if (!something)
1102 return -EINVAL;
1103
1104 break;
1105 }
1106
1107 if (*p == '-')
1108 return -ERANGE;
1109
1110 errno = 0;
1111 l = strtoll(p, &e, 10);
1112 if (errno > 0)
1113 return -errno;
1114 if (l < 0)
1115 return -ERANGE;
1116
1117 if (*e == '.') {
1118 char *b = e + 1;
1119
1120 if (IN_SET(*b, '-', '+') || isspace(*b))
1121 return -EINVAL;
1122
1123 errno = 0;
1124 z = strtoll(b, &e, 10);
1125 if (errno > 0)
1126 return -errno;
1127 if (z < 0)
1128 return -ERANGE;
1129 if (e == b)
1130 return -EINVAL;
1131
1132 n = e - b;
1133
1134 } else if (e == p)
1135 return -EINVAL;
1136
1137 e += strspn(e, WHITESPACE);
1138
1139 for (i = 0; i < ELEMENTSOF(table); i++)
1140 if (startswith(e, table[i].suffix)) {
1141 nsec_t k;
1142
1143 k = ((nsec_t) -1) / table[i].nsec;
1144 if ((nsec_t) l + 1 >= k || (nsec_t) z >= k)
1145 return -ERANGE;
1146
1147 k = (nsec_t) z * table[i].nsec;
1148
1149 for (; n > 0; n--)
1150 k /= 10;
1151
1152 k += (nsec_t) l * table[i].nsec;
1153 if (k >= ((nsec_t) -1) - r)
1154 return -ERANGE;
1155
1156 r += k;
1157 p = e + strlen(table[i].suffix);
1158
1159 something = true;
1160 break;
1161 }
1162
1163 if (i >= ELEMENTSOF(table))
1164 return -EINVAL;
1165
1166 }
1167
1168 *nsec = r;
1169
1170 return 0;
1171 }
1172
1173 bool ntp_synced(void) {
1174 struct timex txc = {};
1175
1176 if (adjtimex(&txc) < 0)
1177 return false;
1178
1179 if (txc.status & STA_UNSYNC)
1180 return false;
1181
1182 return true;
1183 }
1184
1185 int get_timezones(char ***ret) {
1186 _cleanup_fclose_ FILE *f = NULL;
1187 _cleanup_strv_free_ char **zones = NULL;
1188 size_t n_zones = 0, n_allocated = 0;
1189 int r;
1190
1191 assert(ret);
1192
1193 zones = strv_new("UTC", NULL);
1194 if (!zones)
1195 return -ENOMEM;
1196
1197 n_allocated = 2;
1198 n_zones = 1;
1199
1200 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1201 if (f) {
1202 for (;;) {
1203 _cleanup_free_ char *line = NULL;
1204 char *p, *w;
1205 size_t k;
1206
1207 r = read_line(f, LONG_LINE_MAX, &line);
1208 if (r < 0)
1209 return r;
1210 if (r == 0)
1211 break;
1212
1213 p = strstrip(line);
1214
1215 if (isempty(p) || *p == '#')
1216 continue;
1217
1218 /* Skip over country code */
1219 p += strcspn(p, WHITESPACE);
1220 p += strspn(p, WHITESPACE);
1221
1222 /* Skip over coordinates */
1223 p += strcspn(p, WHITESPACE);
1224 p += strspn(p, WHITESPACE);
1225
1226 /* Found timezone name */
1227 k = strcspn(p, WHITESPACE);
1228 if (k <= 0)
1229 continue;
1230
1231 w = strndup(p, k);
1232 if (!w)
1233 return -ENOMEM;
1234
1235 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1236 free(w);
1237 return -ENOMEM;
1238 }
1239
1240 zones[n_zones++] = w;
1241 zones[n_zones] = NULL;
1242 }
1243
1244 strv_sort(zones);
1245
1246 } else if (errno != ENOENT)
1247 return -errno;
1248
1249 *ret = TAKE_PTR(zones);
1250
1251 return 0;
1252 }
1253
1254 bool timezone_is_valid(const char *name, int log_level) {
1255 bool slash = false;
1256 const char *p, *t;
1257 _cleanup_close_ int fd = -1;
1258 char buf[4];
1259 int r;
1260
1261 if (isempty(name))
1262 return false;
1263
1264 if (name[0] == '/')
1265 return false;
1266
1267 for (p = name; *p; p++) {
1268 if (!(*p >= '0' && *p <= '9') &&
1269 !(*p >= 'a' && *p <= 'z') &&
1270 !(*p >= 'A' && *p <= 'Z') &&
1271 !IN_SET(*p, '-', '_', '+', '/'))
1272 return false;
1273
1274 if (*p == '/') {
1275
1276 if (slash)
1277 return false;
1278
1279 slash = true;
1280 } else
1281 slash = false;
1282 }
1283
1284 if (slash)
1285 return false;
1286
1287 if (p - name >= PATH_MAX)
1288 return false;
1289
1290 t = strjoina("/usr/share/zoneinfo/", name);
1291
1292 fd = open(t, O_RDONLY|O_CLOEXEC);
1293 if (fd < 0) {
1294 log_full_errno(log_level, errno, "Failed to open timezone file '%s': %m", t);
1295 return false;
1296 }
1297
1298 r = fd_verify_regular(fd);
1299 if (r < 0) {
1300 log_full_errno(log_level, r, "Timezone file '%s' is not a regular file: %m", t);
1301 return false;
1302 }
1303
1304 r = loop_read_exact(fd, buf, 4, false);
1305 if (r < 0) {
1306 log_full_errno(log_level, r, "Failed to read from timezone file '%s': %m", t);
1307 return false;
1308 }
1309
1310 /* Magic from tzfile(5) */
1311 if (memcmp(buf, "TZif", 4) != 0) {
1312 log_full(log_level, "Timezone file '%s' has wrong magic bytes", t);
1313 return false;
1314 }
1315
1316 return true;
1317 }
1318
1319 bool clock_boottime_supported(void) {
1320 static int supported = -1;
1321
1322 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1323
1324 if (supported < 0) {
1325 int fd;
1326
1327 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1328 if (fd < 0)
1329 supported = false;
1330 else {
1331 safe_close(fd);
1332 supported = true;
1333 }
1334 }
1335
1336 return supported;
1337 }
1338
1339 clockid_t clock_boottime_or_monotonic(void) {
1340 if (clock_boottime_supported())
1341 return CLOCK_BOOTTIME;
1342 else
1343 return CLOCK_MONOTONIC;
1344 }
1345
1346 bool clock_supported(clockid_t clock) {
1347 struct timespec ts;
1348
1349 switch (clock) {
1350
1351 case CLOCK_MONOTONIC:
1352 case CLOCK_REALTIME:
1353 return true;
1354
1355 case CLOCK_BOOTTIME:
1356 return clock_boottime_supported();
1357
1358 case CLOCK_BOOTTIME_ALARM:
1359 if (!clock_boottime_supported())
1360 return false;
1361
1362 _fallthrough_;
1363 default:
1364 /* For everything else, check properly */
1365 return clock_gettime(clock, &ts) >= 0;
1366 }
1367 }
1368
1369 int get_timezone(char **tz) {
1370 _cleanup_free_ char *t = NULL;
1371 const char *e;
1372 char *z;
1373 int r;
1374
1375 r = readlink_malloc("/etc/localtime", &t);
1376 if (r < 0)
1377 return r; /* returns EINVAL if not a symlink */
1378
1379 e = path_startswith(t, "/usr/share/zoneinfo/");
1380 if (!e)
1381 e = path_startswith(t, "../usr/share/zoneinfo/");
1382 if (!e)
1383 return -EINVAL;
1384
1385 if (!timezone_is_valid(e, LOG_DEBUG))
1386 return -EINVAL;
1387
1388 z = strdup(e);
1389 if (!z)
1390 return -ENOMEM;
1391
1392 *tz = z;
1393 return 0;
1394 }
1395
1396 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1397 return utc ? timegm(tm) : mktime(tm);
1398 }
1399
1400 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1401 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1402 }
1403
1404 unsigned long usec_to_jiffies(usec_t u) {
1405 static thread_local unsigned long hz = 0;
1406 long r;
1407
1408 if (hz == 0) {
1409 r = sysconf(_SC_CLK_TCK);
1410
1411 assert(r > 0);
1412 hz = r;
1413 }
1414
1415 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1416 }
1417
1418 usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
1419 usec_t a, b;
1420
1421 if (x == USEC_INFINITY)
1422 return USEC_INFINITY;
1423 if (map_clock_id(from) == map_clock_id(to))
1424 return x;
1425
1426 a = now(from);
1427 b = now(to);
1428
1429 if (x > a)
1430 /* x lies in the future */
1431 return usec_add(b, usec_sub_unsigned(x, a));
1432 else
1433 /* x lies in the past */
1434 return usec_sub_unsigned(b, usec_sub_unsigned(a, x));
1435 }
1436
1437 bool in_utc_timezone(void) {
1438 tzset();
1439
1440 return timezone == 0 && daylight == 0;
1441 }
1442
1443 int time_change_fd(void) {
1444
1445 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1446 static const struct itimerspec its = {
1447 .it_value.tv_sec = TIME_T_MAX,
1448 };
1449
1450 _cleanup_close_ int fd;
1451
1452 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
1453
1454 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1455 * CLOCK_MONOTONIC. */
1456
1457 fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1458 if (fd < 0)
1459 return -errno;
1460
1461 if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0)
1462 return -errno;
1463
1464 return TAKE_FD(fd);
1465 }