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