]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/time-util.c
tree-wide: don't assume CLOCK_BOOTIME is generally available
[thirdparty/systemd.git] / src / basic / time-util.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <limits.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <sys/time.h>
26 #include <sys/timerfd.h>
27 #include <sys/timex.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30
31 #include "alloc-util.h"
32 #include "fd-util.h"
33 #include "fileio.h"
34 #include "fs-util.h"
35 #include "log.h"
36 #include "macro.h"
37 #include "parse-util.h"
38 #include "path-util.h"
39 #include "string-util.h"
40 #include "strv.h"
41 #include "time-util.h"
42
43 static nsec_t timespec_load_nsec(const struct timespec *ts);
44
45 static clockid_t map_clock_id(clockid_t c) {
46
47 /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus, clock_gettime() will
48 * fail for them. Since they are essentially the same as their non-ALARM pendants (their only difference is
49 * when timers are set on them), let's just map them accordingly. This way, we can get the correct time even on
50 * those archs. */
51
52 switch (c) {
53
54 case CLOCK_BOOTTIME_ALARM:
55 return CLOCK_BOOTTIME;
56
57 case CLOCK_REALTIME_ALARM:
58 return CLOCK_REALTIME;
59
60 default:
61 return c;
62 }
63 }
64
65 usec_t now(clockid_t clock_id) {
66 struct timespec ts;
67
68 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
69
70 return timespec_load(&ts);
71 }
72
73 nsec_t now_nsec(clockid_t clock_id) {
74 struct timespec ts;
75
76 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
77
78 return timespec_load_nsec(&ts);
79 }
80
81 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
82 assert(ts);
83
84 ts->realtime = now(CLOCK_REALTIME);
85 ts->monotonic = now(CLOCK_MONOTONIC);
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(now(CLOCK_MONOTONIC), delta);
103
104 return ts;
105 }
106
107 dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
108 int64_t delta;
109 assert(ts);
110
111 if (u == USEC_INFINITY) {
112 ts->realtime = ts->monotonic = USEC_INFINITY;
113 return ts;
114 }
115
116 ts->monotonic = u;
117 delta = (int64_t) now(CLOCK_MONOTONIC) - (int64_t) u;
118 ts->realtime = usec_sub(now(CLOCK_REALTIME), delta);
119
120 return ts;
121 }
122
123 dual_timestamp* dual_timestamp_from_boottime_or_monotonic(dual_timestamp *ts, usec_t u) {
124 int64_t delta;
125
126 if (u == USEC_INFINITY) {
127 ts->realtime = ts->monotonic = USEC_INFINITY;
128 return ts;
129 }
130
131 dual_timestamp_get(ts);
132 delta = (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u;
133 ts->realtime = usec_sub(ts->realtime, delta);
134 ts->monotonic = usec_sub(ts->monotonic, delta);
135
136 return ts;
137 }
138
139 usec_t timespec_load(const struct timespec *ts) {
140 assert(ts);
141
142 if (ts->tv_sec == (time_t) -1 && ts->tv_nsec == (long) -1)
143 return USEC_INFINITY;
144
145 if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
146 return USEC_INFINITY;
147
148 return
149 (usec_t) ts->tv_sec * USEC_PER_SEC +
150 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
151 }
152
153 static nsec_t timespec_load_nsec(const struct timespec *ts) {
154 assert(ts);
155
156 if (ts->tv_sec == (time_t) -1 && ts->tv_nsec == (long) -1)
157 return NSEC_INFINITY;
158
159 if ((nsec_t) ts->tv_sec >= (UINT64_MAX - ts->tv_nsec) / NSEC_PER_SEC)
160 return NSEC_INFINITY;
161
162 return (nsec_t) ts->tv_sec * NSEC_PER_SEC + (nsec_t) ts->tv_nsec;
163 }
164
165 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
166 assert(ts);
167
168 if (u == USEC_INFINITY) {
169 ts->tv_sec = (time_t) -1;
170 ts->tv_nsec = (long) -1;
171 return ts;
172 }
173
174 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
175 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
176
177 return ts;
178 }
179
180 usec_t timeval_load(const struct timeval *tv) {
181 assert(tv);
182
183 if (tv->tv_sec == (time_t) -1 &&
184 tv->tv_usec == (suseconds_t) -1)
185 return USEC_INFINITY;
186
187 if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
188 return USEC_INFINITY;
189
190 return
191 (usec_t) tv->tv_sec * USEC_PER_SEC +
192 (usec_t) tv->tv_usec;
193 }
194
195 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
196 assert(tv);
197
198 if (u == USEC_INFINITY) {
199 tv->tv_sec = (time_t) -1;
200 tv->tv_usec = (suseconds_t) -1;
201 } else {
202 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
203 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
204 }
205
206 return tv;
207 }
208
209 static char *format_timestamp_internal(char *buf, size_t l, usec_t t,
210 bool utc, bool us) {
211 struct tm tm;
212 time_t sec;
213 int k;
214
215 assert(buf);
216 assert(l > 0);
217
218 if (t <= 0 || t == USEC_INFINITY)
219 return NULL;
220
221 sec = (time_t) (t / USEC_PER_SEC);
222 localtime_or_gmtime_r(&sec, &tm, utc);
223
224 if (us)
225 k = strftime(buf, l, "%a %Y-%m-%d %H:%M:%S", &tm);
226 else
227 k = strftime(buf, l, "%a %Y-%m-%d %H:%M:%S %Z", &tm);
228
229 if (k <= 0)
230 return NULL;
231 if (us) {
232 snprintf(buf + strlen(buf), l - strlen(buf), ".%06llu", (unsigned long long) (t % USEC_PER_SEC));
233 if (strftime(buf + strlen(buf), l - strlen(buf), " %Z", &tm) <= 0)
234 return NULL;
235 }
236
237 return buf;
238 }
239
240 char *format_timestamp(char *buf, size_t l, usec_t t) {
241 return format_timestamp_internal(buf, l, t, false, false);
242 }
243
244 char *format_timestamp_utc(char *buf, size_t l, usec_t t) {
245 return format_timestamp_internal(buf, l, t, true, false);
246 }
247
248 char *format_timestamp_us(char *buf, size_t l, usec_t t) {
249 return format_timestamp_internal(buf, l, t, false, true);
250 }
251
252 char *format_timestamp_us_utc(char *buf, size_t l, usec_t t) {
253 return format_timestamp_internal(buf, l, t, true, true);
254 }
255
256 char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
257 const char *s;
258 usec_t n, d;
259
260 if (t <= 0 || t == USEC_INFINITY)
261 return NULL;
262
263 n = now(CLOCK_REALTIME);
264 if (n > t) {
265 d = n - t;
266 s = "ago";
267 } else {
268 d = t - n;
269 s = "left";
270 }
271
272 if (d >= USEC_PER_YEAR)
273 snprintf(buf, l, USEC_FMT " years " USEC_FMT " months %s",
274 d / USEC_PER_YEAR,
275 (d % USEC_PER_YEAR) / USEC_PER_MONTH, s);
276 else if (d >= USEC_PER_MONTH)
277 snprintf(buf, l, USEC_FMT " months " USEC_FMT " days %s",
278 d / USEC_PER_MONTH,
279 (d % USEC_PER_MONTH) / USEC_PER_DAY, s);
280 else if (d >= USEC_PER_WEEK)
281 snprintf(buf, l, USEC_FMT " weeks " USEC_FMT " days %s",
282 d / USEC_PER_WEEK,
283 (d % USEC_PER_WEEK) / USEC_PER_DAY, s);
284 else if (d >= 2*USEC_PER_DAY)
285 snprintf(buf, l, USEC_FMT " days %s", d / USEC_PER_DAY, s);
286 else if (d >= 25*USEC_PER_HOUR)
287 snprintf(buf, l, "1 day " USEC_FMT "h %s",
288 (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
289 else if (d >= 6*USEC_PER_HOUR)
290 snprintf(buf, l, USEC_FMT "h %s",
291 d / USEC_PER_HOUR, s);
292 else if (d >= USEC_PER_HOUR)
293 snprintf(buf, l, USEC_FMT "h " USEC_FMT "min %s",
294 d / USEC_PER_HOUR,
295 (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
296 else if (d >= 5*USEC_PER_MINUTE)
297 snprintf(buf, l, USEC_FMT "min %s",
298 d / USEC_PER_MINUTE, s);
299 else if (d >= USEC_PER_MINUTE)
300 snprintf(buf, l, USEC_FMT "min " USEC_FMT "s %s",
301 d / USEC_PER_MINUTE,
302 (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
303 else if (d >= USEC_PER_SEC)
304 snprintf(buf, l, USEC_FMT "s %s",
305 d / USEC_PER_SEC, s);
306 else if (d >= USEC_PER_MSEC)
307 snprintf(buf, l, USEC_FMT "ms %s",
308 d / USEC_PER_MSEC, s);
309 else if (d > 0)
310 snprintf(buf, l, USEC_FMT"us %s",
311 d, s);
312 else
313 snprintf(buf, l, "now");
314
315 buf[l-1] = 0;
316 return buf;
317 }
318
319 char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
320 static const struct {
321 const char *suffix;
322 usec_t usec;
323 } table[] = {
324 { "y", USEC_PER_YEAR },
325 { "month", USEC_PER_MONTH },
326 { "w", USEC_PER_WEEK },
327 { "d", USEC_PER_DAY },
328 { "h", USEC_PER_HOUR },
329 { "min", USEC_PER_MINUTE },
330 { "s", USEC_PER_SEC },
331 { "ms", USEC_PER_MSEC },
332 { "us", 1 },
333 };
334
335 unsigned i;
336 char *p = buf;
337 bool something = false;
338
339 assert(buf);
340 assert(l > 0);
341
342 if (t == USEC_INFINITY) {
343 strncpy(p, "infinity", l-1);
344 p[l-1] = 0;
345 return p;
346 }
347
348 if (t <= 0) {
349 strncpy(p, "0", l-1);
350 p[l-1] = 0;
351 return p;
352 }
353
354 /* The result of this function can be parsed with parse_sec */
355
356 for (i = 0; i < ELEMENTSOF(table); i++) {
357 int k = 0;
358 size_t n;
359 bool done = false;
360 usec_t a, b;
361
362 if (t <= 0)
363 break;
364
365 if (t < accuracy && something)
366 break;
367
368 if (t < table[i].usec)
369 continue;
370
371 if (l <= 1)
372 break;
373
374 a = t / table[i].usec;
375 b = t % table[i].usec;
376
377 /* Let's see if we should shows this in dot notation */
378 if (t < USEC_PER_MINUTE && b > 0) {
379 usec_t cc;
380 int j;
381
382 j = 0;
383 for (cc = table[i].usec; cc > 1; cc /= 10)
384 j++;
385
386 for (cc = accuracy; cc > 1; cc /= 10) {
387 b /= 10;
388 j--;
389 }
390
391 if (j > 0) {
392 k = snprintf(p, l,
393 "%s"USEC_FMT".%0*llu%s",
394 p > buf ? " " : "",
395 a,
396 j,
397 (unsigned long long) b,
398 table[i].suffix);
399
400 t = 0;
401 done = true;
402 }
403 }
404
405 /* No? Then let's show it normally */
406 if (!done) {
407 k = snprintf(p, l,
408 "%s"USEC_FMT"%s",
409 p > buf ? " " : "",
410 a,
411 table[i].suffix);
412
413 t = b;
414 }
415
416 n = MIN((size_t) k, l);
417
418 l -= n;
419 p += n;
420
421 something = true;
422 }
423
424 *p = 0;
425
426 return buf;
427 }
428
429 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
430
431 assert(f);
432 assert(name);
433 assert(t);
434
435 if (!dual_timestamp_is_set(t))
436 return;
437
438 fprintf(f, "%s="USEC_FMT" "USEC_FMT"\n",
439 name,
440 t->realtime,
441 t->monotonic);
442 }
443
444 int dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
445 unsigned long long a, b;
446
447 assert(value);
448 assert(t);
449
450 if (sscanf(value, "%llu %llu", &a, &b) != 2) {
451 log_debug("Failed to parse dual timestamp value \"%s\": %m", value);
452 return -EINVAL;
453 }
454
455 t->realtime = a;
456 t->monotonic = b;
457
458 return 0;
459 }
460
461 int timestamp_deserialize(const char *value, usec_t *timestamp) {
462 int r;
463
464 assert(value);
465
466 r = safe_atou64(value, timestamp);
467 if (r < 0)
468 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
469
470 return r;
471 }
472
473 int parse_timestamp(const char *t, usec_t *usec) {
474 static const struct {
475 const char *name;
476 const int nr;
477 } day_nr[] = {
478 { "Sunday", 0 },
479 { "Sun", 0 },
480 { "Monday", 1 },
481 { "Mon", 1 },
482 { "Tuesday", 2 },
483 { "Tue", 2 },
484 { "Wednesday", 3 },
485 { "Wed", 3 },
486 { "Thursday", 4 },
487 { "Thu", 4 },
488 { "Friday", 5 },
489 { "Fri", 5 },
490 { "Saturday", 6 },
491 { "Sat", 6 },
492 };
493
494 const char *k;
495 const char *utc;
496 struct tm tm, copy;
497 time_t x;
498 usec_t x_usec, plus = 0, minus = 0, ret;
499 int r, weekday = -1;
500 unsigned i;
501
502 /*
503 * Allowed syntaxes:
504 *
505 * 2012-09-22 16:34:22
506 * 2012-09-22 16:34 (seconds will be set to 0)
507 * 2012-09-22 (time will be set to 00:00:00)
508 * 16:34:22 (date will be set to today)
509 * 16:34 (date will be set to today, seconds to 0)
510 * now
511 * yesterday (time is set to 00:00:00)
512 * today (time is set to 00:00:00)
513 * tomorrow (time is set to 00:00:00)
514 * +5min
515 * -5days
516 * @2147483647 (seconds since epoch)
517 *
518 */
519
520 assert(t);
521 assert(usec);
522
523 if (t[0] == '@')
524 return parse_sec(t + 1, usec);
525
526 ret = now(CLOCK_REALTIME);
527
528 if (streq(t, "now"))
529 goto finish;
530
531 else if (t[0] == '+') {
532 r = parse_sec(t+1, &plus);
533 if (r < 0)
534 return r;
535
536 goto finish;
537
538 } else if (t[0] == '-') {
539 r = parse_sec(t+1, &minus);
540 if (r < 0)
541 return r;
542
543 goto finish;
544
545 } else if ((k = endswith(t, " ago"))) {
546 t = strndupa(t, k - t);
547
548 r = parse_sec(t, &minus);
549 if (r < 0)
550 return r;
551
552 goto finish;
553
554 } else if ((k = endswith(t, " left"))) {
555 t = strndupa(t, k - t);
556
557 r = parse_sec(t, &plus);
558 if (r < 0)
559 return r;
560
561 goto finish;
562 }
563
564 utc = endswith_no_case(t, " UTC");
565 if (utc)
566 t = strndupa(t, utc - t);
567
568 x = ret / USEC_PER_SEC;
569 x_usec = 0;
570
571 assert_se(localtime_or_gmtime_r(&x, &tm, utc));
572 tm.tm_isdst = -1;
573
574 if (streq(t, "today")) {
575 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
576 goto from_tm;
577
578 } else if (streq(t, "yesterday")) {
579 tm.tm_mday--;
580 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
581 goto from_tm;
582
583 } else if (streq(t, "tomorrow")) {
584 tm.tm_mday++;
585 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
586 goto from_tm;
587 }
588
589
590 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
591 size_t skip;
592
593 if (!startswith_no_case(t, day_nr[i].name))
594 continue;
595
596 skip = strlen(day_nr[i].name);
597 if (t[skip] != ' ')
598 continue;
599
600 weekday = day_nr[i].nr;
601 t += skip + 1;
602 break;
603 }
604
605 copy = tm;
606 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
607 if (k) {
608 if (*k == '.')
609 goto parse_usec;
610 else if (*k == 0)
611 goto from_tm;
612 }
613
614 tm = copy;
615 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
616 if (k) {
617 if (*k == '.')
618 goto parse_usec;
619 else if (*k == 0)
620 goto from_tm;
621 }
622
623 tm = copy;
624 k = strptime(t, "%y-%m-%d %H:%M", &tm);
625 if (k && *k == 0) {
626 tm.tm_sec = 0;
627 goto from_tm;
628 }
629
630 tm = copy;
631 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
632 if (k && *k == 0) {
633 tm.tm_sec = 0;
634 goto from_tm;
635 }
636
637 tm = copy;
638 k = strptime(t, "%y-%m-%d", &tm);
639 if (k && *k == 0) {
640 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
641 goto from_tm;
642 }
643
644 tm = copy;
645 k = strptime(t, "%Y-%m-%d", &tm);
646 if (k && *k == 0) {
647 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
648 goto from_tm;
649 }
650
651 tm = copy;
652 k = strptime(t, "%H:%M:%S", &tm);
653 if (k) {
654 if (*k == '.')
655 goto parse_usec;
656 else if (*k == 0)
657 goto from_tm;
658 }
659
660 tm = copy;
661 k = strptime(t, "%H:%M", &tm);
662 if (k && *k == 0) {
663 tm.tm_sec = 0;
664 goto from_tm;
665 }
666
667 return -EINVAL;
668
669 parse_usec:
670 {
671 unsigned add;
672
673 k++;
674 r = parse_fractional_part_u(&k, 6, &add);
675 if (r < 0)
676 return -EINVAL;
677
678 if (*k)
679 return -EINVAL;
680
681 x_usec = add;
682
683 }
684
685 from_tm:
686 x = mktime_or_timegm(&tm, utc);
687 if (x == (time_t) -1)
688 return -EINVAL;
689
690 if (weekday >= 0 && tm.tm_wday != weekday)
691 return -EINVAL;
692
693 ret = (usec_t) x * USEC_PER_SEC + x_usec;
694
695 finish:
696 ret += plus;
697 if (ret > minus)
698 ret -= minus;
699 else
700 ret = 0;
701
702 *usec = ret;
703
704 return 0;
705 }
706
707 static char* extract_multiplier(char *p, usec_t *multiplier) {
708 static const struct {
709 const char *suffix;
710 usec_t usec;
711 } table[] = {
712 { "seconds", USEC_PER_SEC },
713 { "second", USEC_PER_SEC },
714 { "sec", USEC_PER_SEC },
715 { "s", USEC_PER_SEC },
716 { "minutes", USEC_PER_MINUTE },
717 { "minute", USEC_PER_MINUTE },
718 { "min", USEC_PER_MINUTE },
719 { "months", USEC_PER_MONTH },
720 { "month", USEC_PER_MONTH },
721 { "M", USEC_PER_MONTH },
722 { "msec", USEC_PER_MSEC },
723 { "ms", USEC_PER_MSEC },
724 { "m", USEC_PER_MINUTE },
725 { "hours", USEC_PER_HOUR },
726 { "hour", USEC_PER_HOUR },
727 { "hr", USEC_PER_HOUR },
728 { "h", USEC_PER_HOUR },
729 { "days", USEC_PER_DAY },
730 { "day", USEC_PER_DAY },
731 { "d", USEC_PER_DAY },
732 { "weeks", USEC_PER_WEEK },
733 { "week", USEC_PER_WEEK },
734 { "w", USEC_PER_WEEK },
735 { "years", USEC_PER_YEAR },
736 { "year", USEC_PER_YEAR },
737 { "y", USEC_PER_YEAR },
738 { "usec", 1ULL },
739 { "us", 1ULL },
740 };
741 unsigned i;
742
743 for (i = 0; i < ELEMENTSOF(table); i++) {
744 char *e;
745
746 e = startswith(p, table[i].suffix);
747 if (e) {
748 *multiplier = table[i].usec;
749 return e;
750 }
751 }
752
753 return p;
754 }
755
756 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
757 const char *p, *s;
758 usec_t r = 0;
759 bool something = false;
760
761 assert(t);
762 assert(usec);
763 assert(default_unit > 0);
764
765 p = t;
766
767 p += strspn(p, WHITESPACE);
768 s = startswith(p, "infinity");
769 if (s) {
770 s += strspn(s, WHITESPACE);
771 if (*s != 0)
772 return -EINVAL;
773
774 *usec = USEC_INFINITY;
775 return 0;
776 }
777
778 for (;;) {
779 long long l, z = 0;
780 char *e;
781 unsigned n = 0;
782 usec_t multiplier = default_unit, k;
783
784 p += strspn(p, WHITESPACE);
785
786 if (*p == 0) {
787 if (!something)
788 return -EINVAL;
789
790 break;
791 }
792
793 errno = 0;
794 l = strtoll(p, &e, 10);
795 if (errno > 0)
796 return -errno;
797 if (l < 0)
798 return -ERANGE;
799
800 if (*e == '.') {
801 char *b = e + 1;
802
803 errno = 0;
804 z = strtoll(b, &e, 10);
805 if (errno > 0)
806 return -errno;
807
808 if (z < 0)
809 return -ERANGE;
810
811 if (e == b)
812 return -EINVAL;
813
814 n = e - b;
815
816 } else if (e == p)
817 return -EINVAL;
818
819 e += strspn(e, WHITESPACE);
820 p = extract_multiplier(e, &multiplier);
821
822 something = true;
823
824 k = (usec_t) z * multiplier;
825
826 for (; n > 0; n--)
827 k /= 10;
828
829 r += (usec_t) l * multiplier + k;
830 }
831
832 *usec = r;
833
834 return 0;
835 }
836
837 int parse_sec(const char *t, usec_t *usec) {
838 return parse_time(t, usec, USEC_PER_SEC);
839 }
840
841 int parse_nsec(const char *t, nsec_t *nsec) {
842 static const struct {
843 const char *suffix;
844 nsec_t nsec;
845 } table[] = {
846 { "seconds", NSEC_PER_SEC },
847 { "second", NSEC_PER_SEC },
848 { "sec", NSEC_PER_SEC },
849 { "s", NSEC_PER_SEC },
850 { "minutes", NSEC_PER_MINUTE },
851 { "minute", NSEC_PER_MINUTE },
852 { "min", NSEC_PER_MINUTE },
853 { "months", NSEC_PER_MONTH },
854 { "month", NSEC_PER_MONTH },
855 { "msec", NSEC_PER_MSEC },
856 { "ms", NSEC_PER_MSEC },
857 { "m", NSEC_PER_MINUTE },
858 { "hours", NSEC_PER_HOUR },
859 { "hour", NSEC_PER_HOUR },
860 { "hr", NSEC_PER_HOUR },
861 { "h", NSEC_PER_HOUR },
862 { "days", NSEC_PER_DAY },
863 { "day", NSEC_PER_DAY },
864 { "d", NSEC_PER_DAY },
865 { "weeks", NSEC_PER_WEEK },
866 { "week", NSEC_PER_WEEK },
867 { "w", NSEC_PER_WEEK },
868 { "years", NSEC_PER_YEAR },
869 { "year", NSEC_PER_YEAR },
870 { "y", NSEC_PER_YEAR },
871 { "usec", NSEC_PER_USEC },
872 { "us", NSEC_PER_USEC },
873 { "nsec", 1ULL },
874 { "ns", 1ULL },
875 { "", 1ULL }, /* default is nsec */
876 };
877
878 const char *p, *s;
879 nsec_t r = 0;
880 bool something = false;
881
882 assert(t);
883 assert(nsec);
884
885 p = t;
886
887 p += strspn(p, WHITESPACE);
888 s = startswith(p, "infinity");
889 if (s) {
890 s += strspn(s, WHITESPACE);
891 if (*s != 0)
892 return -EINVAL;
893
894 *nsec = NSEC_INFINITY;
895 return 0;
896 }
897
898 for (;;) {
899 long long l, z = 0;
900 char *e;
901 unsigned i, n = 0;
902
903 p += strspn(p, WHITESPACE);
904
905 if (*p == 0) {
906 if (!something)
907 return -EINVAL;
908
909 break;
910 }
911
912 errno = 0;
913 l = strtoll(p, &e, 10);
914
915 if (errno > 0)
916 return -errno;
917
918 if (l < 0)
919 return -ERANGE;
920
921 if (*e == '.') {
922 char *b = e + 1;
923
924 errno = 0;
925 z = strtoll(b, &e, 10);
926 if (errno > 0)
927 return -errno;
928
929 if (z < 0)
930 return -ERANGE;
931
932 if (e == b)
933 return -EINVAL;
934
935 n = e - b;
936
937 } else if (e == p)
938 return -EINVAL;
939
940 e += strspn(e, WHITESPACE);
941
942 for (i = 0; i < ELEMENTSOF(table); i++)
943 if (startswith(e, table[i].suffix)) {
944 nsec_t k = (nsec_t) z * table[i].nsec;
945
946 for (; n > 0; n--)
947 k /= 10;
948
949 r += (nsec_t) l * table[i].nsec + k;
950 p = e + strlen(table[i].suffix);
951
952 something = true;
953 break;
954 }
955
956 if (i >= ELEMENTSOF(table))
957 return -EINVAL;
958
959 }
960
961 *nsec = r;
962
963 return 0;
964 }
965
966 bool ntp_synced(void) {
967 struct timex txc = {};
968
969 if (adjtimex(&txc) < 0)
970 return false;
971
972 if (txc.status & STA_UNSYNC)
973 return false;
974
975 return true;
976 }
977
978 int get_timezones(char ***ret) {
979 _cleanup_fclose_ FILE *f = NULL;
980 _cleanup_strv_free_ char **zones = NULL;
981 size_t n_zones = 0, n_allocated = 0;
982
983 assert(ret);
984
985 zones = strv_new("UTC", NULL);
986 if (!zones)
987 return -ENOMEM;
988
989 n_allocated = 2;
990 n_zones = 1;
991
992 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
993 if (f) {
994 char l[LINE_MAX];
995
996 FOREACH_LINE(l, f, return -errno) {
997 char *p, *w;
998 size_t k;
999
1000 p = strstrip(l);
1001
1002 if (isempty(p) || *p == '#')
1003 continue;
1004
1005 /* Skip over country code */
1006 p += strcspn(p, WHITESPACE);
1007 p += strspn(p, WHITESPACE);
1008
1009 /* Skip over coordinates */
1010 p += strcspn(p, WHITESPACE);
1011 p += strspn(p, WHITESPACE);
1012
1013 /* Found timezone name */
1014 k = strcspn(p, WHITESPACE);
1015 if (k <= 0)
1016 continue;
1017
1018 w = strndup(p, k);
1019 if (!w)
1020 return -ENOMEM;
1021
1022 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1023 free(w);
1024 return -ENOMEM;
1025 }
1026
1027 zones[n_zones++] = w;
1028 zones[n_zones] = NULL;
1029 }
1030
1031 strv_sort(zones);
1032
1033 } else if (errno != ENOENT)
1034 return -errno;
1035
1036 *ret = zones;
1037 zones = NULL;
1038
1039 return 0;
1040 }
1041
1042 bool timezone_is_valid(const char *name) {
1043 bool slash = false;
1044 const char *p, *t;
1045 struct stat st;
1046
1047 if (isempty(name))
1048 return false;
1049
1050 if (name[0] == '/')
1051 return false;
1052
1053 for (p = name; *p; p++) {
1054 if (!(*p >= '0' && *p <= '9') &&
1055 !(*p >= 'a' && *p <= 'z') &&
1056 !(*p >= 'A' && *p <= 'Z') &&
1057 !(*p == '-' || *p == '_' || *p == '+' || *p == '/'))
1058 return false;
1059
1060 if (*p == '/') {
1061
1062 if (slash)
1063 return false;
1064
1065 slash = true;
1066 } else
1067 slash = false;
1068 }
1069
1070 if (slash)
1071 return false;
1072
1073 t = strjoina("/usr/share/zoneinfo/", name);
1074 if (stat(t, &st) < 0)
1075 return false;
1076
1077 if (!S_ISREG(st.st_mode))
1078 return false;
1079
1080 return true;
1081 }
1082
1083 bool clock_boottime_supported(void) {
1084 static int supported = -1;
1085
1086 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1087
1088 if (supported < 0) {
1089 int fd;
1090
1091 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1092 if (fd < 0)
1093 supported = false;
1094 else {
1095 safe_close(fd);
1096 supported = true;
1097 }
1098 }
1099
1100 return supported;
1101 }
1102
1103 clockid_t clock_boottime_or_monotonic(void) {
1104 if (clock_boottime_supported())
1105 return CLOCK_BOOTTIME;
1106 else
1107 return CLOCK_MONOTONIC;
1108 }
1109
1110 int get_timezone(char **tz) {
1111 _cleanup_free_ char *t = NULL;
1112 const char *e;
1113 char *z;
1114 int r;
1115
1116 r = readlink_malloc("/etc/localtime", &t);
1117 if (r < 0)
1118 return r; /* returns EINVAL if not a symlink */
1119
1120 e = path_startswith(t, "/usr/share/zoneinfo/");
1121 if (!e)
1122 e = path_startswith(t, "../usr/share/zoneinfo/");
1123 if (!e)
1124 return -EINVAL;
1125
1126 if (!timezone_is_valid(e))
1127 return -EINVAL;
1128
1129 z = strdup(e);
1130 if (!z)
1131 return -ENOMEM;
1132
1133 *tz = z;
1134 return 0;
1135 }
1136
1137 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1138 return utc ? timegm(tm) : mktime(tm);
1139 }
1140
1141 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1142 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1143 }
1144
1145 unsigned long usec_to_jiffies(usec_t u) {
1146 static thread_local unsigned long hz = 0;
1147 long r;
1148
1149 if (hz == 0) {
1150 r = sysconf(_SC_CLK_TCK);
1151
1152 assert(r > 0);
1153 hz = (unsigned long) r;
1154 }
1155
1156 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1157 }