chiark / gitweb /
tree-wide: make bus_map_all_properties return a proper sd_bus_error
[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(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(now(CLOCK_MONOTONIC), delta);
131         ts->boottime = clock_boottime_supported() ? usec_sub(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(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(ts->realtime, delta);
163         ts->monotonic = usec_sub(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
570         assert(value);
571         assert(t);
572
573         if (sscanf(value, "%" PRIu64 "%" PRIu64, &a, &b) != 2) {
574                 log_debug("Failed to parse dual timestamp value \"%s\": %m", value);
575                 return -EINVAL;
576         }
577
578         t->realtime = a;
579         t->monotonic = b;
580
581         return 0;
582 }
583
584 #endif // 0
585 int timestamp_deserialize(const char *value, usec_t *timestamp) {
586         int r;
587
588         assert(value);
589
590         r = safe_atou64(value, timestamp);
591         if (r < 0)
592                 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
593
594         return r;
595 }
596
597 #if 0 /// UNNEEDED by elogind
598 int parse_timestamp(const char *t, usec_t *usec) {
599         static const struct {
600                 const char *name;
601                 const int nr;
602         } day_nr[] = {
603                 { "Sunday",    0 },
604                 { "Sun",       0 },
605                 { "Monday",    1 },
606                 { "Mon",       1 },
607                 { "Tuesday",   2 },
608                 { "Tue",       2 },
609                 { "Wednesday", 3 },
610                 { "Wed",       3 },
611                 { "Thursday",  4 },
612                 { "Thu",       4 },
613                 { "Friday",    5 },
614                 { "Fri",       5 },
615                 { "Saturday",  6 },
616                 { "Sat",       6 },
617         };
618
619         const char *k, *utc, *tzn = NULL;
620         struct tm tm, copy;
621         time_t x;
622         usec_t x_usec, plus = 0, minus = 0, ret;
623         int r, weekday = -1, dst = -1;
624         unsigned i;
625
626         /*
627          * Allowed syntaxes:
628          *
629          *   2012-09-22 16:34:22
630          *   2012-09-22 16:34     (seconds will be set to 0)
631          *   2012-09-22           (time will be set to 00:00:00)
632          *   16:34:22             (date will be set to today)
633          *   16:34                (date will be set to today, seconds to 0)
634          *   now
635          *   yesterday            (time is set to 00:00:00)
636          *   today                (time is set to 00:00:00)
637          *   tomorrow             (time is set to 00:00:00)
638          *   +5min
639          *   -5days
640          *   @2147483647          (seconds since epoch)
641          *
642          */
643
644         assert(t);
645         assert(usec);
646
647         if (t[0] == '@')
648                 return parse_sec(t + 1, usec);
649
650         ret = now(CLOCK_REALTIME);
651
652         if (streq(t, "now"))
653                 goto finish;
654
655         else if (t[0] == '+') {
656                 r = parse_sec(t+1, &plus);
657                 if (r < 0)
658                         return r;
659
660                 goto finish;
661
662         } else if (t[0] == '-') {
663                 r = parse_sec(t+1, &minus);
664                 if (r < 0)
665                         return r;
666
667                 goto finish;
668
669         } else if ((k = endswith(t, " ago"))) {
670                 t = strndupa(t, k - t);
671
672                 r = parse_sec(t, &minus);
673                 if (r < 0)
674                         return r;
675
676                 goto finish;
677
678         } else if ((k = endswith(t, " left"))) {
679                 t = strndupa(t, k - t);
680
681                 r = parse_sec(t, &plus);
682                 if (r < 0)
683                         return r;
684
685                 goto finish;
686         }
687
688         /* See if the timestamp is suffixed with UTC */
689         utc = endswith_no_case(t, " UTC");
690         if (utc)
691                 t = strndupa(t, utc - t);
692         else {
693                 const char *e = NULL;
694                 int j;
695
696                 tzset();
697
698                 /* See if the timestamp is suffixed by either the DST or non-DST local timezone. Note that we only
699                  * support the local timezones here, nothing else. Not because we wouldn't want to, but simply because
700                  * there are no nice APIs available to cover this. By accepting the local time zone strings, we make
701                  * sure that all timestamps written by format_timestamp() can be parsed correctly, even though we don't
702                  * support arbitrary timezone specifications.  */
703
704                 for (j = 0; j <= 1; j++) {
705
706                         if (isempty(tzname[j]))
707                                 continue;
708
709                         e = endswith_no_case(t, tzname[j]);
710                         if (!e)
711                                 continue;
712                         if (e == t)
713                                 continue;
714                         if (e[-1] != ' ')
715                                 continue;
716
717                         break;
718                 }
719
720                 if (IN_SET(j, 0, 1)) {
721                         /* Found one of the two timezones specified. */
722                         t = strndupa(t, e - t - 1);
723                         dst = j;
724                         tzn = tzname[j];
725                 }
726         }
727
728         x = (time_t) (ret / USEC_PER_SEC);
729         x_usec = 0;
730
731         if (!localtime_or_gmtime_r(&x, &tm, utc))
732                 return -EINVAL;
733
734         tm.tm_isdst = dst;
735         if (tzn)
736                 tm.tm_zone = tzn;
737
738         if (streq(t, "today")) {
739                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
740                 goto from_tm;
741
742         } else if (streq(t, "yesterday")) {
743                 tm.tm_mday--;
744                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
745                 goto from_tm;
746
747         } else if (streq(t, "tomorrow")) {
748                 tm.tm_mday++;
749                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
750                 goto from_tm;
751         }
752
753         for (i = 0; i < ELEMENTSOF(day_nr); i++) {
754                 size_t skip;
755
756                 if (!startswith_no_case(t, day_nr[i].name))
757                         continue;
758
759                 skip = strlen(day_nr[i].name);
760                 if (t[skip] != ' ')
761                         continue;
762
763                 weekday = day_nr[i].nr;
764                 t += skip + 1;
765                 break;
766         }
767
768         copy = tm;
769         k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
770         if (k) {
771                 if (*k == '.')
772                         goto parse_usec;
773                 else if (*k == 0)
774                         goto from_tm;
775         }
776
777         tm = copy;
778         k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
779         if (k) {
780                 if (*k == '.')
781                         goto parse_usec;
782                 else if (*k == 0)
783                         goto from_tm;
784         }
785
786         tm = copy;
787         k = strptime(t, "%y-%m-%d %H:%M", &tm);
788         if (k && *k == 0) {
789                 tm.tm_sec = 0;
790                 goto from_tm;
791         }
792
793         tm = copy;
794         k = strptime(t, "%Y-%m-%d %H:%M", &tm);
795         if (k && *k == 0) {
796                 tm.tm_sec = 0;
797                 goto from_tm;
798         }
799
800         tm = copy;
801         k = strptime(t, "%y-%m-%d", &tm);
802         if (k && *k == 0) {
803                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
804                 goto from_tm;
805         }
806
807         tm = copy;
808         k = strptime(t, "%Y-%m-%d", &tm);
809         if (k && *k == 0) {
810                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
811                 goto from_tm;
812         }
813
814         tm = copy;
815         k = strptime(t, "%H:%M:%S", &tm);
816         if (k) {
817                 if (*k == '.')
818                         goto parse_usec;
819                 else if (*k == 0)
820                         goto from_tm;
821         }
822
823         tm = copy;
824         k = strptime(t, "%H:%M", &tm);
825         if (k && *k == 0) {
826                 tm.tm_sec = 0;
827                 goto from_tm;
828         }
829
830         return -EINVAL;
831
832 parse_usec:
833         {
834                 unsigned add;
835
836                 k++;
837                 r = parse_fractional_part_u(&k, 6, &add);
838                 if (r < 0)
839                         return -EINVAL;
840
841                 if (*k)
842                         return -EINVAL;
843
844                 x_usec = add;
845         }
846
847 from_tm:
848         x = mktime_or_timegm(&tm, utc);
849         if (x < 0)
850                 return -EINVAL;
851
852         if (weekday >= 0 && tm.tm_wday != weekday)
853                 return -EINVAL;
854
855         ret = (usec_t) x * USEC_PER_SEC + x_usec;
856         if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
857                 return -EINVAL;
858
859 finish:
860         if (ret + plus < ret) /* overflow? */
861                 return -EINVAL;
862         ret += plus;
863         if (ret > USEC_TIMESTAMP_FORMATTABLE_MAX)
864                 return -EINVAL;
865
866         if (ret > minus)
867                 ret -= minus;
868         else
869                 ret = 0;
870
871         *usec = ret;
872
873         return 0;
874 }
875 #endif // 0
876
877 static char* extract_multiplier(char *p, usec_t *multiplier) {
878         static const struct {
879                 const char *suffix;
880                 usec_t usec;
881         } table[] = {
882                 { "seconds", USEC_PER_SEC    },
883                 { "second",  USEC_PER_SEC    },
884                 { "sec",     USEC_PER_SEC    },
885                 { "s",       USEC_PER_SEC    },
886                 { "minutes", USEC_PER_MINUTE },
887                 { "minute",  USEC_PER_MINUTE },
888                 { "min",     USEC_PER_MINUTE },
889                 { "months",  USEC_PER_MONTH  },
890                 { "month",   USEC_PER_MONTH  },
891                 { "M",       USEC_PER_MONTH  },
892                 { "msec",    USEC_PER_MSEC   },
893                 { "ms",      USEC_PER_MSEC   },
894                 { "m",       USEC_PER_MINUTE },
895                 { "hours",   USEC_PER_HOUR   },
896                 { "hour",    USEC_PER_HOUR   },
897                 { "hr",      USEC_PER_HOUR   },
898                 { "h",       USEC_PER_HOUR   },
899                 { "days",    USEC_PER_DAY    },
900                 { "day",     USEC_PER_DAY    },
901                 { "d",       USEC_PER_DAY    },
902                 { "weeks",   USEC_PER_WEEK   },
903                 { "week",    USEC_PER_WEEK   },
904                 { "w",       USEC_PER_WEEK   },
905                 { "years",   USEC_PER_YEAR   },
906                 { "year",    USEC_PER_YEAR   },
907                 { "y",       USEC_PER_YEAR   },
908                 { "usec",    1ULL            },
909                 { "us",      1ULL            },
910                 { "µs",      1ULL            },
911         };
912         unsigned i;
913
914         for (i = 0; i < ELEMENTSOF(table); i++) {
915                 char *e;
916
917                 e = startswith(p, table[i].suffix);
918                 if (e) {
919                         *multiplier = table[i].usec;
920                         return e;
921                 }
922         }
923
924         return p;
925 }
926
927 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
928         const char *p, *s;
929         usec_t r = 0;
930         bool something = false;
931
932         assert(t);
933         assert(usec);
934         assert(default_unit > 0);
935
936         p = t;
937
938         p += strspn(p, WHITESPACE);
939         s = startswith(p, "infinity");
940         if (s) {
941                 s += strspn(s, WHITESPACE);
942                 if (*s != 0)
943                         return -EINVAL;
944
945                 *usec = USEC_INFINITY;
946                 return 0;
947         }
948
949         for (;;) {
950                 long long l, z = 0;
951                 char *e;
952                 unsigned n = 0;
953                 usec_t multiplier = default_unit, k;
954
955                 p += strspn(p, WHITESPACE);
956
957                 if (*p == 0) {
958                         if (!something)
959                                 return -EINVAL;
960
961                         break;
962                 }
963
964                 errno = 0;
965                 l = strtoll(p, &e, 10);
966                 if (errno > 0)
967                         return -errno;
968                 if (l < 0)
969                         return -ERANGE;
970
971                 if (*e == '.') {
972                         char *b = e + 1;
973
974                         errno = 0;
975                         z = strtoll(b, &e, 10);
976                         if (errno > 0)
977                                 return -errno;
978
979                         if (z < 0)
980                                 return -ERANGE;
981
982                         if (e == b)
983                                 return -EINVAL;
984
985                         n = e - b;
986
987                 } else if (e == p)
988                         return -EINVAL;
989
990                 e += strspn(e, WHITESPACE);
991                 p = extract_multiplier(e, &multiplier);
992
993                 something = true;
994
995                 k = (usec_t) z * multiplier;
996
997                 for (; n > 0; n--)
998                         k /= 10;
999
1000                 r += (usec_t) l * multiplier + k;
1001         }
1002
1003         *usec = r;
1004
1005         return 0;
1006 }
1007
1008 int parse_sec(const char *t, usec_t *usec) {
1009         return parse_time(t, usec, USEC_PER_SEC);
1010 }
1011
1012 #if 0 /// UNNEEDED by elogind
1013 int parse_nsec(const char *t, nsec_t *nsec) {
1014         static const struct {
1015                 const char *suffix;
1016                 nsec_t nsec;
1017         } table[] = {
1018                 { "seconds", NSEC_PER_SEC },
1019                 { "second", NSEC_PER_SEC },
1020                 { "sec", NSEC_PER_SEC },
1021                 { "s", NSEC_PER_SEC },
1022                 { "minutes", NSEC_PER_MINUTE },
1023                 { "minute", NSEC_PER_MINUTE },
1024                 { "min", NSEC_PER_MINUTE },
1025                 { "months", NSEC_PER_MONTH },
1026                 { "month", NSEC_PER_MONTH },
1027                 { "msec", NSEC_PER_MSEC },
1028                 { "ms", NSEC_PER_MSEC },
1029                 { "m", NSEC_PER_MINUTE },
1030                 { "hours", NSEC_PER_HOUR },
1031                 { "hour", NSEC_PER_HOUR },
1032                 { "hr", NSEC_PER_HOUR },
1033                 { "h", NSEC_PER_HOUR },
1034                 { "days", NSEC_PER_DAY },
1035                 { "day", NSEC_PER_DAY },
1036                 { "d", NSEC_PER_DAY },
1037                 { "weeks", NSEC_PER_WEEK },
1038                 { "week", NSEC_PER_WEEK },
1039                 { "w", NSEC_PER_WEEK },
1040                 { "years", NSEC_PER_YEAR },
1041                 { "year", NSEC_PER_YEAR },
1042                 { "y", NSEC_PER_YEAR },
1043                 { "usec", NSEC_PER_USEC },
1044                 { "us", NSEC_PER_USEC },
1045                 { "µs", NSEC_PER_USEC },
1046                 { "nsec", 1ULL },
1047                 { "ns", 1ULL },
1048                 { "", 1ULL }, /* default is nsec */
1049         };
1050
1051         const char *p, *s;
1052         nsec_t r = 0;
1053         bool something = false;
1054
1055         assert(t);
1056         assert(nsec);
1057
1058         p = t;
1059
1060         p += strspn(p, WHITESPACE);
1061         s = startswith(p, "infinity");
1062         if (s) {
1063                 s += strspn(s, WHITESPACE);
1064                 if (*s != 0)
1065                         return -EINVAL;
1066
1067                 *nsec = NSEC_INFINITY;
1068                 return 0;
1069         }
1070
1071         for (;;) {
1072                 long long l, z = 0;
1073                 char *e;
1074                 unsigned i, n = 0;
1075
1076                 p += strspn(p, WHITESPACE);
1077
1078                 if (*p == 0) {
1079                         if (!something)
1080                                 return -EINVAL;
1081
1082                         break;
1083                 }
1084
1085                 errno = 0;
1086                 l = strtoll(p, &e, 10);
1087
1088                 if (errno > 0)
1089                         return -errno;
1090
1091                 if (l < 0)
1092                         return -ERANGE;
1093
1094                 if (*e == '.') {
1095                         char *b = e + 1;
1096
1097                         errno = 0;
1098                         z = strtoll(b, &e, 10);
1099                         if (errno > 0)
1100                                 return -errno;
1101
1102                         if (z < 0)
1103                                 return -ERANGE;
1104
1105                         if (e == b)
1106                                 return -EINVAL;
1107
1108                         n = e - b;
1109
1110                 } else if (e == p)
1111                         return -EINVAL;
1112
1113                 e += strspn(e, WHITESPACE);
1114
1115                 for (i = 0; i < ELEMENTSOF(table); i++)
1116                         if (startswith(e, table[i].suffix)) {
1117                                 nsec_t k = (nsec_t) z * table[i].nsec;
1118
1119                                 for (; n > 0; n--)
1120                                         k /= 10;
1121
1122                                 r += (nsec_t) l * table[i].nsec + k;
1123                                 p = e + strlen(table[i].suffix);
1124
1125                                 something = true;
1126                                 break;
1127                         }
1128
1129                 if (i >= ELEMENTSOF(table))
1130                         return -EINVAL;
1131
1132         }
1133
1134         *nsec = r;
1135
1136         return 0;
1137 }
1138
1139 bool ntp_synced(void) {
1140         struct timex txc = {};
1141
1142         if (adjtimex(&txc) < 0)
1143                 return false;
1144
1145         if (txc.status & STA_UNSYNC)
1146                 return false;
1147
1148         return true;
1149 }
1150
1151 int get_timezones(char ***ret) {
1152         _cleanup_fclose_ FILE *f = NULL;
1153         _cleanup_strv_free_ char **zones = NULL;
1154         size_t n_zones = 0, n_allocated = 0;
1155
1156         assert(ret);
1157
1158         zones = strv_new("UTC", NULL);
1159         if (!zones)
1160                 return -ENOMEM;
1161
1162         n_allocated = 2;
1163         n_zones = 1;
1164
1165         f = fopen("/usr/share/zoneinfo/zone.tab", "re");
1166         if (f) {
1167                 char l[LINE_MAX];
1168
1169                 FOREACH_LINE(l, f, return -errno) {
1170                         char *p, *w;
1171                         size_t k;
1172
1173                         p = strstrip(l);
1174
1175                         if (isempty(p) || *p == '#')
1176                                 continue;
1177
1178                         /* Skip over country code */
1179                         p += strcspn(p, WHITESPACE);
1180                         p += strspn(p, WHITESPACE);
1181
1182                         /* Skip over coordinates */
1183                         p += strcspn(p, WHITESPACE);
1184                         p += strspn(p, WHITESPACE);
1185
1186                         /* Found timezone name */
1187                         k = strcspn(p, WHITESPACE);
1188                         if (k <= 0)
1189                                 continue;
1190
1191                         w = strndup(p, k);
1192                         if (!w)
1193                                 return -ENOMEM;
1194
1195                         if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1196                                 free(w);
1197                                 return -ENOMEM;
1198                         }
1199
1200                         zones[n_zones++] = w;
1201                         zones[n_zones] = NULL;
1202                 }
1203
1204                 strv_sort(zones);
1205
1206         } else if (errno != ENOENT)
1207                 return -errno;
1208
1209         *ret = zones;
1210         zones = NULL;
1211
1212         return 0;
1213 }
1214
1215 bool timezone_is_valid(const char *name) {
1216         bool slash = false;
1217         const char *p, *t;
1218         struct stat st;
1219
1220         if (isempty(name))
1221                 return false;
1222
1223         if (name[0] == '/')
1224                 return false;
1225
1226         for (p = name; *p; p++) {
1227                 if (!(*p >= '0' && *p <= '9') &&
1228                     !(*p >= 'a' && *p <= 'z') &&
1229                     !(*p >= 'A' && *p <= 'Z') &&
1230                     !(*p == '-' || *p == '_' || *p == '+' || *p == '/'))
1231                         return false;
1232
1233                 if (*p == '/') {
1234
1235                         if (slash)
1236                                 return false;
1237
1238                         slash = true;
1239                 } else
1240                         slash = false;
1241         }
1242
1243         if (slash)
1244                 return false;
1245
1246         t = strjoina("/usr/share/zoneinfo/", name);
1247         if (stat(t, &st) < 0)
1248                 return false;
1249
1250         if (!S_ISREG(st.st_mode))
1251                 return false;
1252
1253         return true;
1254 }
1255
1256 #endif // 0
1257 bool clock_boottime_supported(void) {
1258         static int supported = -1;
1259
1260         /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1261
1262         if (supported < 0) {
1263                 int fd;
1264
1265                 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1266                 if (fd < 0)
1267                         supported = false;
1268                 else {
1269                         safe_close(fd);
1270                         supported = true;
1271                 }
1272         }
1273
1274         return supported;
1275 }
1276
1277 #if 0 /// UNNEEDED by elogind
1278 clockid_t clock_boottime_or_monotonic(void) {
1279         if (clock_boottime_supported())
1280                 return CLOCK_BOOTTIME;
1281         else
1282                 return CLOCK_MONOTONIC;
1283 }
1284 #endif // 0
1285
1286 bool clock_supported(clockid_t clock) {
1287         struct timespec ts;
1288
1289         switch (clock) {
1290
1291         case CLOCK_MONOTONIC:
1292         case CLOCK_REALTIME:
1293                 return true;
1294
1295         case CLOCK_BOOTTIME:
1296                 return clock_boottime_supported();
1297
1298         case CLOCK_BOOTTIME_ALARM:
1299                 if (!clock_boottime_supported())
1300                         return false;
1301
1302                 /* fall through */
1303
1304         default:
1305                 /* For everything else, check properly */
1306                 return clock_gettime(clock, &ts) >= 0;
1307         }
1308 }
1309
1310 #if 0 /// UNNEEDED by elogind
1311 int get_timezone(char **tz) {
1312         _cleanup_free_ char *t = NULL;
1313         const char *e;
1314         char *z;
1315         int r;
1316
1317         r = readlink_malloc("/etc/localtime", &t);
1318         if (r < 0)
1319                 return r; /* returns EINVAL if not a symlink */
1320
1321         e = path_startswith(t, "/usr/share/zoneinfo/");
1322         if (!e)
1323                 e = path_startswith(t, "../usr/share/zoneinfo/");
1324         if (!e)
1325                 return -EINVAL;
1326
1327         if (!timezone_is_valid(e))
1328                 return -EINVAL;
1329
1330         z = strdup(e);
1331         if (!z)
1332                 return -ENOMEM;
1333
1334         *tz = z;
1335         return 0;
1336 }
1337
1338 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1339         return utc ? timegm(tm) : mktime(tm);
1340 }
1341 #endif // 0
1342
1343 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1344         return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1345 }
1346
1347 #if 0 /// UNNEEDED by elogind
1348 unsigned long usec_to_jiffies(usec_t u) {
1349         static thread_local unsigned long hz = 0;
1350         long r;
1351
1352         if (hz == 0) {
1353                 r = sysconf(_SC_CLK_TCK);
1354
1355                 assert(r > 0);
1356                 hz = r;
1357         }
1358
1359         return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1360 }
1361 #endif // 0