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