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