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