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