]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/time-util.c
Merge pull request #6944 from poettering/suspend-fix
[thirdparty/systemd.git] / src / basic / time-util.c
CommitLineData
9a98c7a1
LP
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
11c3a366
TA
20#include <errno.h>
21#include <limits.h>
22#include <stdlib.h>
9a98c7a1 23#include <string.h>
48d26c01 24#include <sys/mman.h>
11c3a366
TA
25#include <sys/stat.h>
26#include <sys/time.h>
77ff2de9 27#include <sys/timerfd.h>
07630cea 28#include <sys/timex.h>
11c3a366
TA
29#include <sys/types.h>
30#include <unistd.h>
9a98c7a1 31
b5efdb8a 32#include "alloc-util.h"
3ffd4af2 33#include "fd-util.h"
0d39fa9c 34#include "fileio.h"
f4f15635 35#include "fs-util.h"
11c3a366
TA
36#include "log.h"
37#include "macro.h"
93cc7779
TA
38#include "parse-util.h"
39#include "path-util.h"
07630cea 40#include "string-util.h"
75683450 41#include "strv.h"
07630cea 42#include "time-util.h"
9a98c7a1 43
32c1f5a5
LP
44static 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
bdf19f8f 49 * those archs. */
32c1f5a5
LP
50
51 switch (c) {
52
53 case CLOCK_BOOTTIME_ALARM:
bdf19f8f 54 return CLOCK_BOOTTIME;
32c1f5a5
LP
55
56 case CLOCK_REALTIME_ALARM:
57 return CLOCK_REALTIME;
58
59 default:
60 return c;
61 }
62}
63
9a98c7a1
LP
64usec_t now(clockid_t clock_id) {
65 struct timespec ts;
66
32c1f5a5 67 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
9a98c7a1
LP
68
69 return timespec_load(&ts);
70}
71
45d7a8bb
LP
72nsec_t now_nsec(clockid_t clock_id) {
73 struct timespec ts;
74
32c1f5a5 75 assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
45d7a8bb
LP
76
77 return timespec_load_nsec(&ts);
78}
79
9a98c7a1
LP
80dual_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
fe624c4c
LP
89triple_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
9a98c7a1
LP
99dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
100 int64_t delta;
101 assert(ts);
102
75a5f1d8
LP
103 if (u == USEC_INFINITY || u <= 0) {
104 ts->realtime = ts->monotonic = u;
cae0c5e0
LP
105 return ts;
106 }
107
9a98c7a1
LP
108 ts->realtime = u;
109
75a5f1d8 110 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
54d8ef14 111 ts->monotonic = usec_sub_signed(now(CLOCK_MONOTONIC), delta);
9a98c7a1
LP
112
113 return ts;
114}
115
fe624c4c
LP
116triple_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;
54d8ef14
LP
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;
fe624c4c
LP
130
131 return ts;
132}
133
cae0c5e0
LP
134dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
135 int64_t delta;
136 assert(ts);
137
3a43da28
KS
138 if (u == USEC_INFINITY) {
139 ts->realtime = ts->monotonic = USEC_INFINITY;
cae0c5e0
LP
140 return ts;
141 }
142
143 ts->monotonic = u;
144 delta = (int64_t) now(CLOCK_MONOTONIC) - (int64_t) u;
54d8ef14 145 ts->realtime = usec_sub_signed(now(CLOCK_REALTIME), delta);
cae0c5e0
LP
146
147 return ts;
148}
149
fbe55073
LP
150dual_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 }
fbe55073 157
0345d252 158 dual_timestamp_get(ts);
fbe55073 159 delta = (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u;
54d8ef14
LP
160 ts->realtime = usec_sub_signed(ts->realtime, delta);
161 ts->monotonic = usec_sub_signed(ts->monotonic, delta);
fbe55073
LP
162
163 return ts;
164}
165
fe624c4c
LP
166usec_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
9a98c7a1
LP
186usec_t timespec_load(const struct timespec *ts) {
187 assert(ts);
188
c477ff14 189 if (ts->tv_sec < 0 || ts->tv_nsec < 0)
3a43da28 190 return USEC_INFINITY;
9a98c7a1
LP
191
192 if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
3a43da28 193 return USEC_INFINITY;
9a98c7a1
LP
194
195 return
196 (usec_t) ts->tv_sec * USEC_PER_SEC +
197 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
198}
199
3a730176 200nsec_t timespec_load_nsec(const struct timespec *ts) {
45d7a8bb
LP
201 assert(ts);
202
c477ff14 203 if (ts->tv_sec < 0 || ts->tv_nsec < 0)
45d7a8bb
LP
204 return NSEC_INFINITY;
205
a2daa2f0
ZJS
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;
45d7a8bb
LP
210}
211
9a98c7a1
LP
212struct timespec *timespec_store(struct timespec *ts, usec_t u) {
213 assert(ts);
214
f977849c 215 if (u == USEC_INFINITY ||
d201d908 216 u / USEC_PER_SEC >= TIME_T_MAX) {
9a98c7a1
LP
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
228usec_t timeval_load(const struct timeval *tv) {
229 assert(tv);
230
c477ff14 231 if (tv->tv_sec < 0 || tv->tv_usec < 0)
3a43da28 232 return USEC_INFINITY;
9a98c7a1
LP
233
234 if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
3a43da28 235 return USEC_INFINITY;
9a98c7a1
LP
236
237 return
238 (usec_t) tv->tv_sec * USEC_PER_SEC +
239 (usec_t) tv->tv_usec;
240}
241
242struct timeval *timeval_store(struct timeval *tv, usec_t u) {
243 assert(tv);
244
68bdd2d2 245 if (u == USEC_INFINITY ||
f977849c 246 u / USEC_PER_SEC > TIME_T_MAX) {
9a98c7a1
LP
247 tv->tv_sec = (time_t) -1;
248 tv->tv_usec = (suseconds_t) -1;
4d89874a
ZJS
249 } else {
250 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
251 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
9a98c7a1
LP
252 }
253
9a98c7a1
LP
254 return tv;
255}
256
21b3a0fc
LP
257static 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
9a98c7a1
LP
276 struct tm tm;
277 time_t sec;
21b3a0fc 278 size_t n;
9a98c7a1
LP
279
280 assert(buf);
9a98c7a1 281
21b3a0fc
LP
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. */
3a43da28 290 if (t <= 0 || t == USEC_INFINITY)
21b3a0fc
LP
291 return NULL; /* Timestamp is unset */
292
1bb4b028
LP
293 /* Let's not format times with years > 9999 */
294 if (t > USEC_TIMESTAMP_FORMATTABLE_MAX)
295 return NULL;
296
21b3a0fc 297 sec = (time_t) (t / USEC_PER_SEC); /* Round down */
21b3a0fc
LP
298
299 if (!localtime_or_gmtime_r(&sec, &tm, utc))
9a98c7a1
LP
300 return NULL;
301
21b3a0fc
LP
302 /* Start with the week day */
303 assert((size_t) tm.tm_wday < ELEMENTSOF(weekdays));
304 memcpy(buf, weekdays[tm.tm_wday], 4);
9a98c7a1 305
21b3a0fc
LP
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 */
0056086a 309
21b3a0fc 310 /* Append the microseconds part, if that's requested */
0056086a 311 if (us) {
21b3a0fc
LP
312 n = strlen(buf);
313 if (n + 8 > l)
314 return NULL; /* Microseconds part doesn't fit. */
315
70887c5f 316 sprintf(buf + n, ".%06"PRI_USEC, t % USEC_PER_SEC);
21b3a0fc
LP
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 }
0056086a 348 }
9a98c7a1
LP
349
350 return buf;
351}
352
a62e83b4 353char *format_timestamp(char *buf, size_t l, usec_t t) {
0056086a 354 return format_timestamp_internal(buf, l, t, false, false);
a62e83b4
JS
355}
356
5ab99e07 357char *format_timestamp_utc(char *buf, size_t l, usec_t t) {
0056086a 358 return format_timestamp_internal(buf, l, t, true, false);
f02d8367
ZJS
359}
360
5ab99e07 361char *format_timestamp_us(char *buf, size_t l, usec_t t) {
0056086a 362 return format_timestamp_internal(buf, l, t, false, true);
5ab99e07
LP
363}
364
365char *format_timestamp_us_utc(char *buf, size_t l, usec_t t) {
0056086a 366 return format_timestamp_internal(buf, l, t, true, true);
5ab99e07
LP
367}
368
bbb8486e 369char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
1fcf71f5 370 const char *s;
9a98c7a1
LP
371 usec_t n, d;
372
65de0395 373 if (t <= 0 || t == USEC_INFINITY)
9a98c7a1
LP
374 return NULL;
375
65de0395 376 n = now(CLOCK_REALTIME);
1fcf71f5
LP
377 if (n > t) {
378 d = n - t;
379 s = "ago";
380 } else {
381 d = t - n;
382 s = "left";
383 }
9a98c7a1
LP
384
385 if (d >= USEC_PER_YEAR)
609e002e 386 snprintf(buf, l, USEC_FMT " years " USEC_FMT " months %s",
de0671ee
ZJS
387 d / USEC_PER_YEAR,
388 (d % USEC_PER_YEAR) / USEC_PER_MONTH, s);
9a98c7a1 389 else if (d >= USEC_PER_MONTH)
609e002e 390 snprintf(buf, l, USEC_FMT " months " USEC_FMT " days %s",
de0671ee
ZJS
391 d / USEC_PER_MONTH,
392 (d % USEC_PER_MONTH) / USEC_PER_DAY, s);
9a98c7a1 393 else if (d >= USEC_PER_WEEK)
609e002e 394 snprintf(buf, l, USEC_FMT " weeks " USEC_FMT " days %s",
de0671ee
ZJS
395 d / USEC_PER_WEEK,
396 (d % USEC_PER_WEEK) / USEC_PER_DAY, s);
9a98c7a1 397 else if (d >= 2*USEC_PER_DAY)
609e002e 398 snprintf(buf, l, USEC_FMT " days %s", d / USEC_PER_DAY, s);
9a98c7a1 399 else if (d >= 25*USEC_PER_HOUR)
609e002e 400 snprintf(buf, l, "1 day " USEC_FMT "h %s",
de0671ee 401 (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
9a98c7a1 402 else if (d >= 6*USEC_PER_HOUR)
609e002e 403 snprintf(buf, l, USEC_FMT "h %s",
de0671ee 404 d / USEC_PER_HOUR, s);
9a98c7a1 405 else if (d >= USEC_PER_HOUR)
609e002e 406 snprintf(buf, l, USEC_FMT "h " USEC_FMT "min %s",
de0671ee
ZJS
407 d / USEC_PER_HOUR,
408 (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
9a98c7a1 409 else if (d >= 5*USEC_PER_MINUTE)
609e002e 410 snprintf(buf, l, USEC_FMT "min %s",
de0671ee 411 d / USEC_PER_MINUTE, s);
9a98c7a1 412 else if (d >= USEC_PER_MINUTE)
609e002e 413 snprintf(buf, l, USEC_FMT "min " USEC_FMT "s %s",
de0671ee
ZJS
414 d / USEC_PER_MINUTE,
415 (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
9a98c7a1 416 else if (d >= USEC_PER_SEC)
609e002e 417 snprintf(buf, l, USEC_FMT "s %s",
de0671ee 418 d / USEC_PER_SEC, s);
9a98c7a1 419 else if (d >= USEC_PER_MSEC)
609e002e 420 snprintf(buf, l, USEC_FMT "ms %s",
de0671ee 421 d / USEC_PER_MSEC, s);
9a98c7a1 422 else if (d > 0)
de0671ee
ZJS
423 snprintf(buf, l, USEC_FMT"us %s",
424 d, s);
9a98c7a1
LP
425 else
426 snprintf(buf, l, "now");
427
428 buf[l-1] = 0;
429 return buf;
430}
431
2fa4092c 432char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
9a98c7a1
LP
433 static const struct {
434 const char *suffix;
435 usec_t usec;
436 } table[] = {
eb55ec9f
LP
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 },
9a98c7a1
LP
446 };
447
448 unsigned i;
449 char *p = buf;
2fa4092c 450 bool something = false;
9a98c7a1
LP
451
452 assert(buf);
453 assert(l > 0);
454
bb1fada8
LP
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);
7c537b2e
LP
463 p[l-1] = 0;
464 return p;
465 }
466
7f602784 467 /* The result of this function can be parsed with parse_sec */
9a98c7a1
LP
468
469 for (i = 0; i < ELEMENTSOF(table); i++) {
7759ecb2 470 int k = 0;
9a98c7a1 471 size_t n;
2fa4092c
LP
472 bool done = false;
473 usec_t a, b;
474
7c537b2e
LP
475 if (t <= 0)
476 break;
2fa4092c 477
7c537b2e 478 if (t < accuracy && something)
2fa4092c 479 break;
9a98c7a1
LP
480
481 if (t < table[i].usec)
482 continue;
483
484 if (l <= 1)
485 break;
486
2fa4092c
LP
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,
70887c5f 506 "%s"USEC_FMT".%0*"PRI_USEC"%s",
2fa4092c 507 p > buf ? " " : "",
de0671ee 508 a,
2fa4092c 509 j,
70887c5f 510 b,
2fa4092c
LP
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,
de0671ee 521 "%s"USEC_FMT"%s",
2fa4092c 522 p > buf ? " " : "",
de0671ee 523 a,
2fa4092c
LP
524 table[i].suffix);
525
526 t = b;
527 }
528
9a98c7a1
LP
529 n = MIN((size_t) k, l);
530
531 l -= n;
532 p += n;
533
2fa4092c 534 something = true;
9a98c7a1
LP
535 }
536
537 *p = 0;
538
539 return buf;
540}
541
542void 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
de0671ee 551 fprintf(f, "%s="USEC_FMT" "USEC_FMT"\n",
9a98c7a1 552 name,
de0671ee
ZJS
553 t->realtime,
554 t->monotonic);
9a98c7a1
LP
555}
556
e911de99 557int dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
74c5b33b 558 uint64_t a, b;
9c0565b2 559 int r, pos;
9a98c7a1
LP
560
561 assert(value);
562 assert(t);
563
9c0565b2
ZJS
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);
e911de99 575 return -EINVAL;
9a98c7a1 576 }
e911de99 577
9c0565b2
ZJS
578 if (value[pos] != '\0')
579 /* trailing garbage */
580 return -EINVAL;
581
e911de99
LP
582 t->realtime = a;
583 t->monotonic = b;
584
585 return 0;
9a98c7a1
LP
586}
587
b895a735 588int timestamp_deserialize(const char *value, usec_t *timestamp) {
ebf30a08
AK
589 int r;
590
591 assert(value);
592
593 r = safe_atou64(value, timestamp);
ebf30a08 594 if (r < 0)
b895a735 595 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
ebf30a08
AK
596
597 return r;
598}
599
48d26c01 600static int parse_timestamp_impl(const char *t, usec_t *usec, bool with_tz) {
92134489
LP
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
48d26c01 621 const char *k, *utc = NULL, *tzn = NULL;
9a98c7a1
LP
622 struct tm tm, copy;
623 time_t x;
e4eaf99a 624 usec_t x_usec, plus = 0, minus = 0, ret;
21b3a0fc 625 int r, weekday = -1, dst = -1;
92134489 626 unsigned i;
9a98c7a1
LP
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
5ba6e094 642 * @2147483647 (seconds since epoch)
9a98c7a1
LP
643 *
644 */
645
646 assert(t);
647 assert(usec);
648
48d26c01 649 if (t[0] == '@' && !with_tz)
e4eaf99a 650 return parse_sec(t + 1, usec);
9a98c7a1 651
e4eaf99a 652 ret = now(CLOCK_REALTIME);
9a98c7a1 653
48d26c01
IK
654 if (!with_tz) {
655 if (streq(t, "now"))
656 goto finish;
9a98c7a1 657
48d26c01
IK
658 else if (t[0] == '+') {
659 r = parse_sec(t+1, &plus);
660 if (r < 0)
661 return r;
9a98c7a1 662
48d26c01 663 goto finish;
9a98c7a1 664
48d26c01
IK
665 } else if (t[0] == '-') {
666 r = parse_sec(t+1, &minus);
667 if (r < 0)
668 return r;
9a98c7a1 669
48d26c01 670 goto finish;
decad910 671
48d26c01
IK
672 } else if ((k = endswith(t, " ago"))) {
673 t = strndupa(t, k - t);
decad910 674
48d26c01
IK
675 r = parse_sec(t, &minus);
676 if (r < 0)
677 return r;
decad910 678
48d26c01 679 goto finish;
1fcf71f5 680
48d26c01
IK
681 } else if ((k = endswith(t, " left"))) {
682 t = strndupa(t, k - t);
1fcf71f5 683
48d26c01
IK
684 r = parse_sec(t, &plus);
685 if (r < 0)
686 return r;
1fcf71f5 687
48d26c01
IK
688 goto finish;
689 }
9a98c7a1 690
48d26c01
IK
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;
21b3a0fc 698
48d26c01 699 tzset();
21b3a0fc 700
48d26c01
IK
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. */
e4eaf99a 706
48d26c01 707 for (j = 0; j <= 1; j++) {
21b3a0fc 708
48d26c01
IK
709 if (isempty(tzname[j]))
710 continue;
21b3a0fc 711
48d26c01
IK
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;
21b3a0fc 719
48d26c01
IK
720 break;
721 }
21b3a0fc 722
48d26c01
IK
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 }
21b3a0fc
LP
729 }
730 }
731
732 x = (time_t) (ret / USEC_PER_SEC);
e4eaf99a
HV
733 x_usec = 0;
734
21b3a0fc
LP
735 if (!localtime_or_gmtime_r(&x, &tm, utc))
736 return -EINVAL;
737
2e72b794
IK
738 tm.tm_isdst = dst;
739 if (!with_tz && tzn)
740 tm.tm_zone = tzn;
e4eaf99a
HV
741
742 if (streq(t, "today")) {
743 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
744 goto from_tm;
745
746 } else if (streq(t, "yesterday")) {
313cefa1 747 tm.tm_mday--;
e4eaf99a
HV
748 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
749 goto from_tm;
750
751 } else if (streq(t, "tomorrow")) {
313cefa1 752 tm.tm_mday++;
e4eaf99a
HV
753 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
754 goto from_tm;
755 }
756
92134489
LP
757 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
758 size_t skip;
759
760 if (!startswith_no_case(t, day_nr[i].name))
761 continue;
762
763 skip = strlen(day_nr[i].name);
764 if (t[skip] != ' ')
765 continue;
766
767 weekday = day_nr[i].nr;
768 t += skip + 1;
769 break;
770 }
771
9a98c7a1
LP
772 copy = tm;
773 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
e4eaf99a
HV
774 if (k) {
775 if (*k == '.')
776 goto parse_usec;
777 else if (*k == 0)
778 goto from_tm;
779 }
9a98c7a1
LP
780
781 tm = copy;
782 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
e4eaf99a
HV
783 if (k) {
784 if (*k == '.')
785 goto parse_usec;
786 else if (*k == 0)
787 goto from_tm;
788 }
9a98c7a1
LP
789
790 tm = copy;
791 k = strptime(t, "%y-%m-%d %H:%M", &tm);
792 if (k && *k == 0) {
793 tm.tm_sec = 0;
e4eaf99a 794 goto from_tm;
9a98c7a1
LP
795 }
796
797 tm = copy;
798 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
799 if (k && *k == 0) {
800 tm.tm_sec = 0;
e4eaf99a 801 goto from_tm;
9a98c7a1
LP
802 }
803
804 tm = copy;
805 k = strptime(t, "%y-%m-%d", &tm);
806 if (k && *k == 0) {
807 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
e4eaf99a 808 goto from_tm;
9a98c7a1
LP
809 }
810
811 tm = copy;
812 k = strptime(t, "%Y-%m-%d", &tm);
813 if (k && *k == 0) {
814 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
e4eaf99a 815 goto from_tm;
9a98c7a1
LP
816 }
817
818 tm = copy;
819 k = strptime(t, "%H:%M:%S", &tm);
e4eaf99a
HV
820 if (k) {
821 if (*k == '.')
822 goto parse_usec;
823 else if (*k == 0)
824 goto from_tm;
825 }
9a98c7a1
LP
826
827 tm = copy;
828 k = strptime(t, "%H:%M", &tm);
829 if (k && *k == 0) {
830 tm.tm_sec = 0;
e4eaf99a 831 goto from_tm;
9a98c7a1
LP
832 }
833
834 return -EINVAL;
835
e4eaf99a
HV
836parse_usec:
837 {
436dd70f 838 unsigned add;
e4eaf99a
HV
839
840 k++;
436dd70f
HV
841 r = parse_fractional_part_u(&k, 6, &add);
842 if (r < 0)
e4eaf99a
HV
843 return -EINVAL;
844
436dd70f 845 if (*k)
e4eaf99a
HV
846 return -EINVAL;
847
436dd70f 848 x_usec = add;
e4eaf99a
HV
849 }
850
851from_tm:
214cc95d 852 if (weekday >= 0 && tm.tm_wday != weekday)
68bdd2d2 853 return -EINVAL;
9a98c7a1 854
214cc95d
MH
855 x = mktime_or_timegm(&tm, utc);
856 if (x < 0)
92134489
LP
857 return -EINVAL;
858
68bdd2d2 859 ret = (usec_t) x * USEC_PER_SEC + x_usec;
1bb4b028
LP
860 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
861 return -EINVAL;
9a98c7a1 862
e4eaf99a 863finish:
315782db 864 if (ret + plus < ret) /* overflow? */
68bdd2d2 865 return -EINVAL;
9a98c7a1 866 ret += plus;
1bb4b028
LP
867 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
868 return -EINVAL;
869
68bdd2d2 870 if (ret >= minus)
9a98c7a1
LP
871 ret -= minus;
872 else
68bdd2d2 873 return -EINVAL;
9a98c7a1
LP
874
875 *usec = ret;
876
877 return 0;
878}
879
48d26c01
IK
880typedef struct ParseTimestampResult {
881 usec_t usec;
882 int return_value;
883} ParseTimestampResult;
884
885int parse_timestamp(const char *t, usec_t *usec) {
ff69484a 886 char *last_space, *tz = NULL;
48d26c01
IK
887 ParseTimestampResult *shared, tmp;
888 int r;
889 pid_t pid;
890
891 last_space = strrchr(t, ' ');
a2932a0d 892 if (last_space != NULL && timezone_is_valid(last_space + 1))
ff69484a 893 tz = last_space + 1;
48d26c01 894
ff69484a 895 if (tz == NULL || endswith_no_case(t, " UTC"))
48d26c01
IK
896 return parse_timestamp_impl(t, usec, false);
897
48d26c01
IK
898 shared = mmap(NULL, sizeof *shared, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
899 if (shared == MAP_FAILED)
900 return negative_errno();
901
902 pid = fork();
903
904 if (pid == -1) {
905 int fork_errno = errno;
906 (void) munmap(shared, sizeof *shared);
907 return -fork_errno;
908 }
909
910 if (pid == 0) {
3fd4929b
MH
911 bool with_tz = true;
912
ff69484a 913 if (setenv("TZ", tz, 1) != 0) {
48d26c01
IK
914 shared->return_value = negative_errno();
915 _exit(EXIT_FAILURE);
916 }
917
918 tzset();
919
3fd4929b
MH
920 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
921 * Otherwise just cut it off */
922 with_tz = !STR_IN_SET(tz, tzname[0], tzname[1]);
923
924 /*cut off the timezone if we dont need it*/
925 if (with_tz)
926 t = strndupa(t, last_space - t);
927
928 shared->return_value = parse_timestamp_impl(t, &shared->usec, with_tz);
48d26c01
IK
929
930 _exit(EXIT_SUCCESS);
931 }
932
933 r = wait_for_terminate(pid, NULL);
934 if (r < 0) {
935 (void) munmap(shared, sizeof *shared);
936 return r;
937 }
938
939 tmp = *shared;
940 if (munmap(shared, sizeof *shared) != 0)
941 return negative_errno();
942
943 if (tmp.return_value == 0)
944 *usec = tmp.usec;
945
946 return tmp.return_value;
947}
948
240a7ba9 949static char* extract_multiplier(char *p, usec_t *multiplier) {
9a98c7a1
LP
950 static const struct {
951 const char *suffix;
952 usec_t usec;
953 } table[] = {
eb55ec9f
LP
954 { "seconds", USEC_PER_SEC },
955 { "second", USEC_PER_SEC },
956 { "sec", USEC_PER_SEC },
957 { "s", USEC_PER_SEC },
9a98c7a1 958 { "minutes", USEC_PER_MINUTE },
eb55ec9f
LP
959 { "minute", USEC_PER_MINUTE },
960 { "min", USEC_PER_MINUTE },
961 { "months", USEC_PER_MONTH },
962 { "month", USEC_PER_MONTH },
963 { "M", USEC_PER_MONTH },
964 { "msec", USEC_PER_MSEC },
965 { "ms", USEC_PER_MSEC },
966 { "m", USEC_PER_MINUTE },
967 { "hours", USEC_PER_HOUR },
968 { "hour", USEC_PER_HOUR },
969 { "hr", USEC_PER_HOUR },
970 { "h", USEC_PER_HOUR },
971 { "days", USEC_PER_DAY },
972 { "day", USEC_PER_DAY },
973 { "d", USEC_PER_DAY },
974 { "weeks", USEC_PER_WEEK },
975 { "week", USEC_PER_WEEK },
976 { "w", USEC_PER_WEEK },
977 { "years", USEC_PER_YEAR },
978 { "year", USEC_PER_YEAR },
979 { "y", USEC_PER_YEAR },
980 { "usec", 1ULL },
981 { "us", 1ULL },
5efdbf11 982 { "µs", 1ULL },
9a98c7a1 983 };
240a7ba9
ZJS
984 unsigned i;
985
986 for (i = 0; i < ELEMENTSOF(table); i++) {
987 char *e;
988
989 e = startswith(p, table[i].suffix);
990 if (e) {
991 *multiplier = table[i].usec;
992 return e;
993 }
994 }
9a98c7a1 995
240a7ba9
ZJS
996 return p;
997}
998
999int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
b1d6dcf5 1000 const char *p, *s;
9a98c7a1 1001 usec_t r = 0;
cb0dac05 1002 bool something = false;
9a98c7a1
LP
1003
1004 assert(t);
1005 assert(usec);
519cffec 1006 assert(default_unit > 0);
9a98c7a1
LP
1007
1008 p = t;
b1d6dcf5
ZJS
1009
1010 p += strspn(p, WHITESPACE);
1011 s = startswith(p, "infinity");
1012 if (s) {
1013 s += strspn(s, WHITESPACE);
1014 if (*s != 0)
1015 return -EINVAL;
1016
1017 *usec = USEC_INFINITY;
1018 return 0;
1019 }
1020
cb0dac05
LP
1021 for (;;) {
1022 long long l, z = 0;
9a98c7a1 1023 char *e;
240a7ba9
ZJS
1024 unsigned n = 0;
1025 usec_t multiplier = default_unit, k;
cb0dac05
LP
1026
1027 p += strspn(p, WHITESPACE);
1028
1029 if (*p == 0) {
1030 if (!something)
1031 return -EINVAL;
1032
1033 break;
1034 }
9a98c7a1
LP
1035
1036 errno = 0;
1037 l = strtoll(p, &e, 10);
8333c77e 1038 if (errno > 0)
9a98c7a1 1039 return -errno;
9a98c7a1
LP
1040 if (l < 0)
1041 return -ERANGE;
1042
cb0dac05
LP
1043 if (*e == '.') {
1044 char *b = e + 1;
1045
1046 errno = 0;
1047 z = strtoll(b, &e, 10);
1048 if (errno > 0)
1049 return -errno;
1050
1051 if (z < 0)
1052 return -ERANGE;
1053
1054 if (e == b)
1055 return -EINVAL;
1056
1057 n = e - b;
1058
1059 } else if (e == p)
9a98c7a1
LP
1060 return -EINVAL;
1061
1062 e += strspn(e, WHITESPACE);
240a7ba9 1063 p = extract_multiplier(e, &multiplier);
9a98c7a1 1064
519cffec
LP
1065 something = true;
1066
1067 k = (usec_t) z * multiplier;
1068
1069 for (; n > 0; n--)
1070 k /= 10;
1071
1072 r += (usec_t) l * multiplier + k;
cb0dac05 1073 }
9a98c7a1
LP
1074
1075 *usec = r;
1076
1077 return 0;
1078}
1079
519cffec
LP
1080int parse_sec(const char *t, usec_t *usec) {
1081 return parse_time(t, usec, USEC_PER_SEC);
1082}
1083
0004f698
ZJS
1084int parse_sec_fix_0(const char *t, usec_t *usec) {
1085 t += strspn(t, WHITESPACE);
1086 if (streq(t, "0")) {
1087 *usec = USEC_INFINITY;
1088 return 0;
1089 }
1090
1091 return parse_sec(t, usec);
1092}
1093
9a98c7a1
LP
1094int parse_nsec(const char *t, nsec_t *nsec) {
1095 static const struct {
1096 const char *suffix;
1097 nsec_t nsec;
1098 } table[] = {
1099 { "seconds", NSEC_PER_SEC },
1100 { "second", NSEC_PER_SEC },
1101 { "sec", NSEC_PER_SEC },
1102 { "s", NSEC_PER_SEC },
1103 { "minutes", NSEC_PER_MINUTE },
1104 { "minute", NSEC_PER_MINUTE },
1105 { "min", NSEC_PER_MINUTE },
1106 { "months", NSEC_PER_MONTH },
1107 { "month", NSEC_PER_MONTH },
1108 { "msec", NSEC_PER_MSEC },
1109 { "ms", NSEC_PER_MSEC },
1110 { "m", NSEC_PER_MINUTE },
1111 { "hours", NSEC_PER_HOUR },
1112 { "hour", NSEC_PER_HOUR },
1113 { "hr", NSEC_PER_HOUR },
1114 { "h", NSEC_PER_HOUR },
1115 { "days", NSEC_PER_DAY },
1116 { "day", NSEC_PER_DAY },
1117 { "d", NSEC_PER_DAY },
1118 { "weeks", NSEC_PER_WEEK },
1119 { "week", NSEC_PER_WEEK },
1120 { "w", NSEC_PER_WEEK },
1121 { "years", NSEC_PER_YEAR },
1122 { "year", NSEC_PER_YEAR },
1123 { "y", NSEC_PER_YEAR },
1124 { "usec", NSEC_PER_USEC },
1125 { "us", NSEC_PER_USEC },
5efdbf11 1126 { "µs", NSEC_PER_USEC },
9a98c7a1
LP
1127 { "nsec", 1ULL },
1128 { "ns", 1ULL },
1129 { "", 1ULL }, /* default is nsec */
1130 };
1131
e73c78c2 1132 const char *p, *s;
9a98c7a1 1133 nsec_t r = 0;
cb0dac05 1134 bool something = false;
9a98c7a1
LP
1135
1136 assert(t);
1137 assert(nsec);
1138
1139 p = t;
e73c78c2
LP
1140
1141 p += strspn(p, WHITESPACE);
1142 s = startswith(p, "infinity");
1143 if (s) {
1144 s += strspn(s, WHITESPACE);
8e8933ca 1145 if (*s != 0)
e73c78c2
LP
1146 return -EINVAL;
1147
1148 *nsec = NSEC_INFINITY;
1149 return 0;
1150 }
1151
cb0dac05
LP
1152 for (;;) {
1153 long long l, z = 0;
9a98c7a1 1154 char *e;
cb0dac05
LP
1155 unsigned i, n = 0;
1156
1157 p += strspn(p, WHITESPACE);
1158
1159 if (*p == 0) {
1160 if (!something)
1161 return -EINVAL;
1162
1163 break;
1164 }
9a98c7a1
LP
1165
1166 errno = 0;
1167 l = strtoll(p, &e, 10);
1168
8333c77e 1169 if (errno > 0)
9a98c7a1
LP
1170 return -errno;
1171
1172 if (l < 0)
1173 return -ERANGE;
1174
cb0dac05
LP
1175 if (*e == '.') {
1176 char *b = e + 1;
1177
1178 errno = 0;
1179 z = strtoll(b, &e, 10);
1180 if (errno > 0)
1181 return -errno;
1182
1183 if (z < 0)
1184 return -ERANGE;
1185
1186 if (e == b)
1187 return -EINVAL;
1188
1189 n = e - b;
1190
1191 } else if (e == p)
9a98c7a1
LP
1192 return -EINVAL;
1193
1194 e += strspn(e, WHITESPACE);
1195
1196 for (i = 0; i < ELEMENTSOF(table); i++)
1197 if (startswith(e, table[i].suffix)) {
cb0dac05
LP
1198 nsec_t k = (nsec_t) z * table[i].nsec;
1199
1200 for (; n > 0; n--)
1201 k /= 10;
1202
1203 r += (nsec_t) l * table[i].nsec + k;
9a98c7a1 1204 p = e + strlen(table[i].suffix);
cb0dac05
LP
1205
1206 something = true;
9a98c7a1
LP
1207 break;
1208 }
1209
1210 if (i >= ELEMENTSOF(table))
1211 return -EINVAL;
1212
cb0dac05 1213 }
9a98c7a1
LP
1214
1215 *nsec = r;
1216
1217 return 0;
1218}
03cc26dd
LP
1219
1220bool ntp_synced(void) {
1221 struct timex txc = {};
1222
1223 if (adjtimex(&txc) < 0)
1224 return false;
1225
1226 if (txc.status & STA_UNSYNC)
1227 return false;
1228
1229 return true;
1230}
75683450
LP
1231
1232int get_timezones(char ***ret) {
1233 _cleanup_fclose_ FILE *f = NULL;
1234 _cleanup_strv_free_ char **zones = NULL;
1235 size_t n_zones = 0, n_allocated = 0;
1236
1237 assert(ret);
1238
1239 zones = strv_new("UTC", NULL);
1240 if (!zones)
1241 return -ENOMEM;
1242
1243 n_allocated = 2;
1244 n_zones = 1;
1245
1246 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1247 if (f) {
1248 char l[LINE_MAX];
1249
1250 FOREACH_LINE(l, f, return -errno) {
1251 char *p, *w;
1252 size_t k;
1253
1254 p = strstrip(l);
1255
1256 if (isempty(p) || *p == '#')
1257 continue;
1258
1259 /* Skip over country code */
1260 p += strcspn(p, WHITESPACE);
1261 p += strspn(p, WHITESPACE);
1262
1263 /* Skip over coordinates */
1264 p += strcspn(p, WHITESPACE);
1265 p += strspn(p, WHITESPACE);
1266
1267 /* Found timezone name */
1268 k = strcspn(p, WHITESPACE);
1269 if (k <= 0)
1270 continue;
1271
1272 w = strndup(p, k);
1273 if (!w)
1274 return -ENOMEM;
1275
1276 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1277 free(w);
1278 return -ENOMEM;
1279 }
1280
1281 zones[n_zones++] = w;
1282 zones[n_zones] = NULL;
1283 }
1284
1285 strv_sort(zones);
1286
1287 } else if (errno != ENOENT)
1288 return -errno;
1289
1290 *ret = zones;
1291 zones = NULL;
1292
1293 return 0;
1294}
1295
1296bool timezone_is_valid(const char *name) {
1297 bool slash = false;
1298 const char *p, *t;
1299 struct stat st;
1300
5c904ba5
LP
1301 if (isempty(name))
1302 return false;
1303
1304 if (name[0] == '/')
75683450
LP
1305 return false;
1306
1307 for (p = name; *p; p++) {
1308 if (!(*p >= '0' && *p <= '9') &&
1309 !(*p >= 'a' && *p <= 'z') &&
1310 !(*p >= 'A' && *p <= 'Z') &&
4c701096 1311 !IN_SET(*p, '-', '_', '+', '/'))
75683450
LP
1312 return false;
1313
1314 if (*p == '/') {
1315
1316 if (slash)
1317 return false;
1318
1319 slash = true;
1320 } else
1321 slash = false;
1322 }
1323
1324 if (slash)
1325 return false;
1326
63c372cb 1327 t = strjoina("/usr/share/zoneinfo/", name);
75683450
LP
1328 if (stat(t, &st) < 0)
1329 return false;
1330
1331 if (!S_ISREG(st.st_mode))
1332 return false;
1333
1334 return true;
1335}
77ff2de9 1336
3411372e
LP
1337bool clock_boottime_supported(void) {
1338 static int supported = -1;
1339
1340 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1341
1342 if (supported < 0) {
1343 int fd;
1344
1345 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1346 if (fd < 0)
1347 supported = false;
1348 else {
1349 safe_close(fd);
1350 supported = true;
1351 }
77ff2de9
TG
1352 }
1353
3411372e
LP
1354 return supported;
1355}
1356
1357clockid_t clock_boottime_or_monotonic(void) {
1358 if (clock_boottime_supported())
1359 return CLOCK_BOOTTIME;
1360 else
1361 return CLOCK_MONOTONIC;
77ff2de9 1362}
5c904ba5 1363
fe624c4c
LP
1364bool clock_supported(clockid_t clock) {
1365 struct timespec ts;
1366
1367 switch (clock) {
1368
1369 case CLOCK_MONOTONIC:
1370 case CLOCK_REALTIME:
1371 return true;
1372
1373 case CLOCK_BOOTTIME:
1374 return clock_boottime_supported();
1375
1376 case CLOCK_BOOTTIME_ALARM:
1377 if (!clock_boottime_supported())
1378 return false;
1379
ec251fe7 1380 /* fall through */
fe624c4c
LP
1381
1382 default:
1383 /* For everything else, check properly */
1384 return clock_gettime(clock, &ts) >= 0;
1385 }
1386}
1387
64d6c229 1388int get_timezone(char **tz) {
5c904ba5
LP
1389 _cleanup_free_ char *t = NULL;
1390 const char *e;
1391 char *z;
1392 int r;
1393
1394 r = readlink_malloc("/etc/localtime", &t);
1395 if (r < 0)
1396 return r; /* returns EINVAL if not a symlink */
1397
1398 e = path_startswith(t, "/usr/share/zoneinfo/");
1399 if (!e)
1400 e = path_startswith(t, "../usr/share/zoneinfo/");
1401 if (!e)
1402 return -EINVAL;
1403
1404 if (!timezone_is_valid(e))
1405 return -EINVAL;
1406
1407 z = strdup(e);
1408 if (!z)
1409 return -ENOMEM;
1410
64d6c229 1411 *tz = z;
5c904ba5
LP
1412 return 0;
1413}
7c67c79c
HV
1414
1415time_t mktime_or_timegm(struct tm *tm, bool utc) {
1416 return utc ? timegm(tm) : mktime(tm);
1417}
1418
1419struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1420 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1421}
87b8ce69
SS
1422
1423unsigned long usec_to_jiffies(usec_t u) {
1424 static thread_local unsigned long hz = 0;
1425 long r;
1426
1427 if (hz == 0) {
1428 r = sysconf(_SC_CLK_TCK);
1429
1430 assert(r > 0);
70887c5f 1431 hz = r;
87b8ce69
SS
1432 }
1433
1434 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1435}
1007ec60
LP
1436
1437usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
1438 usec_t a, b;
1439
1440 if (x == USEC_INFINITY)
1441 return USEC_INFINITY;
1442 if (map_clock_id(from) == map_clock_id(to))
1443 return x;
1444
1445 a = now(from);
1446 b = now(to);
1447
1448 if (x > a)
1449 /* x lies in the future */
1450 return usec_add(b, usec_sub_unsigned(x, a));
1451 else
1452 /* x lies in the past */
1453 return usec_sub_unsigned(b, usec_sub_unsigned(a, x));
1454}