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