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