]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/time-util.c
util: check overflow in parse_time()
[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"
8d2b9d14 17#include "def.h"
3ffd4af2 18#include "fd-util.h"
0d39fa9c 19#include "fileio.h"
f4f15635 20#include "fs-util.h"
a2932d51 21#include "io-util.h"
11c3a366
TA
22#include "log.h"
23#include "macro.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
533void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
534
535 assert(f);
536 assert(name);
537 assert(t);
538
539 if (!dual_timestamp_is_set(t))
540 return;
541
de0671ee 542 fprintf(f, "%s="USEC_FMT" "USEC_FMT"\n",
9a98c7a1 543 name,
de0671ee
ZJS
544 t->realtime,
545 t->monotonic);
9a98c7a1
LP
546}
547
e911de99 548int dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
74c5b33b 549 uint64_t a, b;
9c0565b2 550 int r, pos;
9a98c7a1
LP
551
552 assert(value);
553 assert(t);
554
9c0565b2
ZJS
555 pos = strspn(value, WHITESPACE);
556 if (value[pos] == '-')
557 return -EINVAL;
558 pos += strspn(value + pos, DIGITS);
559 pos += strspn(value + pos, WHITESPACE);
560 if (value[pos] == '-')
561 return -EINVAL;
562
563 r = sscanf(value, "%" PRIu64 "%" PRIu64 "%n", &a, &b, &pos);
564 if (r != 2) {
565 log_debug("Failed to parse dual timestamp value \"%s\".", value);
e911de99 566 return -EINVAL;
9a98c7a1 567 }
e911de99 568
9c0565b2
ZJS
569 if (value[pos] != '\0')
570 /* trailing garbage */
571 return -EINVAL;
572
e911de99
LP
573 t->realtime = a;
574 t->monotonic = b;
575
576 return 0;
9a98c7a1
LP
577}
578
b895a735 579int timestamp_deserialize(const char *value, usec_t *timestamp) {
ebf30a08
AK
580 int r;
581
582 assert(value);
583
584 r = safe_atou64(value, timestamp);
ebf30a08 585 if (r < 0)
b895a735 586 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
ebf30a08
AK
587
588 return r;
589}
590
48d26c01 591static int parse_timestamp_impl(const char *t, usec_t *usec, bool with_tz) {
92134489
LP
592 static const struct {
593 const char *name;
594 const int nr;
595 } day_nr[] = {
596 { "Sunday", 0 },
597 { "Sun", 0 },
598 { "Monday", 1 },
599 { "Mon", 1 },
600 { "Tuesday", 2 },
601 { "Tue", 2 },
602 { "Wednesday", 3 },
603 { "Wed", 3 },
604 { "Thursday", 4 },
605 { "Thu", 4 },
606 { "Friday", 5 },
607 { "Fri", 5 },
608 { "Saturday", 6 },
609 { "Sat", 6 },
610 };
611
48d26c01 612 const char *k, *utc = NULL, *tzn = NULL;
9a98c7a1
LP
613 struct tm tm, copy;
614 time_t x;
e4eaf99a 615 usec_t x_usec, plus = 0, minus = 0, ret;
21b3a0fc 616 int r, weekday = -1, dst = -1;
da6053d0 617 size_t i;
9a98c7a1 618
947f9f01 619 /* Allowed syntaxes:
9a98c7a1
LP
620 *
621 * 2012-09-22 16:34:22
622 * 2012-09-22 16:34 (seconds will be set to 0)
623 * 2012-09-22 (time will be set to 00:00:00)
624 * 16:34:22 (date will be set to today)
625 * 16:34 (date will be set to today, seconds to 0)
626 * now
627 * yesterday (time is set to 00:00:00)
628 * today (time is set to 00:00:00)
629 * tomorrow (time is set to 00:00:00)
630 * +5min
631 * -5days
5ba6e094 632 * @2147483647 (seconds since epoch)
9a98c7a1
LP
633 */
634
635 assert(t);
636 assert(usec);
637
48d26c01 638 if (t[0] == '@' && !with_tz)
e4eaf99a 639 return parse_sec(t + 1, usec);
9a98c7a1 640
e4eaf99a 641 ret = now(CLOCK_REALTIME);
9a98c7a1 642
48d26c01
IK
643 if (!with_tz) {
644 if (streq(t, "now"))
645 goto finish;
9a98c7a1 646
48d26c01
IK
647 else if (t[0] == '+') {
648 r = parse_sec(t+1, &plus);
649 if (r < 0)
650 return r;
9a98c7a1 651
48d26c01 652 goto finish;
9a98c7a1 653
48d26c01
IK
654 } else if (t[0] == '-') {
655 r = parse_sec(t+1, &minus);
656 if (r < 0)
657 return r;
9a98c7a1 658
48d26c01 659 goto finish;
decad910 660
48d26c01
IK
661 } else if ((k = endswith(t, " ago"))) {
662 t = strndupa(t, k - t);
decad910 663
48d26c01
IK
664 r = parse_sec(t, &minus);
665 if (r < 0)
666 return r;
decad910 667
48d26c01 668 goto finish;
1fcf71f5 669
48d26c01
IK
670 } else if ((k = endswith(t, " left"))) {
671 t = strndupa(t, k - t);
1fcf71f5 672
48d26c01
IK
673 r = parse_sec(t, &plus);
674 if (r < 0)
675 return r;
1fcf71f5 676
48d26c01
IK
677 goto finish;
678 }
9a98c7a1 679
48d26c01
IK
680 /* See if the timestamp is suffixed with UTC */
681 utc = endswith_no_case(t, " UTC");
682 if (utc)
683 t = strndupa(t, utc - t);
684 else {
685 const char *e = NULL;
686 int j;
21b3a0fc 687
48d26c01 688 tzset();
21b3a0fc 689
48d26c01 690 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
947f9f01
YW
691 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
692 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
693 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
694 * support arbitrary timezone specifications. */
e4eaf99a 695
48d26c01 696 for (j = 0; j <= 1; j++) {
21b3a0fc 697
48d26c01
IK
698 if (isempty(tzname[j]))
699 continue;
21b3a0fc 700
48d26c01
IK
701 e = endswith_no_case(t, tzname[j]);
702 if (!e)
703 continue;
704 if (e == t)
705 continue;
706 if (e[-1] != ' ')
707 continue;
21b3a0fc 708
48d26c01
IK
709 break;
710 }
21b3a0fc 711
48d26c01
IK
712 if (IN_SET(j, 0, 1)) {
713 /* Found one of the two timezones specified. */
714 t = strndupa(t, e - t - 1);
715 dst = j;
716 tzn = tzname[j];
717 }
21b3a0fc
LP
718 }
719 }
720
721 x = (time_t) (ret / USEC_PER_SEC);
e4eaf99a
HV
722 x_usec = 0;
723
21b3a0fc
LP
724 if (!localtime_or_gmtime_r(&x, &tm, utc))
725 return -EINVAL;
726
2e72b794
IK
727 tm.tm_isdst = dst;
728 if (!with_tz && tzn)
729 tm.tm_zone = tzn;
e4eaf99a
HV
730
731 if (streq(t, "today")) {
732 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
733 goto from_tm;
734
735 } else if (streq(t, "yesterday")) {
313cefa1 736 tm.tm_mday--;
e4eaf99a
HV
737 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
738 goto from_tm;
739
740 } else if (streq(t, "tomorrow")) {
313cefa1 741 tm.tm_mday++;
e4eaf99a
HV
742 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
743 goto from_tm;
744 }
745
92134489
LP
746 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
747 size_t skip;
748
749 if (!startswith_no_case(t, day_nr[i].name))
750 continue;
751
752 skip = strlen(day_nr[i].name);
753 if (t[skip] != ' ')
754 continue;
755
756 weekday = day_nr[i].nr;
757 t += skip + 1;
758 break;
759 }
760
9a98c7a1
LP
761 copy = tm;
762 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
e4eaf99a
HV
763 if (k) {
764 if (*k == '.')
765 goto parse_usec;
766 else if (*k == 0)
767 goto from_tm;
768 }
9a98c7a1
LP
769
770 tm = copy;
771 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
e4eaf99a
HV
772 if (k) {
773 if (*k == '.')
774 goto parse_usec;
775 else if (*k == 0)
776 goto from_tm;
777 }
9a98c7a1
LP
778
779 tm = copy;
780 k = strptime(t, "%y-%m-%d %H:%M", &tm);
781 if (k && *k == 0) {
782 tm.tm_sec = 0;
e4eaf99a 783 goto from_tm;
9a98c7a1
LP
784 }
785
786 tm = copy;
787 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
788 if (k && *k == 0) {
789 tm.tm_sec = 0;
e4eaf99a 790 goto from_tm;
9a98c7a1
LP
791 }
792
793 tm = copy;
794 k = strptime(t, "%y-%m-%d", &tm);
795 if (k && *k == 0) {
796 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
e4eaf99a 797 goto from_tm;
9a98c7a1
LP
798 }
799
800 tm = copy;
801 k = strptime(t, "%Y-%m-%d", &tm);
802 if (k && *k == 0) {
803 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
e4eaf99a 804 goto from_tm;
9a98c7a1
LP
805 }
806
807 tm = copy;
808 k = strptime(t, "%H:%M:%S", &tm);
e4eaf99a
HV
809 if (k) {
810 if (*k == '.')
811 goto parse_usec;
812 else if (*k == 0)
813 goto from_tm;
814 }
9a98c7a1
LP
815
816 tm = copy;
817 k = strptime(t, "%H:%M", &tm);
818 if (k && *k == 0) {
819 tm.tm_sec = 0;
e4eaf99a 820 goto from_tm;
9a98c7a1
LP
821 }
822
823 return -EINVAL;
824
e4eaf99a
HV
825parse_usec:
826 {
436dd70f 827 unsigned add;
e4eaf99a
HV
828
829 k++;
436dd70f
HV
830 r = parse_fractional_part_u(&k, 6, &add);
831 if (r < 0)
e4eaf99a
HV
832 return -EINVAL;
833
436dd70f 834 if (*k)
e4eaf99a
HV
835 return -EINVAL;
836
436dd70f 837 x_usec = add;
e4eaf99a
HV
838 }
839
840from_tm:
214cc95d 841 if (weekday >= 0 && tm.tm_wday != weekday)
68bdd2d2 842 return -EINVAL;
9a98c7a1 843
214cc95d
MH
844 x = mktime_or_timegm(&tm, utc);
845 if (x < 0)
92134489
LP
846 return -EINVAL;
847
68bdd2d2 848 ret = (usec_t) x * USEC_PER_SEC + x_usec;
1bb4b028
LP
849 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
850 return -EINVAL;
9a98c7a1 851
e4eaf99a 852finish:
315782db 853 if (ret + plus < ret) /* overflow? */
68bdd2d2 854 return -EINVAL;
9a98c7a1 855 ret += plus;
1bb4b028
LP
856 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
857 return -EINVAL;
858
68bdd2d2 859 if (ret >= minus)
9a98c7a1
LP
860 ret -= minus;
861 else
68bdd2d2 862 return -EINVAL;
9a98c7a1
LP
863
864 *usec = ret;
865
866 return 0;
867}
868
48d26c01
IK
869typedef struct ParseTimestampResult {
870 usec_t usec;
871 int return_value;
872} ParseTimestampResult;
873
874int parse_timestamp(const char *t, usec_t *usec) {
ff69484a 875 char *last_space, *tz = NULL;
48d26c01 876 ParseTimestampResult *shared, tmp;
4c253ed1 877 int r;
48d26c01
IK
878
879 last_space = strrchr(t, ' ');
089fb865 880 if (last_space != NULL && timezone_is_valid(last_space + 1, LOG_DEBUG))
ff69484a 881 tz = last_space + 1;
48d26c01 882
234519ae 883 if (!tz || endswith_no_case(t, " UTC"))
48d26c01
IK
884 return parse_timestamp_impl(t, usec, false);
885
48d26c01
IK
886 shared = mmap(NULL, sizeof *shared, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
887 if (shared == MAP_FAILED)
888 return negative_errno();
889
1f5d1e02 890 r = safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_WAIT, NULL);
4c253ed1 891 if (r < 0) {
48d26c01 892 (void) munmap(shared, sizeof *shared);
4c253ed1 893 return r;
48d26c01 894 }
4c253ed1 895 if (r == 0) {
3fd4929b
MH
896 bool with_tz = true;
897
ff69484a 898 if (setenv("TZ", tz, 1) != 0) {
48d26c01
IK
899 shared->return_value = negative_errno();
900 _exit(EXIT_FAILURE);
901 }
902
903 tzset();
904
3fd4929b 905 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
947f9f01 906 * Otherwise just cut it off. */
3fd4929b
MH
907 with_tz = !STR_IN_SET(tz, tzname[0], tzname[1]);
908
f21f31b2 909 /* Cut off the timezone if we don't need it. */
3fd4929b
MH
910 if (with_tz)
911 t = strndupa(t, last_space - t);
912
913 shared->return_value = parse_timestamp_impl(t, &shared->usec, with_tz);
48d26c01
IK
914
915 _exit(EXIT_SUCCESS);
916 }
917
48d26c01
IK
918 tmp = *shared;
919 if (munmap(shared, sizeof *shared) != 0)
920 return negative_errno();
921
922 if (tmp.return_value == 0)
923 *usec = tmp.usec;
924
925 return tmp.return_value;
926}
927
240a7ba9 928static char* extract_multiplier(char *p, usec_t *multiplier) {
9a98c7a1
LP
929 static const struct {
930 const char *suffix;
931 usec_t usec;
932 } table[] = {
eb55ec9f
LP
933 { "seconds", USEC_PER_SEC },
934 { "second", USEC_PER_SEC },
935 { "sec", USEC_PER_SEC },
936 { "s", USEC_PER_SEC },
9a98c7a1 937 { "minutes", USEC_PER_MINUTE },
eb55ec9f
LP
938 { "minute", USEC_PER_MINUTE },
939 { "min", USEC_PER_MINUTE },
940 { "months", USEC_PER_MONTH },
941 { "month", USEC_PER_MONTH },
942 { "M", USEC_PER_MONTH },
943 { "msec", USEC_PER_MSEC },
944 { "ms", USEC_PER_MSEC },
945 { "m", USEC_PER_MINUTE },
946 { "hours", USEC_PER_HOUR },
947 { "hour", USEC_PER_HOUR },
948 { "hr", USEC_PER_HOUR },
949 { "h", USEC_PER_HOUR },
950 { "days", USEC_PER_DAY },
951 { "day", USEC_PER_DAY },
952 { "d", USEC_PER_DAY },
953 { "weeks", USEC_PER_WEEK },
954 { "week", USEC_PER_WEEK },
955 { "w", USEC_PER_WEEK },
956 { "years", USEC_PER_YEAR },
957 { "year", USEC_PER_YEAR },
958 { "y", USEC_PER_YEAR },
959 { "usec", 1ULL },
960 { "us", 1ULL },
5efdbf11 961 { "µs", 1ULL },
9a98c7a1 962 };
da6053d0 963 size_t i;
240a7ba9
ZJS
964
965 for (i = 0; i < ELEMENTSOF(table); i++) {
966 char *e;
967
968 e = startswith(p, table[i].suffix);
969 if (e) {
970 *multiplier = table[i].usec;
971 return e;
972 }
973 }
9a98c7a1 974
240a7ba9
ZJS
975 return p;
976}
977
978int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
b1d6dcf5 979 const char *p, *s;
9a98c7a1 980 usec_t r = 0;
cb0dac05 981 bool something = false;
9a98c7a1
LP
982
983 assert(t);
984 assert(usec);
519cffec 985 assert(default_unit > 0);
9a98c7a1
LP
986
987 p = t;
b1d6dcf5
ZJS
988
989 p += strspn(p, WHITESPACE);
990 s = startswith(p, "infinity");
991 if (s) {
992 s += strspn(s, WHITESPACE);
993 if (*s != 0)
994 return -EINVAL;
995
996 *usec = USEC_INFINITY;
997 return 0;
998 }
999
cb0dac05 1000 for (;;) {
5a9fb358 1001 usec_t multiplier = default_unit, k;
cb0dac05 1002 long long l, z = 0;
240a7ba9 1003 unsigned n = 0;
5a9fb358 1004 char *e;
cb0dac05
LP
1005
1006 p += strspn(p, WHITESPACE);
1007
1008 if (*p == 0) {
1009 if (!something)
1010 return -EINVAL;
1011
1012 break;
1013 }
9a98c7a1 1014
5a9fb358
LP
1015 if (*p == '-') /* Don't allow "-0" */
1016 return -ERANGE;
1017
9a98c7a1
LP
1018 errno = 0;
1019 l = strtoll(p, &e, 10);
8333c77e 1020 if (errno > 0)
9a98c7a1 1021 return -errno;
9a98c7a1
LP
1022 if (l < 0)
1023 return -ERANGE;
1024
cb0dac05
LP
1025 if (*e == '.') {
1026 char *b = e + 1;
1027
279f52a1 1028 /* Don't allow "0.-0", "3.+1" or "3. 1" */
490c5a37 1029 if (IN_SET(*b, '-', '+') || isspace(*b))
5a9fb358
LP
1030 return -EINVAL;
1031
cb0dac05
LP
1032 errno = 0;
1033 z = strtoll(b, &e, 10);
1034 if (errno > 0)
1035 return -errno;
cb0dac05
LP
1036 if (z < 0)
1037 return -ERANGE;
cb0dac05
LP
1038 if (e == b)
1039 return -EINVAL;
1040
1041 n = e - b;
1042
1043 } else if (e == p)
9a98c7a1
LP
1044 return -EINVAL;
1045
1046 e += strspn(e, WHITESPACE);
240a7ba9 1047 p = extract_multiplier(e, &multiplier);
9a98c7a1 1048
519cffec
LP
1049 something = true;
1050
8079c903
YW
1051
1052 k = ((usec_t) -1) / multiplier;
1053 if ((usec_t) l + 1 >= k || (usec_t) z >= k)
1054 return -ERANGE;
1055
519cffec
LP
1056 k = (usec_t) z * multiplier;
1057
1058 for (; n > 0; n--)
1059 k /= 10;
1060
8079c903
YW
1061 k += (usec_t) l * multiplier;
1062 if (k >= ((usec_t) -1) - r)
1063 return -ERANGE;
1064
1065 r += k;
cb0dac05 1066 }
9a98c7a1
LP
1067
1068 *usec = r;
1069
1070 return 0;
1071}
1072
519cffec
LP
1073int parse_sec(const char *t, usec_t *usec) {
1074 return parse_time(t, usec, USEC_PER_SEC);
1075}
1076
0004f698 1077int parse_sec_fix_0(const char *t, usec_t *usec) {
eae51da3
LP
1078 assert(t);
1079 assert(usec);
1080
0004f698 1081 t += strspn(t, WHITESPACE);
eae51da3 1082
0004f698
ZJS
1083 if (streq(t, "0")) {
1084 *usec = USEC_INFINITY;
1085 return 0;
1086 }
1087
1088 return parse_sec(t, usec);
1089}
1090
9a98c7a1
LP
1091int parse_nsec(const char *t, nsec_t *nsec) {
1092 static const struct {
1093 const char *suffix;
1094 nsec_t nsec;
1095 } table[] = {
1096 { "seconds", NSEC_PER_SEC },
1097 { "second", NSEC_PER_SEC },
1098 { "sec", NSEC_PER_SEC },
1099 { "s", NSEC_PER_SEC },
1100 { "minutes", NSEC_PER_MINUTE },
1101 { "minute", NSEC_PER_MINUTE },
1102 { "min", NSEC_PER_MINUTE },
1103 { "months", NSEC_PER_MONTH },
1104 { "month", NSEC_PER_MONTH },
1105 { "msec", NSEC_PER_MSEC },
1106 { "ms", NSEC_PER_MSEC },
1107 { "m", NSEC_PER_MINUTE },
1108 { "hours", NSEC_PER_HOUR },
1109 { "hour", NSEC_PER_HOUR },
1110 { "hr", NSEC_PER_HOUR },
1111 { "h", NSEC_PER_HOUR },
1112 { "days", NSEC_PER_DAY },
1113 { "day", NSEC_PER_DAY },
1114 { "d", NSEC_PER_DAY },
1115 { "weeks", NSEC_PER_WEEK },
1116 { "week", NSEC_PER_WEEK },
1117 { "w", NSEC_PER_WEEK },
1118 { "years", NSEC_PER_YEAR },
1119 { "year", NSEC_PER_YEAR },
1120 { "y", NSEC_PER_YEAR },
1121 { "usec", NSEC_PER_USEC },
1122 { "us", NSEC_PER_USEC },
5efdbf11 1123 { "µs", NSEC_PER_USEC },
9a98c7a1
LP
1124 { "nsec", 1ULL },
1125 { "ns", 1ULL },
1126 { "", 1ULL }, /* default is nsec */
1127 };
1128
e73c78c2 1129 const char *p, *s;
9a98c7a1 1130 nsec_t r = 0;
cb0dac05 1131 bool something = false;
9a98c7a1
LP
1132
1133 assert(t);
1134 assert(nsec);
1135
1136 p = t;
e73c78c2
LP
1137
1138 p += strspn(p, WHITESPACE);
1139 s = startswith(p, "infinity");
1140 if (s) {
1141 s += strspn(s, WHITESPACE);
8e8933ca 1142 if (*s != 0)
e73c78c2
LP
1143 return -EINVAL;
1144
1145 *nsec = NSEC_INFINITY;
1146 return 0;
1147 }
1148
cb0dac05
LP
1149 for (;;) {
1150 long long l, z = 0;
da6053d0 1151 size_t n = 0, i;
9a98c7a1 1152 char *e;
cb0dac05
LP
1153
1154 p += strspn(p, WHITESPACE);
1155
1156 if (*p == 0) {
1157 if (!something)
1158 return -EINVAL;
1159
1160 break;
1161 }
9a98c7a1 1162
5a9fb358
LP
1163 if (*p == '-')
1164 return -ERANGE;
1165
9a98c7a1
LP
1166 errno = 0;
1167 l = strtoll(p, &e, 10);
8333c77e 1168 if (errno > 0)
9a98c7a1 1169 return -errno;
9a98c7a1
LP
1170 if (l < 0)
1171 return -ERANGE;
1172
cb0dac05
LP
1173 if (*e == '.') {
1174 char *b = e + 1;
1175
490c5a37 1176 if (IN_SET(*b, '-', '+') || isspace(*b))
5a9fb358
LP
1177 return -EINVAL;
1178
cb0dac05
LP
1179 errno = 0;
1180 z = strtoll(b, &e, 10);
1181 if (errno > 0)
1182 return -errno;
cb0dac05
LP
1183 if (z < 0)
1184 return -ERANGE;
cb0dac05
LP
1185 if (e == b)
1186 return -EINVAL;
1187
1188 n = e - b;
1189
1190 } else if (e == p)
9a98c7a1
LP
1191 return -EINVAL;
1192
1193 e += strspn(e, WHITESPACE);
1194
1195 for (i = 0; i < ELEMENTSOF(table); i++)
1196 if (startswith(e, table[i].suffix)) {
cb0dac05
LP
1197 nsec_t k = (nsec_t) z * table[i].nsec;
1198
1199 for (; n > 0; n--)
1200 k /= 10;
1201
1202 r += (nsec_t) l * table[i].nsec + k;
9a98c7a1 1203 p = e + strlen(table[i].suffix);
cb0dac05
LP
1204
1205 something = true;
9a98c7a1
LP
1206 break;
1207 }
1208
1209 if (i >= ELEMENTSOF(table))
1210 return -EINVAL;
1211
cb0dac05 1212 }
9a98c7a1
LP
1213
1214 *nsec = r;
1215
1216 return 0;
1217}
03cc26dd
LP
1218
1219bool ntp_synced(void) {
1220 struct timex txc = {};
1221
1222 if (adjtimex(&txc) < 0)
1223 return false;
1224
1225 if (txc.status & STA_UNSYNC)
1226 return false;
1227
1228 return true;
1229}
75683450
LP
1230
1231int get_timezones(char ***ret) {
1232 _cleanup_fclose_ FILE *f = NULL;
1233 _cleanup_strv_free_ char **zones = NULL;
1234 size_t n_zones = 0, n_allocated = 0;
8d2b9d14 1235 int r;
75683450
LP
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) {
8d2b9d14
LP
1248 for (;;) {
1249 _cleanup_free_ char *line = NULL;
75683450
LP
1250 char *p, *w;
1251 size_t k;
1252
8d2b9d14
LP
1253 r = read_line(f, LONG_LINE_MAX, &line);
1254 if (r < 0)
1255 return r;
1256 if (r == 0)
1257 break;
1258
1259 p = strstrip(line);
75683450
LP
1260
1261 if (isempty(p) || *p == '#')
1262 continue;
1263
1264 /* Skip over country code */
1265 p += strcspn(p, WHITESPACE);
1266 p += strspn(p, WHITESPACE);
1267
1268 /* Skip over coordinates */
1269 p += strcspn(p, WHITESPACE);
1270 p += strspn(p, WHITESPACE);
1271
1272 /* Found timezone name */
1273 k = strcspn(p, WHITESPACE);
1274 if (k <= 0)
1275 continue;
1276
1277 w = strndup(p, k);
1278 if (!w)
1279 return -ENOMEM;
1280
1281 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1282 free(w);
1283 return -ENOMEM;
1284 }
1285
1286 zones[n_zones++] = w;
1287 zones[n_zones] = NULL;
1288 }
1289
1290 strv_sort(zones);
1291
1292 } else if (errno != ENOENT)
1293 return -errno;
1294
1cc6c93a 1295 *ret = TAKE_PTR(zones);
75683450
LP
1296
1297 return 0;
1298}
1299
089fb865 1300bool timezone_is_valid(const char *name, int log_level) {
75683450
LP
1301 bool slash = false;
1302 const char *p, *t;
a2932d51
MG
1303 _cleanup_close_ int fd = -1;
1304 char buf[4];
1305 int r;
75683450 1306
5c904ba5
LP
1307 if (isempty(name))
1308 return false;
1309
1310 if (name[0] == '/')
75683450
LP
1311 return false;
1312
1313 for (p = name; *p; p++) {
1314 if (!(*p >= '0' && *p <= '9') &&
1315 !(*p >= 'a' && *p <= 'z') &&
1316 !(*p >= 'A' && *p <= 'Z') &&
4c701096 1317 !IN_SET(*p, '-', '_', '+', '/'))
75683450
LP
1318 return false;
1319
1320 if (*p == '/') {
1321
1322 if (slash)
1323 return false;
1324
1325 slash = true;
1326 } else
1327 slash = false;
1328 }
1329
1330 if (slash)
1331 return false;
1332
1c73b60b
YW
1333 if (p - name >= PATH_MAX)
1334 return false;
1335
63c372cb 1336 t = strjoina("/usr/share/zoneinfo/", name);
a2932d51
MG
1337
1338 fd = open(t, O_RDONLY|O_CLOEXEC);
1339 if (fd < 0) {
089fb865 1340 log_full_errno(log_level, errno, "Failed to open timezone file '%s': %m", t);
a2932d51
MG
1341 return false;
1342 }
1343
1344 r = fd_verify_regular(fd);
1345 if (r < 0) {
089fb865 1346 log_full_errno(log_level, r, "Timezone file '%s' is not a regular file: %m", t);
75683450 1347 return false;
a2932d51
MG
1348 }
1349
1350 r = loop_read_exact(fd, buf, 4, false);
1351 if (r < 0) {
089fb865 1352 log_full_errno(log_level, r, "Failed to read from timezone file '%s': %m", t);
a2932d51
MG
1353 return false;
1354 }
75683450 1355
a2932d51
MG
1356 /* Magic from tzfile(5) */
1357 if (memcmp(buf, "TZif", 4) != 0) {
089fb865 1358 log_full(log_level, "Timezone file '%s' has wrong magic bytes", t);
75683450 1359 return false;
a2932d51 1360 }
75683450
LP
1361
1362 return true;
1363}
77ff2de9 1364
3411372e
LP
1365bool clock_boottime_supported(void) {
1366 static int supported = -1;
1367
1368 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1369
1370 if (supported < 0) {
1371 int fd;
1372
1373 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1374 if (fd < 0)
1375 supported = false;
1376 else {
1377 safe_close(fd);
1378 supported = true;
1379 }
77ff2de9
TG
1380 }
1381
3411372e
LP
1382 return supported;
1383}
1384
1385clockid_t clock_boottime_or_monotonic(void) {
1386 if (clock_boottime_supported())
1387 return CLOCK_BOOTTIME;
1388 else
1389 return CLOCK_MONOTONIC;
77ff2de9 1390}
5c904ba5 1391
fe624c4c
LP
1392bool clock_supported(clockid_t clock) {
1393 struct timespec ts;
1394
1395 switch (clock) {
1396
1397 case CLOCK_MONOTONIC:
1398 case CLOCK_REALTIME:
1399 return true;
1400
1401 case CLOCK_BOOTTIME:
1402 return clock_boottime_supported();
1403
1404 case CLOCK_BOOTTIME_ALARM:
1405 if (!clock_boottime_supported())
1406 return false;
1407
4831981d 1408 _fallthrough_;
fe624c4c
LP
1409 default:
1410 /* For everything else, check properly */
1411 return clock_gettime(clock, &ts) >= 0;
1412 }
1413}
1414
64d6c229 1415int get_timezone(char **tz) {
5c904ba5
LP
1416 _cleanup_free_ char *t = NULL;
1417 const char *e;
1418 char *z;
1419 int r;
1420
1421 r = readlink_malloc("/etc/localtime", &t);
1422 if (r < 0)
1423 return r; /* returns EINVAL if not a symlink */
1424
1425 e = path_startswith(t, "/usr/share/zoneinfo/");
1426 if (!e)
1427 e = path_startswith(t, "../usr/share/zoneinfo/");
1428 if (!e)
1429 return -EINVAL;
1430
089fb865 1431 if (!timezone_is_valid(e, LOG_DEBUG))
5c904ba5
LP
1432 return -EINVAL;
1433
1434 z = strdup(e);
1435 if (!z)
1436 return -ENOMEM;
1437
64d6c229 1438 *tz = z;
5c904ba5
LP
1439 return 0;
1440}
7c67c79c
HV
1441
1442time_t mktime_or_timegm(struct tm *tm, bool utc) {
1443 return utc ? timegm(tm) : mktime(tm);
1444}
1445
1446struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1447 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1448}
87b8ce69
SS
1449
1450unsigned long usec_to_jiffies(usec_t u) {
1451 static thread_local unsigned long hz = 0;
1452 long r;
1453
1454 if (hz == 0) {
1455 r = sysconf(_SC_CLK_TCK);
1456
1457 assert(r > 0);
70887c5f 1458 hz = r;
87b8ce69
SS
1459 }
1460
1461 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1462}
1007ec60
LP
1463
1464usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
1465 usec_t a, b;
1466
1467 if (x == USEC_INFINITY)
1468 return USEC_INFINITY;
1469 if (map_clock_id(from) == map_clock_id(to))
1470 return x;
1471
1472 a = now(from);
1473 b = now(to);
1474
1475 if (x > a)
1476 /* x lies in the future */
1477 return usec_add(b, usec_sub_unsigned(x, a));
1478 else
1479 /* x lies in the past */
1480 return usec_sub_unsigned(b, usec_sub_unsigned(a, x));
1481}
9a9a4f10
LP
1482
1483bool in_utc_timezone(void) {
1484 tzset();
1485
1486 return timezone == 0 && daylight == 0;
1487}
4f811d27
LP
1488
1489int time_change_fd(void) {
1490
1491 /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1492 static const struct itimerspec its = {
1493 .it_value.tv_sec = TIME_T_MAX,
1494 };
1495
1496 _cleanup_close_ int fd;
1497
1498 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
1499
1500 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1501 * CLOCK_MONOTONIC. */
1502
1503 fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1504 if (fd < 0)
1505 return -errno;
1506
1507 if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0)
1508 return -errno;
1509
1510 return TAKE_FD(fd);
1511}