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