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