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