chiark / gitweb /
tree-wide: remove Lennart's copyright lines
[elogind.git] / src / basic / time-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <limits.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <sys/mman.h>
8 #include <sys/stat.h>
9 #include <sys/time.h>
10 #include <sys/timerfd.h>
11 #include <sys/timex.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14
15 #include "alloc-util.h"
16 #include "fd-util.h"
17 #include "fileio.h"
18 #include "fs-util.h"
19 //#include "io-util.h"
20 #include "log.h"
21 #include "macro.h"
22 #include "parse-util.h"
23 #include "path-util.h"
24 //#include "process-util.h"
25 //#include "stat-util.h"
26 #include "string-util.h"
27 #include "strv.h"
28 #include "time-util.h"
29
30 static clockid_t map_clock_id(clockid_t c) {
31
32         /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus, clock_gettime() will
33          * fail for them. Since they are essentially the same as their non-ALARM pendants (their only difference is
34          * when timers are set on them), let's just map them accordingly. This way, we can get the correct time even on
35          * those archs. */
36
37         switch (c) {
38
39         case CLOCK_BOOTTIME_ALARM:
40                 return CLOCK_BOOTTIME;
41
42         case CLOCK_REALTIME_ALARM:
43                 return CLOCK_REALTIME;
44
45         default:
46                 return c;
47         }
48 }
49
50 usec_t now(clockid_t clock_id) {
51         struct timespec ts;
52
53         assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
54
55         return timespec_load(&ts);
56 }
57
58 #if 0 /// UNNEEDED by elogind
59 nsec_t now_nsec(clockid_t clock_id) {
60         struct timespec ts;
61
62         assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
63
64         return timespec_load_nsec(&ts);
65 }
66 #endif // 0
67
68 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
69         assert(ts);
70
71         ts->realtime = now(CLOCK_REALTIME);
72         ts->monotonic = now(CLOCK_MONOTONIC);
73
74         return ts;
75 }
76
77 triple_timestamp* triple_timestamp_get(triple_timestamp *ts) {
78         assert(ts);
79
80         ts->realtime = now(CLOCK_REALTIME);
81         ts->monotonic = now(CLOCK_MONOTONIC);
82         ts->boottime = clock_boottime_supported() ? now(CLOCK_BOOTTIME) : USEC_INFINITY;
83
84         return ts;
85 }
86
87 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
88         int64_t delta;
89         assert(ts);
90
91         if (u == USEC_INFINITY || u <= 0) {
92                 ts->realtime = ts->monotonic = u;
93                 return ts;
94         }
95
96         ts->realtime = u;
97
98         delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
99         ts->monotonic = usec_sub_signed(now(CLOCK_MONOTONIC), delta);
100
101         return ts;
102 }
103
104 #if 0 /// UNNEEDED by elogind
105 triple_timestamp* triple_timestamp_from_realtime(triple_timestamp *ts, usec_t u) {
106         int64_t delta;
107
108         assert(ts);
109
110         if (u == USEC_INFINITY || u <= 0) {
111                 ts->realtime = ts->monotonic = ts->boottime = u;
112                 return ts;
113         }
114
115         ts->realtime = u;
116         delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
117         ts->monotonic = usec_sub_signed(now(CLOCK_MONOTONIC), delta);
118         ts->boottime = clock_boottime_supported() ? usec_sub_signed(now(CLOCK_BOOTTIME), delta) : USEC_INFINITY;
119
120         return ts;
121 }
122
123 dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
124         int64_t delta;
125         assert(ts);
126
127         if (u == USEC_INFINITY) {
128                 ts->realtime = ts->monotonic = USEC_INFINITY;
129                 return ts;
130         }
131
132         ts->monotonic = u;
133         delta = (int64_t) now(CLOCK_MONOTONIC) - (int64_t) u;
134         ts->realtime = usec_sub_signed(now(CLOCK_REALTIME), delta);
135
136         return ts;
137 }
138
139 dual_timestamp* dual_timestamp_from_boottime_or_monotonic(dual_timestamp *ts, usec_t u) {
140         int64_t delta;
141
142         if (u == USEC_INFINITY) {
143                 ts->realtime = ts->monotonic = USEC_INFINITY;
144                 return ts;
145         }
146
147         dual_timestamp_get(ts);
148         delta = (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u;
149         ts->realtime = usec_sub_signed(ts->realtime, delta);
150         ts->monotonic = usec_sub_signed(ts->monotonic, delta);
151
152         return ts;
153 }
154 #endif // 0
155
156 usec_t triple_timestamp_by_clock(triple_timestamp *ts, clockid_t clock) {
157
158         switch (clock) {
159
160         case CLOCK_REALTIME:
161         case CLOCK_REALTIME_ALARM:
162                 return ts->realtime;
163
164         case CLOCK_MONOTONIC:
165                 return ts->monotonic;
166
167         case CLOCK_BOOTTIME:
168         case CLOCK_BOOTTIME_ALARM:
169                 return ts->boottime;
170
171         default:
172                 return USEC_INFINITY;
173         }
174 }
175
176 usec_t timespec_load(const struct timespec *ts) {
177         assert(ts);
178
179         if (ts->tv_sec < 0 || ts->tv_nsec < 0)
180                 return USEC_INFINITY;
181
182         if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
183                 return USEC_INFINITY;
184
185         return
186                 (usec_t) ts->tv_sec * USEC_PER_SEC +
187                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
188 }
189
190 #if 0 /// UNNEEDED by elogind
191 nsec_t timespec_load_nsec(const struct timespec *ts) {
192         assert(ts);
193
194         if (ts->tv_sec < 0 || ts->tv_nsec < 0)
195                 return NSEC_INFINITY;
196
197         if ((nsec_t) ts->tv_sec >= (UINT64_MAX - ts->tv_nsec) / NSEC_PER_SEC)
198                 return NSEC_INFINITY;
199
200         return (nsec_t) ts->tv_sec * NSEC_PER_SEC + (nsec_t) ts->tv_nsec;
201 }
202 #endif // 0
203
204 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
205         assert(ts);
206
207         if (u == USEC_INFINITY ||
208             u / USEC_PER_SEC >= TIME_T_MAX) {
209                 ts->tv_sec = (time_t) -1;
210                 ts->tv_nsec = (long) -1;
211                 return ts;
212         }
213
214         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
215         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
216
217         return ts;
218 }
219
220 usec_t timeval_load(const struct timeval *tv) {
221         assert(tv);
222
223         if (tv->tv_sec < 0 || tv->tv_usec < 0)
224                 return USEC_INFINITY;
225
226         if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
227                 return USEC_INFINITY;
228
229         return
230                 (usec_t) tv->tv_sec * USEC_PER_SEC +
231                 (usec_t) tv->tv_usec;
232 }
233
234 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
235         assert(tv);
236
237         if (u == USEC_INFINITY ||
238             u / USEC_PER_SEC > TIME_T_MAX) {
239                 tv->tv_sec = (time_t) -1;
240                 tv->tv_usec = (suseconds_t) -1;
241         } else {
242                 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
243                 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
244         }
245
246         return tv;
247 }
248
249 static char *format_timestamp_internal(
250                 char *buf,
251                 size_t l,
252                 usec_t t,
253                 bool utc,
254                 bool us) {
255
256         /* The weekdays in non-localized (English) form. We use this instead of the localized form, so that our
257          * generated timestamps may be parsed with parse_timestamp(), and always read the same. */
258         static const char * const weekdays[] = {
259                 [0] = "Sun",
260                 [1] = "Mon",
261                 [2] = "Tue",
262                 [3] = "Wed",
263                 [4] = "Thu",
264                 [5] = "Fri",
265                 [6] = "Sat",
266         };
267
268         struct tm tm;
269         time_t sec;
270         size_t n;
271
272         assert(buf);
273
274         if (l <
275             3 +                  /* week day */
276             1 + 10 +             /* space and date */
277             1 + 8 +              /* space and time */
278             (us ? 1 + 6 : 0) +   /* "." and microsecond part */
279             1 + 1 +              /* space and shortest possible zone */
280             1)
281                 return NULL; /* Not enough space even for the shortest form. */
282         if (t <= 0 || t == USEC_INFINITY)
283                 return NULL; /* Timestamp is unset */
284
285         /* Let's not format times with years > 9999 */
286         if (t > USEC_TIMESTAMP_FORMATTABLE_MAX) {
287                 assert(l >= strlen("--- XXXX-XX-XX XX:XX:XX") + 1);
288                 strcpy(buf, "--- XXXX-XX-XX XX:XX:XX");
289                 return buf;
290         }
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                         signed char 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         /* Allowed syntaxes:
631          *
632          *   2012-09-22 16:34:22
633          *   2012-09-22 16:34     (seconds will be set to 0)
634          *   2012-09-22           (time will be set to 00:00:00)
635          *   16:34:22             (date will be set to today)
636          *   16:34                (date will be set to today, seconds to 0)
637          *   now
638          *   yesterday            (time is set to 00:00:00)
639          *   today                (time is set to 00:00:00)
640          *   tomorrow             (time is set to 00:00:00)
641          *   +5min
642          *   -5days
643          *   @2147483647          (seconds since epoch)
644          */
645
646         assert(t);
647         assert(usec);
648
649         if (t[0] == '@' && !with_tz)
650                 return parse_sec(t + 1, usec);
651
652         ret = now(CLOCK_REALTIME);
653
654         if (!with_tz) {
655                 if (streq(t, "now"))
656                         goto finish;
657
658                 else if (t[0] == '+') {
659                         r = parse_sec(t+1, &plus);
660                         if (r < 0)
661                                 return r;
662
663                         goto finish;
664
665                 } else if (t[0] == '-') {
666                         r = parse_sec(t+1, &minus);
667                         if (r < 0)
668                                 return r;
669
670                         goto finish;
671
672                 } else if ((k = endswith(t, " ago"))) {
673                         t = strndupa(t, k - t);
674
675                         r = parse_sec(t, &minus);
676                         if (r < 0)
677                                 return r;
678
679                         goto finish;
680
681                 } else if ((k = endswith(t, " left"))) {
682                         t = strndupa(t, k - t);
683
684                         r = parse_sec(t, &plus);
685                         if (r < 0)
686                                 return r;
687
688                         goto finish;
689                 }
690
691                 /* See if the timestamp is suffixed with UTC */
692                 utc = endswith_no_case(t, " UTC");
693                 if (utc)
694                         t = strndupa(t, utc - t);
695                 else {
696                         const char *e = NULL;
697                         int j;
698
699                         tzset();
700
701                         /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
702                          * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
703                          * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
704                          * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
705                          * support arbitrary timezone specifications. */
706
707                         for (j = 0; j <= 1; j++) {
708
709                                 if (isempty(tzname[j]))
710                                         continue;
711
712                                 e = endswith_no_case(t, tzname[j]);
713                                 if (!e)
714                                         continue;
715                                 if (e == t)
716                                         continue;
717                                 if (e[-1] != ' ')
718                                         continue;
719
720                                 break;
721                         }
722
723                         if (IN_SET(j, 0, 1)) {
724                                 /* Found one of the two timezones specified. */
725                                 t = strndupa(t, e - t - 1);
726                                 dst = j;
727                                 tzn = tzname[j];
728                         }
729                 }
730         }
731
732         x = (time_t) (ret / USEC_PER_SEC);
733         x_usec = 0;
734
735         if (!localtime_or_gmtime_r(&x, &tm, utc))
736                 return -EINVAL;
737
738         tm.tm_isdst = dst;
739         if (!with_tz && tzn)
740                 tm.tm_zone = tzn;
741
742         if (streq(t, "today")) {
743                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
744                 goto from_tm;
745
746         } else if (streq(t, "yesterday")) {
747                 tm.tm_mday--;
748                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
749                 goto from_tm;
750
751         } else if (streq(t, "tomorrow")) {
752                 tm.tm_mday++;
753                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
754                 goto from_tm;
755         }
756
757         for (i = 0; i < ELEMENTSOF(day_nr); i++) {
758                 size_t skip;
759
760                 if (!startswith_no_case(t, day_nr[i].name))
761                         continue;
762
763                 skip = strlen(day_nr[i].name);
764                 if (t[skip] != ' ')
765                         continue;
766
767                 weekday = day_nr[i].nr;
768                 t += skip + 1;
769                 break;
770         }
771
772         copy = tm;
773         k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
774         if (k) {
775                 if (*k == '.')
776                         goto parse_usec;
777                 else if (*k == 0)
778                         goto from_tm;
779         }
780
781         tm = copy;
782         k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
783         if (k) {
784                 if (*k == '.')
785                         goto parse_usec;
786                 else if (*k == 0)
787                         goto from_tm;
788         }
789
790         tm = copy;
791         k = strptime(t, "%y-%m-%d %H:%M", &tm);
792         if (k && *k == 0) {
793                 tm.tm_sec = 0;
794                 goto from_tm;
795         }
796
797         tm = copy;
798         k = strptime(t, "%Y-%m-%d %H:%M", &tm);
799         if (k && *k == 0) {
800                 tm.tm_sec = 0;
801                 goto from_tm;
802         }
803
804         tm = copy;
805         k = strptime(t, "%y-%m-%d", &tm);
806         if (k && *k == 0) {
807                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
808                 goto from_tm;
809         }
810
811         tm = copy;
812         k = strptime(t, "%Y-%m-%d", &tm);
813         if (k && *k == 0) {
814                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
815                 goto from_tm;
816         }
817
818         tm = copy;
819         k = strptime(t, "%H:%M:%S", &tm);
820         if (k) {
821                 if (*k == '.')
822                         goto parse_usec;
823                 else if (*k == 0)
824                         goto from_tm;
825         }
826
827         tm = copy;
828         k = strptime(t, "%H:%M", &tm);
829         if (k && *k == 0) {
830                 tm.tm_sec = 0;
831                 goto from_tm;
832         }
833
834         return -EINVAL;
835
836 parse_usec:
837         {
838                 unsigned add;
839
840                 k++;
841                 r = parse_fractional_part_u(&k, 6, &add);
842                 if (r < 0)
843                         return -EINVAL;
844
845                 if (*k)
846                         return -EINVAL;
847
848                 x_usec = add;
849         }
850
851 from_tm:
852         if (weekday >= 0 && tm.tm_wday != weekday)
853                 return -EINVAL;
854
855         x = mktime_or_timegm(&tm, utc);
856         if (x < 0)
857                 return -EINVAL;
858
859         ret = (usec_t) x * USEC_PER_SEC + x_usec;
860         if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
861                 return -EINVAL;
862
863 finish:
864         if (ret + plus < ret) /* overflow? */
865                 return -EINVAL;
866         ret += plus;
867         if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
868                 return -EINVAL;
869
870         if (ret >= minus)
871                 ret -= minus;
872         else
873                 return -EINVAL;
874
875         *usec = ret;
876
877         return 0;
878 }
879
880 typedef struct ParseTimestampResult {
881         usec_t usec;
882         int return_value;
883 } ParseTimestampResult;
884
885 int parse_timestamp(const char *t, usec_t *usec) {
886         char *last_space, *tz = NULL;
887         ParseTimestampResult *shared, tmp;
888         int r;
889
890         last_space = strrchr(t, ' ');
891         if (last_space != NULL && timezone_is_valid(last_space + 1, LOG_DEBUG))
892                 tz = last_space + 1;
893
894         if (!tz || endswith_no_case(t, " UTC"))
895                 return parse_timestamp_impl(t, usec, false);
896
897         shared = mmap(NULL, sizeof *shared, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
898         if (shared == MAP_FAILED)
899                 return negative_errno();
900
901         r = safe_fork("(sd-timestamp)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_WAIT, NULL);
902         if (r < 0) {
903                 (void) munmap(shared, sizeof *shared);
904                 return r;
905         }
906         if (r == 0) {
907                 bool with_tz = true;
908
909                 if (setenv("TZ", tz, 1) != 0) {
910                         shared->return_value = negative_errno();
911                         _exit(EXIT_FAILURE);
912                 }
913
914                 tzset();
915
916                 /* If there is a timezone that matches the tzname fields, leave the parsing to the implementation.
917                  * Otherwise just cut it off. */
918                 with_tz = !STR_IN_SET(tz, tzname[0], tzname[1]);
919
920                 /* Cut off the timezone if we dont need it. */
921                 if (with_tz)
922                         t = strndupa(t, last_space - t);
923
924                 shared->return_value = parse_timestamp_impl(t, &shared->usec, with_tz);
925
926                 _exit(EXIT_SUCCESS);
927         }
928
929         tmp = *shared;
930         if (munmap(shared, sizeof *shared) != 0)
931                 return negative_errno();
932
933         if (tmp.return_value == 0)
934                 *usec = tmp.usec;
935
936         return tmp.return_value;
937 }
938 #endif // 0
939
940 static char* extract_multiplier(char *p, usec_t *multiplier) {
941         static const struct {
942                 const char *suffix;
943                 usec_t usec;
944         } table[] = {
945                 { "seconds", USEC_PER_SEC    },
946                 { "second",  USEC_PER_SEC    },
947                 { "sec",     USEC_PER_SEC    },
948                 { "s",       USEC_PER_SEC    },
949                 { "minutes", USEC_PER_MINUTE },
950                 { "minute",  USEC_PER_MINUTE },
951                 { "min",     USEC_PER_MINUTE },
952                 { "months",  USEC_PER_MONTH  },
953                 { "month",   USEC_PER_MONTH  },
954                 { "M",       USEC_PER_MONTH  },
955                 { "msec",    USEC_PER_MSEC   },
956                 { "ms",      USEC_PER_MSEC   },
957                 { "m",       USEC_PER_MINUTE },
958                 { "hours",   USEC_PER_HOUR   },
959                 { "hour",    USEC_PER_HOUR   },
960                 { "hr",      USEC_PER_HOUR   },
961                 { "h",       USEC_PER_HOUR   },
962                 { "days",    USEC_PER_DAY    },
963                 { "day",     USEC_PER_DAY    },
964                 { "d",       USEC_PER_DAY    },
965                 { "weeks",   USEC_PER_WEEK   },
966                 { "week",    USEC_PER_WEEK   },
967                 { "w",       USEC_PER_WEEK   },
968                 { "years",   USEC_PER_YEAR   },
969                 { "year",    USEC_PER_YEAR   },
970                 { "y",       USEC_PER_YEAR   },
971                 { "usec",    1ULL            },
972                 { "us",      1ULL            },
973                 { "µs",      1ULL            },
974         };
975         size_t i;
976
977         for (i = 0; i < ELEMENTSOF(table); i++) {
978                 char *e;
979
980                 e = startswith(p, table[i].suffix);
981                 if (e) {
982                         *multiplier = table[i].usec;
983                         return e;
984                 }
985         }
986
987         return p;
988 }
989
990 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
991         const char *p, *s;
992         usec_t r = 0;
993         bool something = false;
994
995         assert(t);
996         assert(usec);
997         assert(default_unit > 0);
998
999         p = t;
1000
1001         p += strspn(p, WHITESPACE);
1002         s = startswith(p, "infinity");
1003         if (s) {
1004                 s += strspn(s, WHITESPACE);
1005                 if (*s != 0)
1006                         return -EINVAL;
1007
1008                 *usec = USEC_INFINITY;
1009                 return 0;
1010         }
1011
1012         for (;;) {
1013                 long long l, z = 0;
1014                 char *e;
1015                 unsigned n = 0;
1016                 usec_t multiplier = default_unit, k;
1017
1018                 p += strspn(p, WHITESPACE);
1019
1020                 if (*p == 0) {
1021                         if (!something)
1022                                 return -EINVAL;
1023
1024                         break;
1025                 }
1026
1027                 errno = 0;
1028                 l = strtoll(p, &e, 10);
1029                 if (errno > 0)
1030                         return -errno;
1031                 if (l < 0)
1032                         return -ERANGE;
1033
1034                 if (*e == '.') {
1035                         char *b = e + 1;
1036
1037                         errno = 0;
1038                         z = strtoll(b, &e, 10);
1039                         if (errno > 0)
1040                                 return -errno;
1041
1042                         if (z < 0)
1043                                 return -ERANGE;
1044
1045                         if (e == b)
1046                                 return -EINVAL;
1047
1048                         n = e - b;
1049
1050                 } else if (e == p)
1051                         return -EINVAL;
1052
1053                 e += strspn(e, WHITESPACE);
1054                 p = extract_multiplier(e, &multiplier);
1055
1056                 something = true;
1057
1058                 k = (usec_t) z * multiplier;
1059
1060                 for (; n > 0; n--)
1061                         k /= 10;
1062
1063                 r += (usec_t) l * multiplier + k;
1064         }
1065
1066         *usec = r;
1067
1068         return 0;
1069 }
1070
1071 int parse_sec(const char *t, usec_t *usec) {
1072         return parse_time(t, usec, USEC_PER_SEC);
1073 }
1074
1075 #if 0 /// UNNEEDED by elogind
1076 int parse_sec_fix_0(const char *t, usec_t *usec) {
1077         assert(t);
1078         assert(usec);
1079
1080         t += strspn(t, WHITESPACE);
1081
1082         if (streq(t, "0")) {
1083                 *usec = USEC_INFINITY;
1084                 return 0;
1085         }
1086
1087         return parse_sec(t, usec);
1088 }
1089
1090 int parse_nsec(const char *t, nsec_t *nsec) {
1091         static const struct {
1092                 const char *suffix;
1093                 nsec_t nsec;
1094         } table[] = {
1095                 { "seconds", NSEC_PER_SEC },
1096                 { "second", NSEC_PER_SEC },
1097                 { "sec", NSEC_PER_SEC },
1098                 { "s", NSEC_PER_SEC },
1099                 { "minutes", NSEC_PER_MINUTE },
1100                 { "minute", NSEC_PER_MINUTE },
1101                 { "min", NSEC_PER_MINUTE },
1102                 { "months", NSEC_PER_MONTH },
1103                 { "month", NSEC_PER_MONTH },
1104                 { "msec", NSEC_PER_MSEC },
1105                 { "ms", NSEC_PER_MSEC },
1106                 { "m", NSEC_PER_MINUTE },
1107                 { "hours", NSEC_PER_HOUR },
1108                 { "hour", NSEC_PER_HOUR },
1109                 { "hr", NSEC_PER_HOUR },
1110                 { "h", NSEC_PER_HOUR },
1111                 { "days", NSEC_PER_DAY },
1112                 { "day", NSEC_PER_DAY },
1113                 { "d", NSEC_PER_DAY },
1114                 { "weeks", NSEC_PER_WEEK },
1115                 { "week", NSEC_PER_WEEK },
1116                 { "w", NSEC_PER_WEEK },
1117                 { "years", NSEC_PER_YEAR },
1118                 { "year", NSEC_PER_YEAR },
1119                 { "y", NSEC_PER_YEAR },
1120                 { "usec", NSEC_PER_USEC },
1121                 { "us", NSEC_PER_USEC },
1122                 { "µs", NSEC_PER_USEC },
1123                 { "nsec", 1ULL },
1124                 { "ns", 1ULL },
1125                 { "", 1ULL }, /* default is nsec */
1126         };
1127
1128         const char *p, *s;
1129         nsec_t r = 0;
1130         bool something = false;
1131
1132         assert(t);
1133         assert(nsec);
1134
1135         p = t;
1136
1137         p += strspn(p, WHITESPACE);
1138         s = startswith(p, "infinity");
1139         if (s) {
1140                 s += strspn(s, WHITESPACE);
1141                 if (*s != 0)
1142                         return -EINVAL;
1143
1144                 *nsec = NSEC_INFINITY;
1145                 return 0;
1146         }
1147
1148         for (;;) {
1149                 long long l, z = 0;
1150                 size_t n = 0, i;
1151                 char *e;
1152
1153                 p += strspn(p, WHITESPACE);
1154
1155                 if (*p == 0) {
1156                         if (!something)
1157                                 return -EINVAL;
1158
1159                         break;
1160                 }
1161
1162                 errno = 0;
1163                 l = strtoll(p, &e, 10);
1164
1165                 if (errno > 0)
1166                         return -errno;
1167
1168                 if (l < 0)
1169                         return -ERANGE;
1170
1171                 if (*e == '.') {
1172                         char *b = e + 1;
1173
1174                         errno = 0;
1175                         z = strtoll(b, &e, 10);
1176                         if (errno > 0)
1177                                 return -errno;
1178
1179                         if (z < 0)
1180                                 return -ERANGE;
1181
1182                         if (e == b)
1183                                 return -EINVAL;
1184
1185                         n = e - b;
1186
1187                 } else if (e == p)
1188                         return -EINVAL;
1189
1190                 e += strspn(e, WHITESPACE);
1191
1192                 for (i = 0; i < ELEMENTSOF(table); i++)
1193                         if (startswith(e, table[i].suffix)) {
1194                                 nsec_t k = (nsec_t) z * table[i].nsec;
1195
1196                                 for (; n > 0; n--)
1197                                         k /= 10;
1198
1199                                 r += (nsec_t) l * table[i].nsec + k;
1200                                 p = e + strlen(table[i].suffix);
1201
1202                                 something = true;
1203                                 break;
1204                         }
1205
1206                 if (i >= ELEMENTSOF(table))
1207                         return -EINVAL;
1208
1209         }
1210
1211         *nsec = r;
1212
1213         return 0;
1214 }
1215
1216 bool ntp_synced(void) {
1217         struct timex txc = {};
1218
1219         if (adjtimex(&txc) < 0)
1220                 return false;
1221
1222         if (txc.status & STA_UNSYNC)
1223                 return false;
1224
1225         return true;
1226 }
1227
1228 int get_timezones(char ***ret) {
1229         _cleanup_fclose_ FILE *f = NULL;
1230         _cleanup_strv_free_ char **zones = NULL;
1231         size_t n_zones = 0, n_allocated = 0;
1232
1233         assert(ret);
1234
1235         zones = strv_new("UTC", NULL);
1236         if (!zones)
1237                 return -ENOMEM;
1238
1239         n_allocated = 2;
1240         n_zones = 1;
1241
1242         f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1243         if (f) {
1244                 char l[LINE_MAX];
1245
1246                 FOREACH_LINE(l, f, return -errno) {
1247                         char *p, *w;
1248                         size_t k;
1249
1250                         p = strstrip(l);
1251
1252                         if (isempty(p) || *p == '#')
1253                                 continue;
1254
1255                         /* Skip over country code */
1256                         p += strcspn(p, WHITESPACE);
1257                         p += strspn(p, WHITESPACE);
1258
1259                         /* Skip over coordinates */
1260                         p += strcspn(p, WHITESPACE);
1261                         p += strspn(p, WHITESPACE);
1262
1263                         /* Found timezone name */
1264                         k = strcspn(p, WHITESPACE);
1265                         if (k <= 0)
1266                                 continue;
1267
1268                         w = strndup(p, k);
1269                         if (!w)
1270                                 return -ENOMEM;
1271
1272                         if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1273                                 free(w);
1274                                 return -ENOMEM;
1275                         }
1276
1277                         zones[n_zones++] = w;
1278                         zones[n_zones] = NULL;
1279                 }
1280
1281                 strv_sort(zones);
1282
1283         } else if (errno != ENOENT)
1284                 return -errno;
1285
1286         *ret = TAKE_PTR(zones);
1287
1288         return 0;
1289 }
1290
1291 bool timezone_is_valid(const char *name, int log_level) {
1292         bool slash = false;
1293         const char *p, *t;
1294         _cleanup_close_ int fd = -1;
1295         char buf[4];
1296         int r;
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         if (p - name >= PATH_MAX)
1325                 return false;
1326
1327         t = strjoina("/usr/share/zoneinfo/", name);
1328
1329         fd = open(t, O_RDONLY|O_CLOEXEC);
1330         if (fd < 0) {
1331                 log_full_errno(log_level, errno, "Failed to open timezone file '%s': %m", t);
1332                 return false;
1333         }
1334
1335         r = fd_verify_regular(fd);
1336         if (r < 0) {
1337                 log_full_errno(log_level, r, "Timezone file '%s' is not  a regular file: %m", t);
1338                 return false;
1339         }
1340
1341         r = loop_read_exact(fd, buf, 4, false);
1342         if (r < 0) {
1343                 log_full_errno(log_level, r, "Failed to read from timezone file '%s': %m", t);
1344                 return false;
1345         }
1346
1347         /* Magic from tzfile(5) */
1348         if (memcmp(buf, "TZif", 4) != 0) {
1349                 log_full(log_level, "Timezone file '%s' has wrong magic bytes", t);
1350                 return false;
1351         }
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                 _fallthrough_;
1409         default:
1410                 /* For everything else, check properly */
1411                 return clock_gettime(clock, &ts) >= 0;
1412         }
1413 }
1414 #if 1 /// end diagnostic push in elogind
1415 #  ifdef __GNUC__
1416 #    pragma GCC diagnostic pop
1417 #  endif // __GNUC__
1418 #endif // 1
1419
1420 #if 0 /// UNNEEDED by elogind
1421 int get_timezone(char **tz) {
1422         _cleanup_free_ char *t = NULL;
1423         const char *e;
1424         char *z;
1425         int r;
1426
1427         r = readlink_malloc("/etc/localtime", &t);
1428         if (r < 0)
1429                 return r; /* returns EINVAL if not a symlink */
1430
1431         e = path_startswith(t, "/usr/share/zoneinfo/");
1432         if (!e)
1433                 e = path_startswith(t, "../usr/share/zoneinfo/");
1434         if (!e)
1435                 return -EINVAL;
1436
1437         if (!timezone_is_valid(e, LOG_DEBUG))
1438                 return -EINVAL;
1439
1440         z = strdup(e);
1441         if (!z)
1442                 return -ENOMEM;
1443
1444         *tz = z;
1445         return 0;
1446 }
1447
1448 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1449         return utc ? timegm(tm) : mktime(tm);
1450 }
1451 #endif // 0
1452
1453 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1454         return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1455 }
1456
1457 #if 0 /// UNNEEDED by elogind
1458 unsigned long usec_to_jiffies(usec_t u) {
1459         static thread_local unsigned long hz = 0;
1460         long r;
1461
1462         if (hz == 0) {
1463                 r = sysconf(_SC_CLK_TCK);
1464
1465                 assert(r > 0);
1466                 hz = r;
1467         }
1468
1469         return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1470 }
1471
1472 usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
1473         usec_t a, b;
1474
1475         if (x == USEC_INFINITY)
1476                 return USEC_INFINITY;
1477         if (map_clock_id(from) == map_clock_id(to))
1478                 return x;
1479
1480         a = now(from);
1481         b = now(to);
1482
1483         if (x > a)
1484                 /* x lies in the future */
1485                 return usec_add(b, usec_sub_unsigned(x, a));
1486         else
1487                 /* x lies in the past */
1488                 return usec_sub_unsigned(b, usec_sub_unsigned(a, x));
1489 }
1490 #endif // 0
1491
1492 bool in_utc_timezone(void) {
1493         tzset();
1494
1495         return timezone == 0 && daylight == 0;
1496 }
1497
1498 int time_change_fd(void) {
1499
1500         /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1501         static const struct itimerspec its = {
1502                 .it_value.tv_sec = TIME_T_MAX,
1503         };
1504
1505         _cleanup_close_ int fd;
1506
1507         assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
1508
1509         /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1510          * CLOCK_MONOTONIC. */
1511
1512         fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1513         if (fd < 0)
1514                 return -errno;
1515
1516         if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0)
1517                 return -errno;
1518
1519         return TAKE_FD(fd);
1520 }