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