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