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