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