]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/time-util.c
nspawn: fix clobbering of selinux context arg
[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
70887c5f 312 sprintf(buf + n, ".%06"PRI_USEC, t % USEC_PER_SEC);
21b3a0fc
LP
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,
70887c5f 502 "%s"USEC_FMT".%0*"PRI_USEC"%s",
2fa4092c 503 p > buf ? " " : "",
de0671ee 504 a,
2fa4092c 505 j,
70887c5f 506 b,
2fa4092c
LP
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 },
5efdbf11 886 { "µs", 1ULL },
9a98c7a1 887 };
240a7ba9
ZJS
888 unsigned i;
889
890 for (i = 0; i < ELEMENTSOF(table); i++) {
891 char *e;
892
893 e = startswith(p, table[i].suffix);
894 if (e) {
895 *multiplier = table[i].usec;
896 return e;
897 }
898 }
9a98c7a1 899
240a7ba9
ZJS
900 return p;
901}
902
903int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
b1d6dcf5 904 const char *p, *s;
9a98c7a1 905 usec_t r = 0;
cb0dac05 906 bool something = false;
9a98c7a1
LP
907
908 assert(t);
909 assert(usec);
519cffec 910 assert(default_unit > 0);
9a98c7a1
LP
911
912 p = t;
b1d6dcf5
ZJS
913
914 p += strspn(p, WHITESPACE);
915 s = startswith(p, "infinity");
916 if (s) {
917 s += strspn(s, WHITESPACE);
918 if (*s != 0)
919 return -EINVAL;
920
921 *usec = USEC_INFINITY;
922 return 0;
923 }
924
cb0dac05
LP
925 for (;;) {
926 long long l, z = 0;
9a98c7a1 927 char *e;
240a7ba9
ZJS
928 unsigned n = 0;
929 usec_t multiplier = default_unit, k;
cb0dac05
LP
930
931 p += strspn(p, WHITESPACE);
932
933 if (*p == 0) {
934 if (!something)
935 return -EINVAL;
936
937 break;
938 }
9a98c7a1
LP
939
940 errno = 0;
941 l = strtoll(p, &e, 10);
8333c77e 942 if (errno > 0)
9a98c7a1 943 return -errno;
9a98c7a1
LP
944 if (l < 0)
945 return -ERANGE;
946
cb0dac05
LP
947 if (*e == '.') {
948 char *b = e + 1;
949
950 errno = 0;
951 z = strtoll(b, &e, 10);
952 if (errno > 0)
953 return -errno;
954
955 if (z < 0)
956 return -ERANGE;
957
958 if (e == b)
959 return -EINVAL;
960
961 n = e - b;
962
963 } else if (e == p)
9a98c7a1
LP
964 return -EINVAL;
965
966 e += strspn(e, WHITESPACE);
240a7ba9 967 p = extract_multiplier(e, &multiplier);
9a98c7a1 968
519cffec
LP
969 something = true;
970
971 k = (usec_t) z * multiplier;
972
973 for (; n > 0; n--)
974 k /= 10;
975
976 r += (usec_t) l * multiplier + k;
cb0dac05 977 }
9a98c7a1
LP
978
979 *usec = r;
980
981 return 0;
982}
983
519cffec
LP
984int parse_sec(const char *t, usec_t *usec) {
985 return parse_time(t, usec, USEC_PER_SEC);
986}
987
9a98c7a1
LP
988int parse_nsec(const char *t, nsec_t *nsec) {
989 static const struct {
990 const char *suffix;
991 nsec_t nsec;
992 } table[] = {
993 { "seconds", NSEC_PER_SEC },
994 { "second", NSEC_PER_SEC },
995 { "sec", NSEC_PER_SEC },
996 { "s", NSEC_PER_SEC },
997 { "minutes", NSEC_PER_MINUTE },
998 { "minute", NSEC_PER_MINUTE },
999 { "min", NSEC_PER_MINUTE },
1000 { "months", NSEC_PER_MONTH },
1001 { "month", NSEC_PER_MONTH },
1002 { "msec", NSEC_PER_MSEC },
1003 { "ms", NSEC_PER_MSEC },
1004 { "m", NSEC_PER_MINUTE },
1005 { "hours", NSEC_PER_HOUR },
1006 { "hour", NSEC_PER_HOUR },
1007 { "hr", NSEC_PER_HOUR },
1008 { "h", NSEC_PER_HOUR },
1009 { "days", NSEC_PER_DAY },
1010 { "day", NSEC_PER_DAY },
1011 { "d", NSEC_PER_DAY },
1012 { "weeks", NSEC_PER_WEEK },
1013 { "week", NSEC_PER_WEEK },
1014 { "w", NSEC_PER_WEEK },
1015 { "years", NSEC_PER_YEAR },
1016 { "year", NSEC_PER_YEAR },
1017 { "y", NSEC_PER_YEAR },
1018 { "usec", NSEC_PER_USEC },
1019 { "us", NSEC_PER_USEC },
5efdbf11 1020 { "µs", NSEC_PER_USEC },
9a98c7a1
LP
1021 { "nsec", 1ULL },
1022 { "ns", 1ULL },
1023 { "", 1ULL }, /* default is nsec */
1024 };
1025
e73c78c2 1026 const char *p, *s;
9a98c7a1 1027 nsec_t r = 0;
cb0dac05 1028 bool something = false;
9a98c7a1
LP
1029
1030 assert(t);
1031 assert(nsec);
1032
1033 p = t;
e73c78c2
LP
1034
1035 p += strspn(p, WHITESPACE);
1036 s = startswith(p, "infinity");
1037 if (s) {
1038 s += strspn(s, WHITESPACE);
8e8933ca 1039 if (*s != 0)
e73c78c2
LP
1040 return -EINVAL;
1041
1042 *nsec = NSEC_INFINITY;
1043 return 0;
1044 }
1045
cb0dac05
LP
1046 for (;;) {
1047 long long l, z = 0;
9a98c7a1 1048 char *e;
cb0dac05
LP
1049 unsigned i, n = 0;
1050
1051 p += strspn(p, WHITESPACE);
1052
1053 if (*p == 0) {
1054 if (!something)
1055 return -EINVAL;
1056
1057 break;
1058 }
9a98c7a1
LP
1059
1060 errno = 0;
1061 l = strtoll(p, &e, 10);
1062
8333c77e 1063 if (errno > 0)
9a98c7a1
LP
1064 return -errno;
1065
1066 if (l < 0)
1067 return -ERANGE;
1068
cb0dac05
LP
1069 if (*e == '.') {
1070 char *b = e + 1;
1071
1072 errno = 0;
1073 z = strtoll(b, &e, 10);
1074 if (errno > 0)
1075 return -errno;
1076
1077 if (z < 0)
1078 return -ERANGE;
1079
1080 if (e == b)
1081 return -EINVAL;
1082
1083 n = e - b;
1084
1085 } else if (e == p)
9a98c7a1
LP
1086 return -EINVAL;
1087
1088 e += strspn(e, WHITESPACE);
1089
1090 for (i = 0; i < ELEMENTSOF(table); i++)
1091 if (startswith(e, table[i].suffix)) {
cb0dac05
LP
1092 nsec_t k = (nsec_t) z * table[i].nsec;
1093
1094 for (; n > 0; n--)
1095 k /= 10;
1096
1097 r += (nsec_t) l * table[i].nsec + k;
9a98c7a1 1098 p = e + strlen(table[i].suffix);
cb0dac05
LP
1099
1100 something = true;
9a98c7a1
LP
1101 break;
1102 }
1103
1104 if (i >= ELEMENTSOF(table))
1105 return -EINVAL;
1106
cb0dac05 1107 }
9a98c7a1
LP
1108
1109 *nsec = r;
1110
1111 return 0;
1112}
03cc26dd
LP
1113
1114bool ntp_synced(void) {
1115 struct timex txc = {};
1116
1117 if (adjtimex(&txc) < 0)
1118 return false;
1119
1120 if (txc.status & STA_UNSYNC)
1121 return false;
1122
1123 return true;
1124}
75683450
LP
1125
1126int get_timezones(char ***ret) {
1127 _cleanup_fclose_ FILE *f = NULL;
1128 _cleanup_strv_free_ char **zones = NULL;
1129 size_t n_zones = 0, n_allocated = 0;
1130
1131 assert(ret);
1132
1133 zones = strv_new("UTC", NULL);
1134 if (!zones)
1135 return -ENOMEM;
1136
1137 n_allocated = 2;
1138 n_zones = 1;
1139
1140 f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1141 if (f) {
1142 char l[LINE_MAX];
1143
1144 FOREACH_LINE(l, f, return -errno) {
1145 char *p, *w;
1146 size_t k;
1147
1148 p = strstrip(l);
1149
1150 if (isempty(p) || *p == '#')
1151 continue;
1152
1153 /* Skip over country code */
1154 p += strcspn(p, WHITESPACE);
1155 p += strspn(p, WHITESPACE);
1156
1157 /* Skip over coordinates */
1158 p += strcspn(p, WHITESPACE);
1159 p += strspn(p, WHITESPACE);
1160
1161 /* Found timezone name */
1162 k = strcspn(p, WHITESPACE);
1163 if (k <= 0)
1164 continue;
1165
1166 w = strndup(p, k);
1167 if (!w)
1168 return -ENOMEM;
1169
1170 if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1171 free(w);
1172 return -ENOMEM;
1173 }
1174
1175 zones[n_zones++] = w;
1176 zones[n_zones] = NULL;
1177 }
1178
1179 strv_sort(zones);
1180
1181 } else if (errno != ENOENT)
1182 return -errno;
1183
1184 *ret = zones;
1185 zones = NULL;
1186
1187 return 0;
1188}
1189
1190bool timezone_is_valid(const char *name) {
1191 bool slash = false;
1192 const char *p, *t;
1193 struct stat st;
1194
5c904ba5
LP
1195 if (isempty(name))
1196 return false;
1197
1198 if (name[0] == '/')
75683450
LP
1199 return false;
1200
1201 for (p = name; *p; p++) {
1202 if (!(*p >= '0' && *p <= '9') &&
1203 !(*p >= 'a' && *p <= 'z') &&
1204 !(*p >= 'A' && *p <= 'Z') &&
1205 !(*p == '-' || *p == '_' || *p == '+' || *p == '/'))
1206 return false;
1207
1208 if (*p == '/') {
1209
1210 if (slash)
1211 return false;
1212
1213 slash = true;
1214 } else
1215 slash = false;
1216 }
1217
1218 if (slash)
1219 return false;
1220
63c372cb 1221 t = strjoina("/usr/share/zoneinfo/", name);
75683450
LP
1222 if (stat(t, &st) < 0)
1223 return false;
1224
1225 if (!S_ISREG(st.st_mode))
1226 return false;
1227
1228 return true;
1229}
77ff2de9 1230
3411372e
LP
1231bool clock_boottime_supported(void) {
1232 static int supported = -1;
1233
1234 /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1235
1236 if (supported < 0) {
1237 int fd;
1238
1239 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1240 if (fd < 0)
1241 supported = false;
1242 else {
1243 safe_close(fd);
1244 supported = true;
1245 }
77ff2de9
TG
1246 }
1247
3411372e
LP
1248 return supported;
1249}
1250
1251clockid_t clock_boottime_or_monotonic(void) {
1252 if (clock_boottime_supported())
1253 return CLOCK_BOOTTIME;
1254 else
1255 return CLOCK_MONOTONIC;
77ff2de9 1256}
5c904ba5 1257
fe624c4c
LP
1258bool clock_supported(clockid_t clock) {
1259 struct timespec ts;
1260
1261 switch (clock) {
1262
1263 case CLOCK_MONOTONIC:
1264 case CLOCK_REALTIME:
1265 return true;
1266
1267 case CLOCK_BOOTTIME:
1268 return clock_boottime_supported();
1269
1270 case CLOCK_BOOTTIME_ALARM:
1271 if (!clock_boottime_supported())
1272 return false;
1273
1274 /* fall through, after checking the cached value for CLOCK_BOOTTIME. */
1275
1276 default:
1277 /* For everything else, check properly */
1278 return clock_gettime(clock, &ts) >= 0;
1279 }
1280}
1281
64d6c229 1282int get_timezone(char **tz) {
5c904ba5
LP
1283 _cleanup_free_ char *t = NULL;
1284 const char *e;
1285 char *z;
1286 int r;
1287
1288 r = readlink_malloc("/etc/localtime", &t);
1289 if (r < 0)
1290 return r; /* returns EINVAL if not a symlink */
1291
1292 e = path_startswith(t, "/usr/share/zoneinfo/");
1293 if (!e)
1294 e = path_startswith(t, "../usr/share/zoneinfo/");
1295 if (!e)
1296 return -EINVAL;
1297
1298 if (!timezone_is_valid(e))
1299 return -EINVAL;
1300
1301 z = strdup(e);
1302 if (!z)
1303 return -ENOMEM;
1304
64d6c229 1305 *tz = z;
5c904ba5
LP
1306 return 0;
1307}
7c67c79c
HV
1308
1309time_t mktime_or_timegm(struct tm *tm, bool utc) {
1310 return utc ? timegm(tm) : mktime(tm);
1311}
1312
1313struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1314 return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1315}
87b8ce69
SS
1316
1317unsigned long usec_to_jiffies(usec_t u) {
1318 static thread_local unsigned long hz = 0;
1319 long r;
1320
1321 if (hz == 0) {
1322 r = sysconf(_SC_CLK_TCK);
1323
1324 assert(r > 0);
70887c5f 1325 hz = r;
87b8ce69
SS
1326 }
1327
1328 return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1329}