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