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