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