]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/time-util.c
coredump: fix format string on 32 bits
[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
a2daa2f0 188 if (ts->tv_sec == (time_t) -1 && ts->tv_nsec == (long) -1)
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
a2daa2f0 202 if (ts->tv_sec == (time_t) -1 && ts->tv_nsec == (long) -1)
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
3a43da28 214 if (u == USEC_INFINITY) {
9a98c7a1
LP
215 ts->tv_sec = (time_t) -1;
216 ts->tv_nsec = (long) -1;
217 return ts;
218 }
219
220 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
221 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
222
223 return ts;
224}
225
226usec_t timeval_load(const struct timeval *tv) {
227 assert(tv);
228
229 if (tv->tv_sec == (time_t) -1 &&
230 tv->tv_usec == (suseconds_t) -1)
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
3a43da28 244 if (u == USEC_INFINITY) {
9a98c7a1
LP
245 tv->tv_sec = (time_t) -1;
246 tv->tv_usec = (suseconds_t) -1;
4d89874a
ZJS
247 } else {
248 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
249 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
9a98c7a1
LP
250 }
251
9a98c7a1
LP
252 return tv;
253}
254
21b3a0fc
LP
255static char *format_timestamp_internal(
256 char *buf,
257 size_t l,
258 usec_t t,
259 bool utc,
260 bool us) {
261
262 /* The weekdays in non-localized (English) form. We use this instead of the localized form, so that our
263 * generated timestamps may be parsed with parse_timestamp(), and always read the same. */
264 static const char * const weekdays[] = {
265 [0] = "Sun",
266 [1] = "Mon",
267 [2] = "Tue",
268 [3] = "Wed",
269 [4] = "Thu",
270 [5] = "Fri",
271 [6] = "Sat",
272 };
273
9a98c7a1
LP
274 struct tm tm;
275 time_t sec;
21b3a0fc 276 size_t n;
9a98c7a1
LP
277
278 assert(buf);
9a98c7a1 279
21b3a0fc
LP
280 if (l <
281 3 + /* week day */
282 1 + 10 + /* space and date */
283 1 + 8 + /* space and time */
284 (us ? 1 + 6 : 0) + /* "." and microsecond part */
285 1 + 1 + /* space and shortest possible zone */
286 1)
287 return NULL; /* Not enough space even for the shortest form. */
3a43da28 288 if (t <= 0 || t == USEC_INFINITY)
21b3a0fc
LP
289 return NULL; /* Timestamp is unset */
290
291 sec = (time_t) (t / USEC_PER_SEC); /* Round down */
292 if ((usec_t) sec != (t / USEC_PER_SEC))
293 return NULL; /* overflow? */
294
295 if (!localtime_or_gmtime_r(&sec, &tm, utc))
9a98c7a1
LP
296 return NULL;
297
21b3a0fc
LP
298 /* Start with the week day */
299 assert((size_t) tm.tm_wday < ELEMENTSOF(weekdays));
300 memcpy(buf, weekdays[tm.tm_wday], 4);
9a98c7a1 301
21b3a0fc
LP
302 /* Add the main components */
303 if (strftime(buf + 3, l - 3, " %Y-%m-%d %H:%M:%S", &tm) <= 0)
304 return NULL; /* Doesn't fit */
0056086a 305
21b3a0fc 306 /* Append the microseconds part, if that's requested */
0056086a 307 if (us) {
21b3a0fc
LP
308 n = strlen(buf);
309 if (n + 8 > l)
310 return NULL; /* Microseconds part doesn't fit. */
311
312 sprintf(buf + n, ".%06llu", (unsigned long long) (t % USEC_PER_SEC));
313 }
314
315 /* Append the timezone */
316 n = strlen(buf);
317 if (utc) {
318 /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r() normally uses the
319 * obsolete "GMT" instead. */
320 if (n + 5 > l)
321 return NULL; /* "UTC" doesn't fit. */
322
323 strcpy(buf + n, " UTC");
324
325 } else if (!isempty(tm.tm_zone)) {
326 size_t tn;
327
328 /* An explicit timezone is specified, let's use it, if it fits */
329 tn = strlen(tm.tm_zone);
330 if (n + 1 + tn + 1 > l) {
331 /* The full time zone does not fit in. Yuck. */
332
333 if (n + 1 + _POSIX_TZNAME_MAX + 1 > l)
334 return NULL; /* Not even enough space for the POSIX minimum (of 6)? In that case, complain that it doesn't fit */
335
336 /* So the time zone doesn't fit in fully, but the caller passed enough space for the POSIX
337 * minimum time zone length. In this case suppress the timezone entirely, in order not to dump
338 * an overly long, hard to read string on the user. This should be safe, because the user will
339 * assume the local timezone anyway if none is shown. And so does parse_timestamp(). */
340 } else {
341 buf[n++] = ' ';
342 strcpy(buf + n, tm.tm_zone);
343 }
0056086a 344 }
9a98c7a1
LP
345
346 return buf;
347}
348
a62e83b4 349char *format_timestamp(char *buf, size_t l, usec_t t) {
0056086a 350 return format_timestamp_internal(buf, l, t, false, false);
a62e83b4
JS
351}
352
5ab99e07 353char *format_timestamp_utc(char *buf, size_t l, usec_t t) {
0056086a 354 return format_timestamp_internal(buf, l, t, true, false);
f02d8367
ZJS
355}
356
5ab99e07 357char *format_timestamp_us(char *buf, size_t l, usec_t t) {
0056086a 358 return format_timestamp_internal(buf, l, t, false, true);
5ab99e07
LP
359}
360
361char *format_timestamp_us_utc(char *buf, size_t l, usec_t t) {
0056086a 362 return format_timestamp_internal(buf, l, t, true, true);
5ab99e07
LP
363}
364
bbb8486e 365char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
1fcf71f5 366 const char *s;
9a98c7a1
LP
367 usec_t n, d;
368
65de0395 369 if (t <= 0 || t == USEC_INFINITY)
9a98c7a1
LP
370 return NULL;
371
65de0395 372 n = now(CLOCK_REALTIME);
1fcf71f5
LP
373 if (n > t) {
374 d = n - t;
375 s = "ago";
376 } else {
377 d = t - n;
378 s = "left";
379 }
9a98c7a1
LP
380
381 if (d >= USEC_PER_YEAR)
609e002e 382 snprintf(buf, l, USEC_FMT " years " USEC_FMT " months %s",
de0671ee
ZJS
383 d / USEC_PER_YEAR,
384 (d % USEC_PER_YEAR) / USEC_PER_MONTH, s);
9a98c7a1 385 else if (d >= USEC_PER_MONTH)
609e002e 386 snprintf(buf, l, USEC_FMT " months " USEC_FMT " days %s",
de0671ee
ZJS
387 d / USEC_PER_MONTH,
388 (d % USEC_PER_MONTH) / USEC_PER_DAY, s);
9a98c7a1 389 else if (d >= USEC_PER_WEEK)
609e002e 390 snprintf(buf, l, USEC_FMT " weeks " USEC_FMT " days %s",
de0671ee
ZJS
391 d / USEC_PER_WEEK,
392 (d % USEC_PER_WEEK) / USEC_PER_DAY, s);
9a98c7a1 393 else if (d >= 2*USEC_PER_DAY)
609e002e 394 snprintf(buf, l, USEC_FMT " days %s", d / USEC_PER_DAY, s);
9a98c7a1 395 else if (d >= 25*USEC_PER_HOUR)
609e002e 396 snprintf(buf, l, "1 day " USEC_FMT "h %s",
de0671ee 397 (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
9a98c7a1 398 else if (d >= 6*USEC_PER_HOUR)
609e002e 399 snprintf(buf, l, USEC_FMT "h %s",
de0671ee 400 d / USEC_PER_HOUR, s);
9a98c7a1 401 else if (d >= USEC_PER_HOUR)
609e002e 402 snprintf(buf, l, USEC_FMT "h " USEC_FMT "min %s",
de0671ee
ZJS
403 d / USEC_PER_HOUR,
404 (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
9a98c7a1 405 else if (d >= 5*USEC_PER_MINUTE)
609e002e 406 snprintf(buf, l, USEC_FMT "min %s",
de0671ee 407 d / USEC_PER_MINUTE, s);
9a98c7a1 408 else if (d >= USEC_PER_MINUTE)
609e002e 409 snprintf(buf, l, USEC_FMT "min " USEC_FMT "s %s",
de0671ee
ZJS
410 d / USEC_PER_MINUTE,
411 (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
9a98c7a1 412 else if (d >= USEC_PER_SEC)
609e002e 413 snprintf(buf, l, USEC_FMT "s %s",
de0671ee 414 d / USEC_PER_SEC, s);
9a98c7a1 415 else if (d >= USEC_PER_MSEC)
609e002e 416 snprintf(buf, l, USEC_FMT "ms %s",
de0671ee 417 d / USEC_PER_MSEC, s);
9a98c7a1 418 else if (d > 0)
de0671ee
ZJS
419 snprintf(buf, l, USEC_FMT"us %s",
420 d, s);
9a98c7a1
LP
421 else
422 snprintf(buf, l, "now");
423
424 buf[l-1] = 0;
425 return buf;
426}
427
2fa4092c 428char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
9a98c7a1
LP
429 static const struct {
430 const char *suffix;
431 usec_t usec;
432 } table[] = {
eb55ec9f
LP
433 { "y", USEC_PER_YEAR },
434 { "month", USEC_PER_MONTH },
435 { "w", USEC_PER_WEEK },
436 { "d", USEC_PER_DAY },
437 { "h", USEC_PER_HOUR },
438 { "min", USEC_PER_MINUTE },
439 { "s", USEC_PER_SEC },
440 { "ms", USEC_PER_MSEC },
441 { "us", 1 },
9a98c7a1
LP
442 };
443
444 unsigned i;
445 char *p = buf;
2fa4092c 446 bool something = false;
9a98c7a1
LP
447
448 assert(buf);
449 assert(l > 0);
450
bb1fada8
LP
451 if (t == USEC_INFINITY) {
452 strncpy(p, "infinity", l-1);
453 p[l-1] = 0;
454 return p;
455 }
456
457 if (t <= 0) {
458 strncpy(p, "0", l-1);
7c537b2e
LP
459 p[l-1] = 0;
460 return p;
461 }
462
7f602784 463 /* The result of this function can be parsed with parse_sec */
9a98c7a1
LP
464
465 for (i = 0; i < ELEMENTSOF(table); i++) {
7759ecb2 466 int k = 0;
9a98c7a1 467 size_t n;
2fa4092c
LP
468 bool done = false;
469 usec_t a, b;
470
7c537b2e
LP
471 if (t <= 0)
472 break;
2fa4092c 473
7c537b2e 474 if (t < accuracy && something)
2fa4092c 475 break;
9a98c7a1
LP
476
477 if (t < table[i].usec)
478 continue;
479
480 if (l <= 1)
481 break;
482
2fa4092c
LP
483 a = t / table[i].usec;
484 b = t % table[i].usec;
485
486 /* Let's see if we should shows this in dot notation */
487 if (t < USEC_PER_MINUTE && b > 0) {
488 usec_t cc;
489 int j;
490
491 j = 0;
492 for (cc = table[i].usec; cc > 1; cc /= 10)
493 j++;
494
495 for (cc = accuracy; cc > 1; cc /= 10) {
496 b /= 10;
497 j--;
498 }
499
500 if (j > 0) {
501 k = snprintf(p, l,
de0671ee 502 "%s"USEC_FMT".%0*llu%s",
2fa4092c 503 p > buf ? " " : "",
de0671ee 504 a,
2fa4092c
LP
505 j,
506 (unsigned long long) b,
507 table[i].suffix);
508
509 t = 0;
510 done = true;
511 }
512 }
513
514 /* No? Then let's show it normally */
515 if (!done) {
516 k = snprintf(p, l,
de0671ee 517 "%s"USEC_FMT"%s",
2fa4092c 518 p > buf ? " " : "",
de0671ee 519 a,
2fa4092c
LP
520 table[i].suffix);
521
522 t = b;
523 }
524
9a98c7a1
LP
525 n = MIN((size_t) k, l);
526
527 l -= n;
528 p += n;
529
2fa4092c 530 something = true;
9a98c7a1
LP
531 }
532
533 *p = 0;
534
535 return buf;
536}
537
538void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
539
540 assert(f);
541 assert(name);
542 assert(t);
543
544 if (!dual_timestamp_is_set(t))
545 return;
546
de0671ee 547 fprintf(f, "%s="USEC_FMT" "USEC_FMT"\n",
9a98c7a1 548 name,
de0671ee
ZJS
549 t->realtime,
550 t->monotonic);
9a98c7a1
LP
551}
552
e911de99 553int dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
9a98c7a1
LP
554 unsigned long long a, b;
555
556 assert(value);
557 assert(t);
558
e911de99 559 if (sscanf(value, "%llu %llu", &a, &b) != 2) {
b895a735 560 log_debug("Failed to parse dual timestamp value \"%s\": %m", value);
e911de99 561 return -EINVAL;
9a98c7a1 562 }
e911de99
LP
563
564 t->realtime = a;
565 t->monotonic = b;
566
567 return 0;
9a98c7a1
LP
568}
569
b895a735 570int timestamp_deserialize(const char *value, usec_t *timestamp) {
ebf30a08
AK
571 int r;
572
573 assert(value);
574
575 r = safe_atou64(value, timestamp);
ebf30a08 576 if (r < 0)
b895a735 577 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
ebf30a08
AK
578
579 return r;
580}
581
9a98c7a1 582int parse_timestamp(const char *t, usec_t *usec) {
92134489
LP
583 static const struct {
584 const char *name;
585 const int nr;
586 } day_nr[] = {
587 { "Sunday", 0 },
588 { "Sun", 0 },
589 { "Monday", 1 },
590 { "Mon", 1 },
591 { "Tuesday", 2 },
592 { "Tue", 2 },
593 { "Wednesday", 3 },
594 { "Wed", 3 },
595 { "Thursday", 4 },
596 { "Thu", 4 },
597 { "Friday", 5 },
598 { "Fri", 5 },
599 { "Saturday", 6 },
600 { "Sat", 6 },
601 };
602
21b3a0fc 603 const char *k, *utc, *tzn = NULL;
9a98c7a1
LP
604 struct tm tm, copy;
605 time_t x;
e4eaf99a 606 usec_t x_usec, plus = 0, minus = 0, ret;
21b3a0fc 607 int r, weekday = -1, dst = -1;
92134489 608 unsigned i;
9a98c7a1
LP
609
610 /*
611 * Allowed syntaxes:
612 *
613 * 2012-09-22 16:34:22
614 * 2012-09-22 16:34 (seconds will be set to 0)
615 * 2012-09-22 (time will be set to 00:00:00)
616 * 16:34:22 (date will be set to today)
617 * 16:34 (date will be set to today, seconds to 0)
618 * now
619 * yesterday (time is set to 00:00:00)
620 * today (time is set to 00:00:00)
621 * tomorrow (time is set to 00:00:00)
622 * +5min
623 * -5days
5ba6e094 624 * @2147483647 (seconds since epoch)
9a98c7a1
LP
625 *
626 */
627
628 assert(t);
629 assert(usec);
630
e4eaf99a
HV
631 if (t[0] == '@')
632 return parse_sec(t + 1, usec);
9a98c7a1 633
e4eaf99a 634 ret = now(CLOCK_REALTIME);
9a98c7a1 635
e4eaf99a 636 if (streq(t, "now"))
9a98c7a1
LP
637 goto finish;
638
e4eaf99a 639 else if (t[0] == '+') {
7f602784 640 r = parse_sec(t+1, &plus);
9a98c7a1
LP
641 if (r < 0)
642 return r;
643
644 goto finish;
9a98c7a1 645
5ba6e094 646 } else if (t[0] == '-') {
7f602784 647 r = parse_sec(t+1, &minus);
9a98c7a1
LP
648 if (r < 0)
649 return r;
650
651 goto finish;
decad910 652
078efddd
HV
653 } else if ((k = endswith(t, " ago"))) {
654 t = strndupa(t, k - t);
decad910 655
e4eaf99a 656 r = parse_sec(t, &minus);
decad910
LP
657 if (r < 0)
658 return r;
659
1fcf71f5 660 goto finish;
1fcf71f5 661
078efddd
HV
662 } else if ((k = endswith(t, " left"))) {
663 t = strndupa(t, k - t);
1fcf71f5 664
e4eaf99a 665 r = parse_sec(t, &plus);
1fcf71f5
LP
666 if (r < 0)
667 return r;
668
decad910 669 goto finish;
9a98c7a1
LP
670 }
671
21b3a0fc 672 /* See if the timestamp is suffixed with UTC */
e4eaf99a
HV
673 utc = endswith_no_case(t, " UTC");
674 if (utc)
078efddd 675 t = strndupa(t, utc - t);
21b3a0fc
LP
676 else {
677 const char *e = NULL;
678 int j;
679
680 tzset();
681
682 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
683 * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
684 * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
685 * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
686 * support arbitrary timezone specifications. */
e4eaf99a 687
21b3a0fc
LP
688 for (j = 0; j <= 1; j++) {
689
690 if (isempty(tzname[j]))
691 continue;
692
693 e = endswith_no_case(t, tzname[j]);
694 if (!e)
695 continue;
696 if (e == t)
697 continue;
698 if (e[-1] != ' ')
699 continue;
700
701 break;
702 }
703
704 if (IN_SET(j, 0, 1)) {
705 /* Found one of the two timezones specified. */
706 t = strndupa(t, e - t - 1);
707 dst = j;
708 tzn = tzname[j];
709 }
710 }
711
712 x = (time_t) (ret / USEC_PER_SEC);
e4eaf99a
HV
713 x_usec = 0;
714
21b3a0fc
LP
715 if (!localtime_or_gmtime_r(&x, &tm, utc))
716 return -EINVAL;
717
718 tm.tm_isdst = dst;
719 if (tzn)
720 tm.tm_zone = tzn;
e4eaf99a
HV
721
722 if (streq(t, "today")) {
723 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
724 goto from_tm;
725
726 } else if (streq(t, "yesterday")) {
313cefa1 727 tm.tm_mday--;
e4eaf99a
HV
728 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
729 goto from_tm;
730
731 } else if (streq(t, "tomorrow")) {
313cefa1 732 tm.tm_mday++;
e4eaf99a
HV
733 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
734 goto from_tm;
735 }
736
92134489
LP
737 for (i = 0; i < ELEMENTSOF(day_nr); i++) {
738 size_t skip;
739
740 if (!startswith_no_case(t, day_nr[i].name))
741 continue;
742
743 skip = strlen(day_nr[i].name);
744 if (t[skip] != ' ')
745 continue;
746
747 weekday = day_nr[i].nr;
748 t += skip + 1;
749 break;
750 }
751
9a98c7a1
LP
752 copy = tm;
753 k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
e4eaf99a
HV
754 if (k) {
755 if (*k == '.')
756 goto parse_usec;
757 else if (*k == 0)
758 goto from_tm;
759 }
9a98c7a1
LP
760
761 tm = copy;
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", &tm);
772 if (k && *k == 0) {
773 tm.tm_sec = 0;
e4eaf99a 774 goto from_tm;
9a98c7a1
LP
775 }
776
777 tm = copy;
778 k = strptime(t, "%Y-%m-%d %H:%M", &tm);
779 if (k && *k == 0) {
780 tm.tm_sec = 0;
e4eaf99a 781 goto from_tm;
9a98c7a1
LP
782 }
783
784 tm = copy;
785 k = strptime(t, "%y-%m-%d", &tm);
786 if (k && *k == 0) {
787 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
e4eaf99a 788 goto from_tm;
9a98c7a1
LP
789 }
790
791 tm = copy;
792 k = strptime(t, "%Y-%m-%d", &tm);
793 if (k && *k == 0) {
794 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
e4eaf99a 795 goto from_tm;
9a98c7a1
LP
796 }
797
798 tm = copy;
799 k = strptime(t, "%H:%M:%S", &tm);
e4eaf99a
HV
800 if (k) {
801 if (*k == '.')
802 goto parse_usec;
803 else if (*k == 0)
804 goto from_tm;
805 }
9a98c7a1
LP
806
807 tm = copy;
808 k = strptime(t, "%H:%M", &tm);
809 if (k && *k == 0) {
810 tm.tm_sec = 0;
e4eaf99a 811 goto from_tm;
9a98c7a1
LP
812 }
813
814 return -EINVAL;
815
e4eaf99a
HV
816parse_usec:
817 {
436dd70f 818 unsigned add;
e4eaf99a
HV
819
820 k++;
436dd70f
HV
821 r = parse_fractional_part_u(&k, 6, &add);
822 if (r < 0)
e4eaf99a
HV
823 return -EINVAL;
824
436dd70f 825 if (*k)
e4eaf99a
HV
826 return -EINVAL;
827
436dd70f 828 x_usec = add;
e4eaf99a
HV
829 }
830
831from_tm:
832 x = mktime_or_timegm(&tm, utc);
9a98c7a1
LP
833 if (x == (time_t) -1)
834 return -EINVAL;
835
92134489
LP
836 if (weekday >= 0 && tm.tm_wday != weekday)
837 return -EINVAL;
838
e4eaf99a 839 ret = (usec_t) x * USEC_PER_SEC + x_usec;
9a98c7a1 840
e4eaf99a 841finish:
9a98c7a1
LP
842 ret += plus;
843 if (ret > minus)
844 ret -= minus;
845 else
846 ret = 0;
847
848 *usec = ret;
849
850 return 0;
851}
852
240a7ba9 853static char* extract_multiplier(char *p, usec_t *multiplier) {
9a98c7a1
LP
854 static const struct {
855 const char *suffix;
856 usec_t usec;
857 } table[] = {
eb55ec9f
LP
858 { "seconds", USEC_PER_SEC },
859 { "second", USEC_PER_SEC },
860 { "sec", USEC_PER_SEC },
861 { "s", USEC_PER_SEC },
9a98c7a1 862 { "minutes", USEC_PER_MINUTE },
eb55ec9f
LP
863 { "minute", USEC_PER_MINUTE },
864 { "min", USEC_PER_MINUTE },
865 { "months", USEC_PER_MONTH },
866 { "month", USEC_PER_MONTH },
867 { "M", USEC_PER_MONTH },
868 { "msec", USEC_PER_MSEC },
869 { "ms", USEC_PER_MSEC },
870 { "m", USEC_PER_MINUTE },
871 { "hours", USEC_PER_HOUR },
872 { "hour", USEC_PER_HOUR },
873 { "hr", USEC_PER_HOUR },
874 { "h", USEC_PER_HOUR },
875 { "days", USEC_PER_DAY },
876 { "day", USEC_PER_DAY },
877 { "d", USEC_PER_DAY },
878 { "weeks", USEC_PER_WEEK },
879 { "week", USEC_PER_WEEK },
880 { "w", USEC_PER_WEEK },
881 { "years", USEC_PER_YEAR },
882 { "year", USEC_PER_YEAR },
883 { "y", USEC_PER_YEAR },
884 { "usec", 1ULL },
885 { "us", 1ULL },
9a98c7a1 886 };
240a7ba9
ZJS
887 unsigned i;
888
889 for (i = 0; i < ELEMENTSOF(table); i++) {
890 char *e;
891
892 e = startswith(p, table[i].suffix);
893 if (e) {
894 *multiplier = table[i].usec;
895 return e;
896 }
897 }
9a98c7a1 898
240a7ba9
ZJS
899 return p;
900}
901
902int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
b1d6dcf5 903 const char *p, *s;
9a98c7a1 904 usec_t r = 0;
cb0dac05 905 bool something = false;
9a98c7a1
LP
906
907 assert(t);
908 assert(usec);
519cffec 909 assert(default_unit > 0);
9a98c7a1
LP
910
911 p = t;
b1d6dcf5
ZJS
912
913 p += strspn(p, WHITESPACE);
914 s = startswith(p, "infinity");
915 if (s) {
916 s += strspn(s, WHITESPACE);
917 if (*s != 0)
918 return -EINVAL;
919
920 *usec = USEC_INFINITY;
921 return 0;
922 }
923
cb0dac05
LP
924 for (;;) {
925 long long l, z = 0;
9a98c7a1 926 char *e;
240a7ba9
ZJS
927 unsigned n = 0;
928 usec_t multiplier = default_unit, k;
cb0dac05
LP
929
930 p += strspn(p, WHITESPACE);
931
932 if (*p == 0) {
933 if (!something)
934 return -EINVAL;
935
936 break;
937 }
9a98c7a1
LP
938
939 errno = 0;
940 l = strtoll(p, &e, 10);
8333c77e 941 if (errno > 0)
9a98c7a1 942 return -errno;
9a98c7a1
LP
943 if (l < 0)
944 return -ERANGE;
945
cb0dac05
LP
946 if (*e == '.') {
947 char *b = e + 1;
948
949 errno = 0;
950 z = strtoll(b, &e, 10);
951 if (errno > 0)
952 return -errno;
953
954 if (z < 0)
955 return -ERANGE;
956
957 if (e == b)
958 return -EINVAL;
959
960 n = e - b;
961
962 } else if (e == p)
9a98c7a1
LP
963 return -EINVAL;
964
965 e += strspn(e, WHITESPACE);
240a7ba9 966 p = extract_multiplier(e, &multiplier);
9a98c7a1 967
519cffec
LP
968 something = true;
969
970 k = (usec_t) z * multiplier;
971
972 for (; n > 0; n--)
973 k /= 10;
974
975 r += (usec_t) l * multiplier + k;
cb0dac05 976 }
9a98c7a1
LP
977
978 *usec = r;
979
980 return 0;
981}
982
519cffec
LP
983int parse_sec(const char *t, usec_t *usec) {
984 return parse_time(t, usec, USEC_PER_SEC);
985}
986
9a98c7a1
LP
987int parse_nsec(const char *t, nsec_t *nsec) {
988 static const struct {
989 const char *suffix;
990 nsec_t nsec;
991 } table[] = {
992 { "seconds", NSEC_PER_SEC },
993 { "second", NSEC_PER_SEC },
994 { "sec", NSEC_PER_SEC },
995 { "s", NSEC_PER_SEC },
996 { "minutes", NSEC_PER_MINUTE },
997 { "minute", NSEC_PER_MINUTE },
998 { "min", NSEC_PER_MINUTE },
999 { "months", NSEC_PER_MONTH },
1000 { "month", NSEC_PER_MONTH },
1001 { "msec", NSEC_PER_MSEC },
1002 { "ms", NSEC_PER_MSEC },
1003 { "m", NSEC_PER_MINUTE },
1004 { "hours", NSEC_PER_HOUR },
1005 { "hour", NSEC_PER_HOUR },
1006 { "hr", NSEC_PER_HOUR },
1007 { "h", NSEC_PER_HOUR },
1008 { "days", NSEC_PER_DAY },
1009 { "day", NSEC_PER_DAY },
1010 { "d", NSEC_PER_DAY },
1011 { "weeks", NSEC_PER_WEEK },
1012 { "week", NSEC_PER_WEEK },
1013 { "w", NSEC_PER_WEEK },
1014 { "years", NSEC_PER_YEAR },
1015 { "year", NSEC_PER_YEAR },
1016 { "y", NSEC_PER_YEAR },
1017 { "usec", NSEC_PER_USEC },
1018 { "us", NSEC_PER_USEC },
1019 { "nsec", 1ULL },
1020 { "ns", 1ULL },
1021 { "", 1ULL }, /* default is nsec */
1022 };
1023
e73c78c2 1024 const char *p, *s;
9a98c7a1 1025 nsec_t r = 0;
cb0dac05 1026 bool something = false;
9a98c7a1
LP
1027
1028 assert(t);
1029 assert(nsec);
1030
1031 p = t;
e73c78c2
LP
1032
1033 p += strspn(p, WHITESPACE);
1034 s = startswith(p, "infinity");
1035 if (s) {
1036 s += strspn(s, WHITESPACE);
8e8933ca 1037 if (*s != 0)
e73c78c2
LP
1038 return -EINVAL;
1039
1040 *nsec = NSEC_INFINITY;
1041 return 0;
1042 }
1043
cb0dac05
LP
1044 for (;;) {
1045 long long l, z = 0;
9a98c7a1 1046 char *e;
cb0dac05
LP
1047 unsigned i, n = 0;
1048
1049 p += strspn(p, WHITESPACE);
1050
1051 if (*p == 0) {
1052 if (!something)
1053 return -EINVAL;
1054
1055 break;
1056 }
9a98c7a1
LP
1057
1058 errno = 0;
1059 l = strtoll(p, &e, 10);
1060
8333c77e 1061 if (errno > 0)
9a98c7a1
LP
1062 return -errno;
1063
1064 if (l < 0)
1065 return -ERANGE;
1066
cb0dac05
LP
1067 if (*e == '.') {
1068 char *b = e + 1;
1069
1070 errno = 0;
1071 z = strtoll(b, &e, 10);
1072 if (errno > 0)
1073 return -errno;
1074
1075 if (z < 0)
1076 return -ERANGE;
1077
1078 if (e == b)
1079 return -EINVAL;
1080
1081 n = e - b;
1082
1083 } else if (e == p)
9a98c7a1
LP
1084 return -EINVAL;
1085
1086 e += strspn(e, WHITESPACE);
1087
1088 for (i = 0; i < ELEMENTSOF(table); i++)
1089 if (startswith(e, table[i].suffix)) {
cb0dac05
LP
1090 nsec_t k = (nsec_t) z * table[i].nsec;
1091
1092 for (; n > 0; n--)
1093 k /= 10;
1094
1095 r += (nsec_t) l * table[i].nsec + k;
9a98c7a1 1096 p = e + strlen(table[i].suffix);
cb0dac05
LP
1097
1098 something = true;
9a98c7a1
LP
1099 break;
1100 }
1101
1102 if (i >= ELEMENTSOF(table))
1103 return -EINVAL;
1104
cb0dac05 1105 }
9a98c7a1
LP
1106
1107 *nsec = r;
1108
1109 return 0;
1110}
03cc26dd
LP
1111
1112bool ntp_synced(void) {
1113 struct timex txc = {};
1114
1115 if (adjtimex(&txc) < 0)
1116 return false;
1117
1118 if (txc.status & STA_UNSYNC)
1119 return false;
1120
1121 return true;
1122}
75683450
LP
1123
1124int get_timezones(char ***ret) {
1125 _cleanup_fclose_ FILE *f = NULL;
1126 _cleanup_strv_free_ char **zones = NULL;
1127 size_t n_zones = 0, n_allocated = 0;
1128
1129 assert(ret);
1130
1131 zones = strv_new("UTC", NULL);
1132 if (!zones)
1133 return -ENOMEM;
1134
1135 n_allocated = 2;
1136 n_zones = 1;
1137
1138 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1139 if (f) {
1140 char l[LINE_MAX];
1141
1142 FOREACH_LINE(l, f, return -errno) {
1143 char *p, *w;
1144 size_t k;
1145
1146 p = strstrip(l);
1147
1148 if (isempty(p) || *p == '#')
1149 continue;
1150
1151 /* Skip over country code */
1152 p += strcspn(p, WHITESPACE);
1153 p += strspn(p, WHITESPACE);
1154
1155 /* Skip over coordinates */
1156 p += strcspn(p, WHITESPACE);
1157 p += strspn(p, WHITESPACE);
1158
1159 /* Found timezone name */
1160 k = strcspn(p, WHITESPACE);
1161 if (k <= 0)
1162 continue;
1163
1164 w = strndup(p, k);
1165 if (!w)
1166 return -ENOMEM;
1167
1168 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1169 free(w);
1170 return -ENOMEM;
1171 }
1172
1173 zones[n_zones++] = w;
1174 zones[n_zones] = NULL;
1175 }
1176
1177 strv_sort(zones);
1178
1179 } else if (errno != ENOENT)
1180 return -errno;
1181
1182 *ret = zones;
1183 zones = NULL;
1184
1185 return 0;
1186}
1187
1188bool timezone_is_valid(const char *name) {
1189 bool slash = false;
1190 const char *p, *t;
1191 struct stat st;
1192
5c904ba5
LP
1193 if (isempty(name))
1194 return false;
1195
1196 if (name[0] == '/')
75683450
LP
1197 return false;
1198
1199 for (p = name; *p; p++) {
1200 if (!(*p >= '0' && *p <= '9') &&
1201 !(*p >= 'a' && *p <= 'z') &&
1202 !(*p >= 'A' && *p <= 'Z') &&
1203 !(*p == '-' || *p == '_' || *p == '+' || *p == '/'))
1204 return false;
1205
1206 if (*p == '/') {
1207
1208 if (slash)
1209 return false;
1210
1211 slash = true;
1212 } else
1213 slash = false;
1214 }
1215
1216 if (slash)
1217 return false;
1218
63c372cb 1219 t = strjoina("/usr/share/zoneinfo/", name);
75683450
LP
1220 if (stat(t, &st) < 0)
1221 return false;
1222
1223 if (!S_ISREG(st.st_mode))
1224 return false;
1225
1226 return true;
1227}
77ff2de9 1228
3411372e
LP
1229bool clock_boottime_supported(void) {
1230 static int supported = -1;
1231
1232 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1233
1234 if (supported < 0) {
1235 int fd;
1236
1237 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1238 if (fd < 0)
1239 supported = false;
1240 else {
1241 safe_close(fd);
1242 supported = true;
1243 }
77ff2de9
TG
1244 }
1245
3411372e
LP
1246 return supported;
1247}
1248
1249clockid_t clock_boottime_or_monotonic(void) {
1250 if (clock_boottime_supported())
1251 return CLOCK_BOOTTIME;
1252 else
1253 return CLOCK_MONOTONIC;
77ff2de9 1254}
5c904ba5 1255
fe624c4c
LP
1256bool clock_supported(clockid_t clock) {
1257 struct timespec ts;
1258
1259 switch (clock) {
1260
1261 case CLOCK_MONOTONIC:
1262 case CLOCK_REALTIME:
1263 return true;
1264
1265 case CLOCK_BOOTTIME:
1266 return clock_boottime_supported();
1267
1268 case CLOCK_BOOTTIME_ALARM:
1269 if (!clock_boottime_supported())
1270 return false;
1271
1272 /* fall through, after checking the cached value for CLOCK_BOOTTIME. */
1273
1274 default:
1275 /* For everything else, check properly */
1276 return clock_gettime(clock, &ts) >= 0;
1277 }
1278}
1279
64d6c229 1280int get_timezone(char **tz) {
5c904ba5
LP
1281 _cleanup_free_ char *t = NULL;
1282 const char *e;
1283 char *z;
1284 int r;
1285
1286 r = readlink_malloc("/etc/localtime", &t);
1287 if (r < 0)
1288 return r; /* returns EINVAL if not a symlink */
1289
1290 e = path_startswith(t, "/usr/share/zoneinfo/");
1291 if (!e)
1292 e = path_startswith(t, "../usr/share/zoneinfo/");
1293 if (!e)
1294 return -EINVAL;
1295
1296 if (!timezone_is_valid(e))
1297 return -EINVAL;
1298
1299 z = strdup(e);
1300 if (!z)
1301 return -ENOMEM;
1302
64d6c229 1303 *tz = z;
5c904ba5
LP
1304 return 0;
1305}
7c67c79c
HV
1306
1307time_t mktime_or_timegm(struct tm *tm, bool utc) {
1308 return utc ? timegm(tm) : mktime(tm);
1309}
1310
1311struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1312 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1313}
87b8ce69
SS
1314
1315unsigned long usec_to_jiffies(usec_t u) {
1316 static thread_local unsigned long hz = 0;
1317 long r;
1318
1319 if (hz == 0) {
1320 r = sysconf(_SC_CLK_TCK);
1321
1322 assert(r > 0);
1323 hz = (unsigned long) r;
1324 }
1325
1326 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1327}