]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/time-util.c
test-parse-util: verify that ato[ui] actually rejects trailing garbage
[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;
5d634ca8 110 ts->monotonic = usec_sub(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;
127 ts->monotonic = usec_sub(now(CLOCK_MONOTONIC), delta);
128 ts->boottime = clock_boottime_supported() ? usec_sub(now(CLOCK_BOOTTIME), delta) : USEC_INFINITY;
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;
5d634ca8 144 ts->realtime = usec_sub(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;
5d634ca8
AK
159 ts->realtime = usec_sub(ts->realtime, delta);
160 ts->monotonic = usec_sub(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;
9a98c7a1
LP
558
559 assert(value);
560 assert(t);
561
74c5b33b 562 if (sscanf(value, "%" PRIu64 "%" PRIu64, &a, &b) != 2) {
b895a735 563 log_debug("Failed to parse dual timestamp value \"%s\": %m", value);
e911de99 564 return -EINVAL;
9a98c7a1 565 }
e911de99
LP
566
567 t->realtime = a;
568 t->monotonic = b;
569
570 return 0;
9a98c7a1
LP
571}
572
b895a735 573int timestamp_deserialize(const char *value, usec_t *timestamp) {
ebf30a08
AK
574 int r;
575
576 assert(value);
577
578 r = safe_atou64(value, timestamp);
ebf30a08 579 if (r < 0)
b895a735 580 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
ebf30a08
AK
581
582 return r;
583}
584
9a98c7a1 585int parse_timestamp(const char *t, usec_t *usec) {
92134489
LP
586 static const struct {
587 const char *name;
588 const int nr;
589 } day_nr[] = {
590 { "Sunday", 0 },
591 { "Sun", 0 },
592 { "Monday", 1 },
593 { "Mon", 1 },
594 { "Tuesday", 2 },
595 { "Tue", 2 },
596 { "Wednesday", 3 },
597 { "Wed", 3 },
598 { "Thursday", 4 },
599 { "Thu", 4 },
600 { "Friday", 5 },
601 { "Fri", 5 },
602 { "Saturday", 6 },
603 { "Sat", 6 },
604 };
605
21b3a0fc 606 const char *k, *utc, *tzn = NULL;
9a98c7a1
LP
607 struct tm tm, copy;
608 time_t x;
e4eaf99a 609 usec_t x_usec, plus = 0, minus = 0, ret;
21b3a0fc 610 int r, weekday = -1, dst = -1;
92134489 611 unsigned i;
9a98c7a1
LP
612
613 /*
614 * Allowed syntaxes:
615 *
616 * 2012-09-22 16:34:22
617 * 2012-09-22 16:34 (seconds will be set to 0)
618 * 2012-09-22 (time will be set to 00:00:00)
619 * 16:34:22 (date will be set to today)
620 * 16:34 (date will be set to today, seconds to 0)
621 * now
622 * yesterday (time is set to 00:00:00)
623 * today (time is set to 00:00:00)
624 * tomorrow (time is set to 00:00:00)
625 * +5min
626 * -5days
5ba6e094 627 * @2147483647 (seconds since epoch)
9a98c7a1
LP
628 *
629 */
630
631 assert(t);
632 assert(usec);
633
e4eaf99a
HV
634 if (t[0] == '@')
635 return parse_sec(t + 1, usec);
9a98c7a1 636
e4eaf99a 637 ret = now(CLOCK_REALTIME);
9a98c7a1 638
e4eaf99a 639 if (streq(t, "now"))
9a98c7a1
LP
640 goto finish;
641
e4eaf99a 642 else if (t[0] == '+') {
7f602784 643 r = parse_sec(t+1, &plus);
9a98c7a1
LP
644 if (r < 0)
645 return r;
646
647 goto finish;
9a98c7a1 648
5ba6e094 649 } else if (t[0] == '-') {
7f602784 650 r = parse_sec(t+1, &minus);
9a98c7a1
LP
651 if (r < 0)
652 return r;
653
654 goto finish;
decad910 655
078efddd
HV
656 } else if ((k = endswith(t, " ago"))) {
657 t = strndupa(t, k - t);
decad910 658
e4eaf99a 659 r = parse_sec(t, &minus);
decad910
LP
660 if (r < 0)
661 return r;
662
1fcf71f5 663 goto finish;
1fcf71f5 664
078efddd
HV
665 } else if ((k = endswith(t, " left"))) {
666 t = strndupa(t, k - t);
1fcf71f5 667
e4eaf99a 668 r = parse_sec(t, &plus);
1fcf71f5
LP
669 if (r < 0)
670 return r;
671
decad910 672 goto finish;
9a98c7a1
LP
673 }
674
21b3a0fc 675 /* See if the timestamp is suffixed with UTC */
e4eaf99a
HV
676 utc = endswith_no_case(t, " UTC");
677 if (utc)
078efddd 678 t = strndupa(t, utc - t);
21b3a0fc
LP
679 else {
680 const char *e = NULL;
681 int j;
682
683 tzset();
684
685 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
686 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
687 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
688 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
689 * support arbitrary timezone specifications. */
e4eaf99a 690
21b3a0fc
LP
691 for (j = 0; j <= 1; j++) {
692
693 if (isempty(tzname[j]))
694 continue;
695
696 e = endswith_no_case(t, tzname[j]);
697 if (!e)
698 continue;
699 if (e == t)
700 continue;
701 if (e[-1] != ' ')
702 continue;
703
704 break;
705 }
706
707 if (IN_SET(j, 0, 1)) {
708 /* Found one of the two timezones specified. */
709 t = strndupa(t, e - t - 1);
710 dst = j;
711 tzn = tzname[j];
712 }
713 }
714
715 x = (time_t) (ret / USEC_PER_SEC);
e4eaf99a
HV
716 x_usec = 0;
717
21b3a0fc
LP
718 if (!localtime_or_gmtime_r(&x, &tm, utc))
719 return -EINVAL;
720
721 tm.tm_isdst = dst;
722 if (tzn)
723 tm.tm_zone = tzn;
e4eaf99a
HV
724
725 if (streq(t, "today")) {
726 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
727 goto from_tm;
728
729 } else if (streq(t, "yesterday")) {
313cefa1 730 tm.tm_mday--;
e4eaf99a
HV
731 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
732 goto from_tm;
733
734 } else if (streq(t, "tomorrow")) {
313cefa1 735 tm.tm_mday++;
e4eaf99a
HV
736 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
737 goto from_tm;
738 }
739
92134489
LP
740 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
741 size_t skip;
742
743 if (!startswith_no_case(t, day_nr[i].name))
744 continue;
745
746 skip = strlen(day_nr[i].name);
747 if (t[skip] != ' ')
748 continue;
749
750 weekday = day_nr[i].nr;
751 t += skip + 1;
752 break;
753 }
754
9a98c7a1
LP
755 copy = tm;
756 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
e4eaf99a
HV
757 if (k) {
758 if (*k == '.')
759 goto parse_usec;
760 else if (*k == 0)
761 goto from_tm;
762 }
9a98c7a1
LP
763
764 tm = copy;
765 k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
e4eaf99a
HV
766 if (k) {
767 if (*k == '.')
768 goto parse_usec;
769 else if (*k == 0)
770 goto from_tm;
771 }
9a98c7a1
LP
772
773 tm = copy;
774 k = strptime(t, "%y-%m-%d %H:%M", &tm);
775 if (k && *k == 0) {
776 tm.tm_sec = 0;
e4eaf99a 777 goto from_tm;
9a98c7a1
LP
778 }
779
780 tm = copy;
781 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
782 if (k && *k == 0) {
783 tm.tm_sec = 0;
e4eaf99a 784 goto from_tm;
9a98c7a1
LP
785 }
786
787 tm = copy;
788 k = strptime(t, "%y-%m-%d", &tm);
789 if (k && *k == 0) {
790 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
e4eaf99a 791 goto from_tm;
9a98c7a1
LP
792 }
793
794 tm = copy;
795 k = strptime(t, "%Y-%m-%d", &tm);
796 if (k && *k == 0) {
797 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
e4eaf99a 798 goto from_tm;
9a98c7a1
LP
799 }
800
801 tm = copy;
802 k = strptime(t, "%H:%M:%S", &tm);
e4eaf99a
HV
803 if (k) {
804 if (*k == '.')
805 goto parse_usec;
806 else if (*k == 0)
807 goto from_tm;
808 }
9a98c7a1
LP
809
810 tm = copy;
811 k = strptime(t, "%H:%M", &tm);
812 if (k && *k == 0) {
813 tm.tm_sec = 0;
e4eaf99a 814 goto from_tm;
9a98c7a1
LP
815 }
816
817 return -EINVAL;
818
e4eaf99a
HV
819parse_usec:
820 {
436dd70f 821 unsigned add;
e4eaf99a
HV
822
823 k++;
436dd70f
HV
824 r = parse_fractional_part_u(&k, 6, &add);
825 if (r < 0)
e4eaf99a
HV
826 return -EINVAL;
827
436dd70f 828 if (*k)
e4eaf99a
HV
829 return -EINVAL;
830
436dd70f 831 x_usec = add;
e4eaf99a
HV
832 }
833
834from_tm:
835 x = mktime_or_timegm(&tm, utc);
c477ff14 836 if (x < 0)
9a98c7a1
LP
837 return -EINVAL;
838
92134489
LP
839 if (weekday >= 0 && tm.tm_wday != weekday)
840 return -EINVAL;
841
e4eaf99a 842 ret = (usec_t) x * USEC_PER_SEC + x_usec;
1bb4b028
LP
843 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
844 return -EINVAL;
9a98c7a1 845
e4eaf99a 846finish:
315782db
LP
847 if (ret + plus < ret) /* overflow? */
848 return -EINVAL;
9a98c7a1 849 ret += plus;
1bb4b028
LP
850 if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
851 return -EINVAL;
852
9a98c7a1
LP
853 if (ret > minus)
854 ret -= minus;
855 else
856 ret = 0;
857
858 *usec = ret;
859
860 return 0;
861}
862
240a7ba9 863static char* extract_multiplier(char *p, usec_t *multiplier) {
9a98c7a1
LP
864 static const struct {
865 const char *suffix;
866 usec_t usec;
867 } table[] = {
eb55ec9f
LP
868 { "seconds", USEC_PER_SEC },
869 { "second", USEC_PER_SEC },
870 { "sec", USEC_PER_SEC },
871 { "s", USEC_PER_SEC },
9a98c7a1 872 { "minutes", USEC_PER_MINUTE },
eb55ec9f
LP
873 { "minute", USEC_PER_MINUTE },
874 { "min", USEC_PER_MINUTE },
875 { "months", USEC_PER_MONTH },
876 { "month", USEC_PER_MONTH },
877 { "M", USEC_PER_MONTH },
878 { "msec", USEC_PER_MSEC },
879 { "ms", USEC_PER_MSEC },
880 { "m", USEC_PER_MINUTE },
881 { "hours", USEC_PER_HOUR },
882 { "hour", USEC_PER_HOUR },
883 { "hr", USEC_PER_HOUR },
884 { "h", USEC_PER_HOUR },
885 { "days", USEC_PER_DAY },
886 { "day", USEC_PER_DAY },
887 { "d", USEC_PER_DAY },
888 { "weeks", USEC_PER_WEEK },
889 { "week", USEC_PER_WEEK },
890 { "w", USEC_PER_WEEK },
891 { "years", USEC_PER_YEAR },
892 { "year", USEC_PER_YEAR },
893 { "y", USEC_PER_YEAR },
894 { "usec", 1ULL },
895 { "us", 1ULL },
5efdbf11 896 { "µs", 1ULL },
9a98c7a1 897 };
240a7ba9
ZJS
898 unsigned i;
899
900 for (i = 0; i < ELEMENTSOF(table); i++) {
901 char *e;
902
903 e = startswith(p, table[i].suffix);
904 if (e) {
905 *multiplier = table[i].usec;
906 return e;
907 }
908 }
9a98c7a1 909
240a7ba9
ZJS
910 return p;
911}
912
913int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
b1d6dcf5 914 const char *p, *s;
9a98c7a1 915 usec_t r = 0;
cb0dac05 916 bool something = false;
9a98c7a1
LP
917
918 assert(t);
919 assert(usec);
519cffec 920 assert(default_unit > 0);
9a98c7a1
LP
921
922 p = t;
b1d6dcf5
ZJS
923
924 p += strspn(p, WHITESPACE);
925 s = startswith(p, "infinity");
926 if (s) {
927 s += strspn(s, WHITESPACE);
928 if (*s != 0)
929 return -EINVAL;
930
931 *usec = USEC_INFINITY;
932 return 0;
933 }
934
cb0dac05
LP
935 for (;;) {
936 long long l, z = 0;
9a98c7a1 937 char *e;
240a7ba9
ZJS
938 unsigned n = 0;
939 usec_t multiplier = default_unit, k;
cb0dac05
LP
940
941 p += strspn(p, WHITESPACE);
942
943 if (*p == 0) {
944 if (!something)
945 return -EINVAL;
946
947 break;
948 }
9a98c7a1
LP
949
950 errno = 0;
951 l = strtoll(p, &e, 10);
8333c77e 952 if (errno > 0)
9a98c7a1 953 return -errno;
9a98c7a1
LP
954 if (l < 0)
955 return -ERANGE;
956
cb0dac05
LP
957 if (*e == '.') {
958 char *b = e + 1;
959
960 errno = 0;
961 z = strtoll(b, &e, 10);
962 if (errno > 0)
963 return -errno;
964
965 if (z < 0)
966 return -ERANGE;
967
968 if (e == b)
969 return -EINVAL;
970
971 n = e - b;
972
973 } else if (e == p)
9a98c7a1
LP
974 return -EINVAL;
975
976 e += strspn(e, WHITESPACE);
240a7ba9 977 p = extract_multiplier(e, &multiplier);
9a98c7a1 978
519cffec
LP
979 something = true;
980
981 k = (usec_t) z * multiplier;
982
983 for (; n > 0; n--)
984 k /= 10;
985
986 r += (usec_t) l * multiplier + k;
cb0dac05 987 }
9a98c7a1
LP
988
989 *usec = r;
990
991 return 0;
992}
993
519cffec
LP
994int parse_sec(const char *t, usec_t *usec) {
995 return parse_time(t, usec, USEC_PER_SEC);
996}
997
9a98c7a1
LP
998int parse_nsec(const char *t, nsec_t *nsec) {
999 static const struct {
1000 const char *suffix;
1001 nsec_t nsec;
1002 } table[] = {
1003 { "seconds", NSEC_PER_SEC },
1004 { "second", NSEC_PER_SEC },
1005 { "sec", NSEC_PER_SEC },
1006 { "s", NSEC_PER_SEC },
1007 { "minutes", NSEC_PER_MINUTE },
1008 { "minute", NSEC_PER_MINUTE },
1009 { "min", NSEC_PER_MINUTE },
1010 { "months", NSEC_PER_MONTH },
1011 { "month", NSEC_PER_MONTH },
1012 { "msec", NSEC_PER_MSEC },
1013 { "ms", NSEC_PER_MSEC },
1014 { "m", NSEC_PER_MINUTE },
1015 { "hours", NSEC_PER_HOUR },
1016 { "hour", NSEC_PER_HOUR },
1017 { "hr", NSEC_PER_HOUR },
1018 { "h", NSEC_PER_HOUR },
1019 { "days", NSEC_PER_DAY },
1020 { "day", NSEC_PER_DAY },
1021 { "d", NSEC_PER_DAY },
1022 { "weeks", NSEC_PER_WEEK },
1023 { "week", NSEC_PER_WEEK },
1024 { "w", NSEC_PER_WEEK },
1025 { "years", NSEC_PER_YEAR },
1026 { "year", NSEC_PER_YEAR },
1027 { "y", NSEC_PER_YEAR },
1028 { "usec", NSEC_PER_USEC },
1029 { "us", NSEC_PER_USEC },
5efdbf11 1030 { "µs", NSEC_PER_USEC },
9a98c7a1
LP
1031 { "nsec", 1ULL },
1032 { "ns", 1ULL },
1033 { "", 1ULL }, /* default is nsec */
1034 };
1035
e73c78c2 1036 const char *p, *s;
9a98c7a1 1037 nsec_t r = 0;
cb0dac05 1038 bool something = false;
9a98c7a1
LP
1039
1040 assert(t);
1041 assert(nsec);
1042
1043 p = t;
e73c78c2
LP
1044
1045 p += strspn(p, WHITESPACE);
1046 s = startswith(p, "infinity");
1047 if (s) {
1048 s += strspn(s, WHITESPACE);
8e8933ca 1049 if (*s != 0)
e73c78c2
LP
1050 return -EINVAL;
1051
1052 *nsec = NSEC_INFINITY;
1053 return 0;
1054 }
1055
cb0dac05
LP
1056 for (;;) {
1057 long long l, z = 0;
9a98c7a1 1058 char *e;
cb0dac05
LP
1059 unsigned i, n = 0;
1060
1061 p += strspn(p, WHITESPACE);
1062
1063 if (*p == 0) {
1064 if (!something)
1065 return -EINVAL;
1066
1067 break;
1068 }
9a98c7a1
LP
1069
1070 errno = 0;
1071 l = strtoll(p, &e, 10);
1072
8333c77e 1073 if (errno > 0)
9a98c7a1
LP
1074 return -errno;
1075
1076 if (l < 0)
1077 return -ERANGE;
1078
cb0dac05
LP
1079 if (*e == '.') {
1080 char *b = e + 1;
1081
1082 errno = 0;
1083 z = strtoll(b, &e, 10);
1084 if (errno > 0)
1085 return -errno;
1086
1087 if (z < 0)
1088 return -ERANGE;
1089
1090 if (e == b)
1091 return -EINVAL;
1092
1093 n = e - b;
1094
1095 } else if (e == p)
9a98c7a1
LP
1096 return -EINVAL;
1097
1098 e += strspn(e, WHITESPACE);
1099
1100 for (i = 0; i < ELEMENTSOF(table); i++)
1101 if (startswith(e, table[i].suffix)) {
cb0dac05
LP
1102 nsec_t k = (nsec_t) z * table[i].nsec;
1103
1104 for (; n > 0; n--)
1105 k /= 10;
1106
1107 r += (nsec_t) l * table[i].nsec + k;
9a98c7a1 1108 p = e + strlen(table[i].suffix);
cb0dac05
LP
1109
1110 something = true;
9a98c7a1
LP
1111 break;
1112 }
1113
1114 if (i >= ELEMENTSOF(table))
1115 return -EINVAL;
1116
cb0dac05 1117 }
9a98c7a1
LP
1118
1119 *nsec = r;
1120
1121 return 0;
1122}
03cc26dd
LP
1123
1124bool ntp_synced(void) {
1125 struct timex txc = {};
1126
1127 if (adjtimex(&txc) < 0)
1128 return false;
1129
1130 if (txc.status & STA_UNSYNC)
1131 return false;
1132
1133 return true;
1134}
75683450
LP
1135
1136int get_timezones(char ***ret) {
1137 _cleanup_fclose_ FILE *f = NULL;
1138 _cleanup_strv_free_ char **zones = NULL;
1139 size_t n_zones = 0, n_allocated = 0;
1140
1141 assert(ret);
1142
1143 zones = strv_new("UTC", NULL);
1144 if (!zones)
1145 return -ENOMEM;
1146
1147 n_allocated = 2;
1148 n_zones = 1;
1149
1150 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1151 if (f) {
1152 char l[LINE_MAX];
1153
1154 FOREACH_LINE(l, f, return -errno) {
1155 char *p, *w;
1156 size_t k;
1157
1158 p = strstrip(l);
1159
1160 if (isempty(p) || *p == '#')
1161 continue;
1162
1163 /* Skip over country code */
1164 p += strcspn(p, WHITESPACE);
1165 p += strspn(p, WHITESPACE);
1166
1167 /* Skip over coordinates */
1168 p += strcspn(p, WHITESPACE);
1169 p += strspn(p, WHITESPACE);
1170
1171 /* Found timezone name */
1172 k = strcspn(p, WHITESPACE);
1173 if (k <= 0)
1174 continue;
1175
1176 w = strndup(p, k);
1177 if (!w)
1178 return -ENOMEM;
1179
1180 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1181 free(w);
1182 return -ENOMEM;
1183 }
1184
1185 zones[n_zones++] = w;
1186 zones[n_zones] = NULL;
1187 }
1188
1189 strv_sort(zones);
1190
1191 } else if (errno != ENOENT)
1192 return -errno;
1193
1194 *ret = zones;
1195 zones = NULL;
1196
1197 return 0;
1198}
1199
1200bool timezone_is_valid(const char *name) {
1201 bool slash = false;
1202 const char *p, *t;
1203 struct stat st;
1204
5c904ba5
LP
1205 if (isempty(name))
1206 return false;
1207
1208 if (name[0] == '/')
75683450
LP
1209 return false;
1210
1211 for (p = name; *p; p++) {
1212 if (!(*p >= '0' && *p <= '9') &&
1213 !(*p >= 'a' && *p <= 'z') &&
1214 !(*p >= 'A' && *p <= 'Z') &&
1215 !(*p == '-' || *p == '_' || *p == '+' || *p == '/'))
1216 return false;
1217
1218 if (*p == '/') {
1219
1220 if (slash)
1221 return false;
1222
1223 slash = true;
1224 } else
1225 slash = false;
1226 }
1227
1228 if (slash)
1229 return false;
1230
63c372cb 1231 t = strjoina("/usr/share/zoneinfo/", name);
75683450
LP
1232 if (stat(t, &st) < 0)
1233 return false;
1234
1235 if (!S_ISREG(st.st_mode))
1236 return false;
1237
1238 return true;
1239}
77ff2de9 1240
3411372e
LP
1241bool clock_boottime_supported(void) {
1242 static int supported = -1;
1243
1244 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1245
1246 if (supported < 0) {
1247 int fd;
1248
1249 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1250 if (fd < 0)
1251 supported = false;
1252 else {
1253 safe_close(fd);
1254 supported = true;
1255 }
77ff2de9
TG
1256 }
1257
3411372e
LP
1258 return supported;
1259}
1260
1261clockid_t clock_boottime_or_monotonic(void) {
1262 if (clock_boottime_supported())
1263 return CLOCK_BOOTTIME;
1264 else
1265 return CLOCK_MONOTONIC;
77ff2de9 1266}
5c904ba5 1267
fe624c4c
LP
1268bool clock_supported(clockid_t clock) {
1269 struct timespec ts;
1270
1271 switch (clock) {
1272
1273 case CLOCK_MONOTONIC:
1274 case CLOCK_REALTIME:
1275 return true;
1276
1277 case CLOCK_BOOTTIME:
1278 return clock_boottime_supported();
1279
1280 case CLOCK_BOOTTIME_ALARM:
1281 if (!clock_boottime_supported())
1282 return false;
1283
ec251fe7 1284 /* fall through */
fe624c4c
LP
1285
1286 default:
1287 /* For everything else, check properly */
1288 return clock_gettime(clock, &ts) >= 0;
1289 }
1290}
1291
64d6c229 1292int get_timezone(char **tz) {
5c904ba5
LP
1293 _cleanup_free_ char *t = NULL;
1294 const char *e;
1295 char *z;
1296 int r;
1297
1298 r = readlink_malloc("/etc/localtime", &t);
1299 if (r < 0)
1300 return r; /* returns EINVAL if not a symlink */
1301
1302 e = path_startswith(t, "/usr/share/zoneinfo/");
1303 if (!e)
1304 e = path_startswith(t, "../usr/share/zoneinfo/");
1305 if (!e)
1306 return -EINVAL;
1307
1308 if (!timezone_is_valid(e))
1309 return -EINVAL;
1310
1311 z = strdup(e);
1312 if (!z)
1313 return -ENOMEM;
1314
64d6c229 1315 *tz = z;
5c904ba5
LP
1316 return 0;
1317}
7c67c79c
HV
1318
1319time_t mktime_or_timegm(struct tm *tm, bool utc) {
1320 return utc ? timegm(tm) : mktime(tm);
1321}
1322
1323struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1324 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1325}
87b8ce69
SS
1326
1327unsigned long usec_to_jiffies(usec_t u) {
1328 static thread_local unsigned long hz = 0;
1329 long r;
1330
1331 if (hz == 0) {
1332 r = sysconf(_SC_CLK_TCK);
1333
1334 assert(r > 0);
70887c5f 1335 hz = r;
87b8ce69
SS
1336 }
1337
1338 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1339}