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