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