chiark / gitweb /
Merge pull request #15 from elogind/dev_v229
[elogind.git] / src / basic / time-util.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2010 Lennart Poettering
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <limits.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <sys/time.h>
26 #include <sys/timerfd.h>
27 #include <sys/timex.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30
31 #include "alloc-util.h"
32 #include "fd-util.h"
33 #include "fileio.h"
34 #include "fs-util.h"
35 #include "log.h"
36 #include "macro.h"
37 #include "parse-util.h"
38 #include "path-util.h"
39 #include "string-util.h"
40 #include "strv.h"
41 #include "time-util.h"
42
43 #if 0 /// UNNEEDED by elogind
44 static nsec_t timespec_load_nsec(const struct timespec *ts);
45 #endif // 0
46
47 usec_t now(clockid_t clock_id) {
48         struct timespec ts;
49
50         assert_se(clock_gettime(clock_id, &ts) == 0);
51
52         return timespec_load(&ts);
53 }
54
55 #if 0 /// UNNEEDED by elogind
56 nsec_t now_nsec(clockid_t clock_id) {
57         struct timespec ts;
58
59         assert_se(clock_gettime(clock_id, &ts) == 0);
60
61         return timespec_load_nsec(&ts);
62 }
63 #endif // 0
64
65 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
66         assert(ts);
67
68         ts->realtime = now(CLOCK_REALTIME);
69         ts->monotonic = now(CLOCK_MONOTONIC);
70
71         return ts;
72 }
73
74 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
75         int64_t delta;
76         assert(ts);
77
78         if (u == USEC_INFINITY || u <= 0) {
79                 ts->realtime = ts->monotonic = u;
80                 return ts;
81         }
82
83         ts->realtime = u;
84
85         delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
86         ts->monotonic = usec_sub(now(CLOCK_MONOTONIC), delta);
87
88         return ts;
89 }
90
91 #if 0 /// UNNEEDED by elogind
92 dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
93         int64_t delta;
94         assert(ts);
95
96         if (u == USEC_INFINITY) {
97                 ts->realtime = ts->monotonic = USEC_INFINITY;
98                 return ts;
99         }
100
101         ts->monotonic = u;
102         delta = (int64_t) now(CLOCK_MONOTONIC) - (int64_t) u;
103         ts->realtime = usec_sub(now(CLOCK_REALTIME), delta);
104
105         return ts;
106 }
107
108 dual_timestamp* dual_timestamp_from_boottime_or_monotonic(dual_timestamp *ts, usec_t u) {
109         int64_t delta;
110
111         if (u == USEC_INFINITY) {
112                 ts->realtime = ts->monotonic = USEC_INFINITY;
113                 return ts;
114         }
115
116         dual_timestamp_get(ts);
117         delta = (int64_t) now(clock_boottime_or_monotonic()) - (int64_t) u;
118         ts->realtime = usec_sub(ts->realtime, delta);
119         ts->monotonic = usec_sub(ts->monotonic, delta);
120
121         return ts;
122 }
123 #endif // 0
124
125 usec_t timespec_load(const struct timespec *ts) {
126         assert(ts);
127
128         if (ts->tv_sec == (time_t) -1 &&
129             ts->tv_nsec == (long) -1)
130                 return USEC_INFINITY;
131
132         if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
133                 return USEC_INFINITY;
134
135         return
136                 (usec_t) ts->tv_sec * USEC_PER_SEC +
137                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
138 }
139
140 #if 0 /// UNNEEDED by elogind
141 static nsec_t timespec_load_nsec(const struct timespec *ts) {
142         assert(ts);
143
144         if (ts->tv_sec == (time_t) -1 &&
145             ts->tv_nsec == (long) -1)
146                 return NSEC_INFINITY;
147
148         return
149                 (nsec_t) ts->tv_sec * NSEC_PER_SEC +
150                 (nsec_t) ts->tv_nsec;
151 }
152 #endif // 0
153
154 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
155         assert(ts);
156
157         if (u == USEC_INFINITY) {
158                 ts->tv_sec = (time_t) -1;
159                 ts->tv_nsec = (long) -1;
160                 return ts;
161         }
162
163         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
164         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
165
166         return ts;
167 }
168
169 usec_t timeval_load(const struct timeval *tv) {
170         assert(tv);
171
172         if (tv->tv_sec == (time_t) -1 &&
173             tv->tv_usec == (suseconds_t) -1)
174                 return USEC_INFINITY;
175
176         if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
177                 return USEC_INFINITY;
178
179         return
180                 (usec_t) tv->tv_sec * USEC_PER_SEC +
181                 (usec_t) tv->tv_usec;
182 }
183
184 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
185         assert(tv);
186
187         if (u == USEC_INFINITY) {
188                 tv->tv_sec = (time_t) -1;
189                 tv->tv_usec = (suseconds_t) -1;
190         } else {
191                 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
192                 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
193         }
194
195         return tv;
196 }
197
198 static char *format_timestamp_internal(char *buf, size_t l, usec_t t,
199                                        bool utc, bool us) {
200         struct tm tm;
201         time_t sec;
202         int k;
203
204         assert(buf);
205         assert(l > 0);
206
207         if (t <= 0 || t == USEC_INFINITY)
208                 return NULL;
209
210         sec = (time_t) (t / USEC_PER_SEC);
211         localtime_or_gmtime_r(&sec, &tm, utc);
212
213         if (us)
214                 k = strftime(buf, l, "%a %Y-%m-%d %H:%M:%S", &tm);
215         else
216                 k = strftime(buf, l, "%a %Y-%m-%d %H:%M:%S %Z", &tm);
217
218         if (k <= 0)
219                 return NULL;
220         if (us) {
221                 snprintf(buf + strlen(buf), l - strlen(buf), ".%06llu", (unsigned long long) (t % USEC_PER_SEC));
222                 if (strftime(buf + strlen(buf), l - strlen(buf), " %Z", &tm) <= 0)
223                         return NULL;
224         }
225
226         return buf;
227 }
228
229 char *format_timestamp(char *buf, size_t l, usec_t t) {
230         return format_timestamp_internal(buf, l, t, false, false);
231 }
232
233 #if 0 /// UNNEEDED by elogind
234 char *format_timestamp_utc(char *buf, size_t l, usec_t t) {
235         return format_timestamp_internal(buf, l, t, true, false);
236 }
237 #endif // 0
238
239 char *format_timestamp_us(char *buf, size_t l, usec_t t) {
240         return format_timestamp_internal(buf, l, t, false, true);
241 }
242
243 #if 0 /// UNNEEDED by elogind
244 char *format_timestamp_us_utc(char *buf, size_t l, usec_t t) {
245         return format_timestamp_internal(buf, l, t, true, true);
246 }
247 #endif // 0
248
249 char *format_timestamp_relative(char *buf, size_t l, usec_t t) {
250         const char *s;
251         usec_t n, d;
252
253         if (t <= 0 || t == USEC_INFINITY)
254                 return NULL;
255
256         n = now(CLOCK_REALTIME);
257         if (n > t) {
258                 d = n - t;
259                 s = "ago";
260         } else {
261                 d = t - n;
262                 s = "left";
263         }
264
265         if (d >= USEC_PER_YEAR)
266                 snprintf(buf, l, USEC_FMT " years " USEC_FMT " months %s",
267                          d / USEC_PER_YEAR,
268                          (d % USEC_PER_YEAR) / USEC_PER_MONTH, s);
269         else if (d >= USEC_PER_MONTH)
270                 snprintf(buf, l, USEC_FMT " months " USEC_FMT " days %s",
271                          d / USEC_PER_MONTH,
272                          (d % USEC_PER_MONTH) / USEC_PER_DAY, s);
273         else if (d >= USEC_PER_WEEK)
274                 snprintf(buf, l, USEC_FMT " weeks " USEC_FMT " days %s",
275                          d / USEC_PER_WEEK,
276                          (d % USEC_PER_WEEK) / USEC_PER_DAY, s);
277         else if (d >= 2*USEC_PER_DAY)
278                 snprintf(buf, l, USEC_FMT " days %s", d / USEC_PER_DAY, s);
279         else if (d >= 25*USEC_PER_HOUR)
280                 snprintf(buf, l, "1 day " USEC_FMT "h %s",
281                          (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
282         else if (d >= 6*USEC_PER_HOUR)
283                 snprintf(buf, l, USEC_FMT "h %s",
284                          d / USEC_PER_HOUR, s);
285         else if (d >= USEC_PER_HOUR)
286                 snprintf(buf, l, USEC_FMT "h " USEC_FMT "min %s",
287                          d / USEC_PER_HOUR,
288                          (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
289         else if (d >= 5*USEC_PER_MINUTE)
290                 snprintf(buf, l, USEC_FMT "min %s",
291                          d / USEC_PER_MINUTE, s);
292         else if (d >= USEC_PER_MINUTE)
293                 snprintf(buf, l, USEC_FMT "min " USEC_FMT "s %s",
294                          d / USEC_PER_MINUTE,
295                          (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
296         else if (d >= USEC_PER_SEC)
297                 snprintf(buf, l, USEC_FMT "s %s",
298                          d / USEC_PER_SEC, s);
299         else if (d >= USEC_PER_MSEC)
300                 snprintf(buf, l, USEC_FMT "ms %s",
301                          d / USEC_PER_MSEC, s);
302         else if (d > 0)
303                 snprintf(buf, l, USEC_FMT"us %s",
304                          d, s);
305         else
306                 snprintf(buf, l, "now");
307
308         buf[l-1] = 0;
309         return buf;
310 }
311
312 char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
313         static const struct {
314                 const char *suffix;
315                 usec_t usec;
316         } table[] = {
317                 { "y", USEC_PER_YEAR },
318                 { "month", USEC_PER_MONTH },
319                 { "w", USEC_PER_WEEK },
320                 { "d", USEC_PER_DAY },
321                 { "h", USEC_PER_HOUR },
322                 { "min", USEC_PER_MINUTE },
323                 { "s", USEC_PER_SEC },
324                 { "ms", USEC_PER_MSEC },
325                 { "us", 1 },
326         };
327
328         unsigned i;
329         char *p = buf;
330         bool something = false;
331
332         assert(buf);
333         assert(l > 0);
334
335         if (t == USEC_INFINITY) {
336                 strncpy(p, "infinity", l-1);
337                 p[l-1] = 0;
338                 return p;
339         }
340
341         if (t <= 0) {
342                 strncpy(p, "0", l-1);
343                 p[l-1] = 0;
344                 return p;
345         }
346
347         /* The result of this function can be parsed with parse_sec */
348
349         for (i = 0; i < ELEMENTSOF(table); i++) {
350                 int k = 0;
351                 size_t n;
352                 bool done = false;
353                 usec_t a, b;
354
355                 if (t <= 0)
356                         break;
357
358                 if (t < accuracy && something)
359                         break;
360
361                 if (t < table[i].usec)
362                         continue;
363
364                 if (l <= 1)
365                         break;
366
367                 a = t / table[i].usec;
368                 b = t % table[i].usec;
369
370                 /* Let's see if we should shows this in dot notation */
371                 if (t < USEC_PER_MINUTE && b > 0) {
372                         usec_t cc;
373                         int j;
374
375                         j = 0;
376                         for (cc = table[i].usec; cc > 1; cc /= 10)
377                                 j++;
378
379                         for (cc = accuracy; cc > 1; cc /= 10) {
380                                 b /= 10;
381                                 j--;
382                         }
383
384                         if (j > 0) {
385                                 k = snprintf(p, l,
386                                              "%s"USEC_FMT".%0*llu%s",
387                                              p > buf ? " " : "",
388                                              a,
389                                              j,
390                                              (unsigned long long) b,
391                                              table[i].suffix);
392
393                                 t = 0;
394                                 done = true;
395                         }
396                 }
397
398                 /* No? Then let's show it normally */
399                 if (!done) {
400                         k = snprintf(p, l,
401                                      "%s"USEC_FMT"%s",
402                                      p > buf ? " " : "",
403                                      a,
404                                      table[i].suffix);
405
406                         t = b;
407                 }
408
409                 n = MIN((size_t) k, l);
410
411                 l -= n;
412                 p += n;
413
414                 something = true;
415         }
416
417         *p = 0;
418
419         return buf;
420 }
421
422 #if 0 /// UNNEEDED by elogind
423 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
424
425         assert(f);
426         assert(name);
427         assert(t);
428
429         if (!dual_timestamp_is_set(t))
430                 return;
431
432         fprintf(f, "%s="USEC_FMT" "USEC_FMT"\n",
433                 name,
434                 t->realtime,
435                 t->monotonic);
436 }
437
438 int dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
439         unsigned long long a, b;
440
441         assert(value);
442         assert(t);
443
444         if (sscanf(value, "%llu %llu", &a, &b) != 2) {
445                 log_debug("Failed to parse finish timestamp value %s.", value);
446                 return -EINVAL;
447         }
448
449         t->realtime = a;
450         t->monotonic = b;
451
452         return 0;
453 }
454
455 int parse_timestamp(const char *t, usec_t *usec) {
456         static const struct {
457                 const char *name;
458                 const int nr;
459         } day_nr[] = {
460                 { "Sunday",    0 },
461                 { "Sun",       0 },
462                 { "Monday",    1 },
463                 { "Mon",       1 },
464                 { "Tuesday",   2 },
465                 { "Tue",       2 },
466                 { "Wednesday", 3 },
467                 { "Wed",       3 },
468                 { "Thursday",  4 },
469                 { "Thu",       4 },
470                 { "Friday",    5 },
471                 { "Fri",       5 },
472                 { "Saturday",  6 },
473                 { "Sat",       6 },
474         };
475
476         const char *k;
477         const char *utc;
478         struct tm tm, copy;
479         time_t x;
480         usec_t x_usec, plus = 0, minus = 0, ret;
481         int r, weekday = -1;
482         unsigned i;
483
484         /*
485          * Allowed syntaxes:
486          *
487          *   2012-09-22 16:34:22
488          *   2012-09-22 16:34     (seconds will be set to 0)
489          *   2012-09-22           (time will be set to 00:00:00)
490          *   16:34:22             (date will be set to today)
491          *   16:34                (date will be set to today, seconds to 0)
492          *   now
493          *   yesterday            (time is set to 00:00:00)
494          *   today                (time is set to 00:00:00)
495          *   tomorrow             (time is set to 00:00:00)
496          *   +5min
497          *   -5days
498          *   @2147483647          (seconds since epoch)
499          *
500          */
501
502         assert(t);
503         assert(usec);
504
505         if (t[0] == '@')
506                 return parse_sec(t + 1, usec);
507
508         ret = now(CLOCK_REALTIME);
509
510         if (streq(t, "now"))
511                 goto finish;
512
513         else if (t[0] == '+') {
514                 r = parse_sec(t+1, &plus);
515                 if (r < 0)
516                         return r;
517
518                 goto finish;
519
520         } else if (t[0] == '-') {
521                 r = parse_sec(t+1, &minus);
522                 if (r < 0)
523                         return r;
524
525                 goto finish;
526
527         } else if ((k = endswith(t, " ago"))) {
528                 t = strndupa(t, k - t);
529
530                 r = parse_sec(t, &minus);
531                 if (r < 0)
532                         return r;
533
534                 goto finish;
535
536         } else if ((k = endswith(t, " left"))) {
537                 t = strndupa(t, k - t);
538
539                 r = parse_sec(t, &plus);
540                 if (r < 0)
541                         return r;
542
543                 goto finish;
544         }
545
546         utc = endswith_no_case(t, " UTC");
547         if (utc)
548                 t = strndupa(t, utc - t);
549
550         x = ret / USEC_PER_SEC;
551         x_usec = 0;
552
553         assert_se(localtime_or_gmtime_r(&x, &tm, utc));
554         tm.tm_isdst = -1;
555
556         if (streq(t, "today")) {
557                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
558                 goto from_tm;
559
560         } else if (streq(t, "yesterday")) {
561                 tm.tm_mday --;
562                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
563                 goto from_tm;
564
565         } else if (streq(t, "tomorrow")) {
566                 tm.tm_mday ++;
567                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
568                 goto from_tm;
569         }
570
571
572         for (i = 0; i < ELEMENTSOF(day_nr); i++) {
573                 size_t skip;
574
575                 if (!startswith_no_case(t, day_nr[i].name))
576                         continue;
577
578                 skip = strlen(day_nr[i].name);
579                 if (t[skip] != ' ')
580                         continue;
581
582                 weekday = day_nr[i].nr;
583                 t += skip + 1;
584                 break;
585         }
586
587         copy = tm;
588         k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
589         if (k) {
590                 if (*k == '.')
591                         goto parse_usec;
592                 else if (*k == 0)
593                         goto from_tm;
594         }
595
596         tm = copy;
597         k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
598         if (k) {
599                 if (*k == '.')
600                         goto parse_usec;
601                 else if (*k == 0)
602                         goto from_tm;
603         }
604
605         tm = copy;
606         k = strptime(t, "%y-%m-%d %H:%M", &tm);
607         if (k && *k == 0) {
608                 tm.tm_sec = 0;
609                 goto from_tm;
610         }
611
612         tm = copy;
613         k = strptime(t, "%Y-%m-%d %H:%M", &tm);
614         if (k && *k == 0) {
615                 tm.tm_sec = 0;
616                 goto from_tm;
617         }
618
619         tm = copy;
620         k = strptime(t, "%y-%m-%d", &tm);
621         if (k && *k == 0) {
622                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
623                 goto from_tm;
624         }
625
626         tm = copy;
627         k = strptime(t, "%Y-%m-%d", &tm);
628         if (k && *k == 0) {
629                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
630                 goto from_tm;
631         }
632
633         tm = copy;
634         k = strptime(t, "%H:%M:%S", &tm);
635         if (k) {
636                 if (*k == '.')
637                         goto parse_usec;
638                 else if (*k == 0)
639                         goto from_tm;
640         }
641
642         tm = copy;
643         k = strptime(t, "%H:%M", &tm);
644         if (k && *k == 0) {
645                 tm.tm_sec = 0;
646                 goto from_tm;
647         }
648
649         return -EINVAL;
650
651 parse_usec:
652         {
653                 unsigned add;
654
655                 k++;
656                 r = parse_fractional_part_u(&k, 6, &add);
657                 if (r < 0)
658                         return -EINVAL;
659
660                 if (*k)
661                         return -EINVAL;
662
663                 x_usec = add;
664
665         }
666
667 from_tm:
668         x = mktime_or_timegm(&tm, utc);
669         if (x == (time_t) -1)
670                 return -EINVAL;
671
672         if (weekday >= 0 && tm.tm_wday != weekday)
673                 return -EINVAL;
674
675         ret = (usec_t) x * USEC_PER_SEC + x_usec;
676
677 finish:
678         ret += plus;
679         if (ret > minus)
680                 ret -= minus;
681         else
682                 ret = 0;
683
684         *usec = ret;
685
686         return 0;
687 }
688 #endif // 0
689
690 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
691
692         static const struct {
693                 const char *suffix;
694                 usec_t usec;
695         } table[] = {
696                 { "seconds", USEC_PER_SEC },
697                 { "second", USEC_PER_SEC },
698                 { "sec", USEC_PER_SEC },
699                 { "s", USEC_PER_SEC },
700                 { "minutes", USEC_PER_MINUTE },
701                 { "minute", USEC_PER_MINUTE },
702                 { "min", USEC_PER_MINUTE },
703                 { "months", USEC_PER_MONTH },
704                 { "month", USEC_PER_MONTH },
705                 { "M",       USEC_PER_MONTH  },
706                 { "msec", USEC_PER_MSEC },
707                 { "ms", USEC_PER_MSEC },
708                 { "m", USEC_PER_MINUTE },
709                 { "hours", USEC_PER_HOUR },
710                 { "hour", USEC_PER_HOUR },
711                 { "hr", USEC_PER_HOUR },
712                 { "h", USEC_PER_HOUR },
713                 { "days", USEC_PER_DAY },
714                 { "day", USEC_PER_DAY },
715                 { "d", USEC_PER_DAY },
716                 { "weeks", USEC_PER_WEEK },
717                 { "week", USEC_PER_WEEK },
718                 { "w", USEC_PER_WEEK },
719                 { "years", USEC_PER_YEAR },
720                 { "year", USEC_PER_YEAR },
721                 { "y", USEC_PER_YEAR },
722                 { "usec", 1ULL },
723                 { "us", 1ULL },
724         };
725
726         const char *p, *s;
727         usec_t r = 0;
728         bool something = false;
729
730         assert(t);
731         assert(usec);
732         assert(default_unit > 0);
733
734         p = t;
735
736         p += strspn(p, WHITESPACE);
737         s = startswith(p, "infinity");
738         if (s) {
739                 s += strspn(s, WHITESPACE);
740                 if (*s != 0)
741                         return -EINVAL;
742
743                 *usec = USEC_INFINITY;
744                 return 0;
745         }
746
747         for (;;) {
748                 long long l, z = 0;
749                 char *e;
750                 unsigned i, n = 0;
751                 usec_t multiplier, k;
752
753                 p += strspn(p, WHITESPACE);
754
755                 if (*p == 0) {
756                         if (!something)
757                                 return -EINVAL;
758
759                         break;
760                 }
761
762                 errno = 0;
763                 l = strtoll(p, &e, 10);
764
765                 if (errno > 0)
766                         return -errno;
767
768                 if (l < 0)
769                         return -ERANGE;
770
771                 if (*e == '.') {
772                         char *b = e + 1;
773
774                         errno = 0;
775                         z = strtoll(b, &e, 10);
776                         if (errno > 0)
777                                 return -errno;
778
779                         if (z < 0)
780                                 return -ERANGE;
781
782                         if (e == b)
783                                 return -EINVAL;
784
785                         n = e - b;
786
787                 } else if (e == p)
788                         return -EINVAL;
789
790                 e += strspn(e, WHITESPACE);
791
792                 for (i = 0; i < ELEMENTSOF(table); i++)
793                         if (startswith(e, table[i].suffix)) {
794                                 multiplier = table[i].usec;
795                                 p = e + strlen(table[i].suffix);
796                                 break;
797                         }
798
799                 if (i >= ELEMENTSOF(table)) {
800                         multiplier = default_unit;
801                         p = e;
802                 }
803
804                 something = true;
805
806                 k = (usec_t) z * multiplier;
807
808                 for (; n > 0; n--)
809                         k /= 10;
810
811                 r += (usec_t) l * multiplier + k;
812         }
813
814         *usec = r;
815
816         return 0;
817 }
818
819 int parse_sec(const char *t, usec_t *usec) {
820         return parse_time(t, usec, USEC_PER_SEC);
821 }
822
823 #if 0 /// UNNEEDED by elogind
824 int parse_nsec(const char *t, nsec_t *nsec) {
825         static const struct {
826                 const char *suffix;
827                 nsec_t nsec;
828         } table[] = {
829                 { "seconds", NSEC_PER_SEC },
830                 { "second", NSEC_PER_SEC },
831                 { "sec", NSEC_PER_SEC },
832                 { "s", NSEC_PER_SEC },
833                 { "minutes", NSEC_PER_MINUTE },
834                 { "minute", NSEC_PER_MINUTE },
835                 { "min", NSEC_PER_MINUTE },
836                 { "months", NSEC_PER_MONTH },
837                 { "month", NSEC_PER_MONTH },
838                 { "msec", NSEC_PER_MSEC },
839                 { "ms", NSEC_PER_MSEC },
840                 { "m", NSEC_PER_MINUTE },
841                 { "hours", NSEC_PER_HOUR },
842                 { "hour", NSEC_PER_HOUR },
843                 { "hr", NSEC_PER_HOUR },
844                 { "h", NSEC_PER_HOUR },
845                 { "days", NSEC_PER_DAY },
846                 { "day", NSEC_PER_DAY },
847                 { "d", NSEC_PER_DAY },
848                 { "weeks", NSEC_PER_WEEK },
849                 { "week", NSEC_PER_WEEK },
850                 { "w", NSEC_PER_WEEK },
851                 { "years", NSEC_PER_YEAR },
852                 { "year", NSEC_PER_YEAR },
853                 { "y", NSEC_PER_YEAR },
854                 { "usec", NSEC_PER_USEC },
855                 { "us", NSEC_PER_USEC },
856                 { "nsec", 1ULL },
857                 { "ns", 1ULL },
858                 { "", 1ULL }, /* default is nsec */
859         };
860
861         const char *p, *s;
862         nsec_t r = 0;
863         bool something = false;
864
865         assert(t);
866         assert(nsec);
867
868         p = t;
869
870         p += strspn(p, WHITESPACE);
871         s = startswith(p, "infinity");
872         if (s) {
873                 s += strspn(s, WHITESPACE);
874                 if (*s != 0)
875                         return -EINVAL;
876
877                 *nsec = NSEC_INFINITY;
878                 return 0;
879         }
880
881         for (;;) {
882                 long long l, z = 0;
883                 char *e;
884                 unsigned i, n = 0;
885
886                 p += strspn(p, WHITESPACE);
887
888                 if (*p == 0) {
889                         if (!something)
890                                 return -EINVAL;
891
892                         break;
893                 }
894
895                 errno = 0;
896                 l = strtoll(p, &e, 10);
897
898                 if (errno > 0)
899                         return -errno;
900
901                 if (l < 0)
902                         return -ERANGE;
903
904                 if (*e == '.') {
905                         char *b = e + 1;
906
907                         errno = 0;
908                         z = strtoll(b, &e, 10);
909                         if (errno > 0)
910                                 return -errno;
911
912                         if (z < 0)
913                                 return -ERANGE;
914
915                         if (e == b)
916                                 return -EINVAL;
917
918                         n = e - b;
919
920                 } else if (e == p)
921                         return -EINVAL;
922
923                 e += strspn(e, WHITESPACE);
924
925                 for (i = 0; i < ELEMENTSOF(table); i++)
926                         if (startswith(e, table[i].suffix)) {
927                                 nsec_t k = (nsec_t) z * table[i].nsec;
928
929                                 for (; n > 0; n--)
930                                         k /= 10;
931
932                                 r += (nsec_t) l * table[i].nsec + k;
933                                 p = e + strlen(table[i].suffix);
934
935                                 something = true;
936                                 break;
937                         }
938
939                 if (i >= ELEMENTSOF(table))
940                         return -EINVAL;
941
942         }
943
944         *nsec = r;
945
946         return 0;
947 }
948
949 bool ntp_synced(void) {
950         struct timex txc = {};
951
952         if (adjtimex(&txc) < 0)
953                 return false;
954
955         if (txc.status & STA_UNSYNC)
956                 return false;
957
958         return true;
959 }
960
961 int get_timezones(char ***ret) {
962         _cleanup_fclose_ FILE *f = NULL;
963         _cleanup_strv_free_ char **zones = NULL;
964         size_t n_zones = 0, n_allocated = 0;
965
966         assert(ret);
967
968         zones = strv_new("UTC", NULL);
969         if (!zones)
970                 return -ENOMEM;
971
972         n_allocated = 2;
973         n_zones = 1;
974
975         f = fopen("/usr/share/zoneinfo/zone.tab", "re");
976         if (f) {
977                 char l[LINE_MAX];
978
979                 FOREACH_LINE(l, f, return -errno) {
980                         char *p, *w;
981                         size_t k;
982
983                         p = strstrip(l);
984
985                         if (isempty(p) || *p == '#')
986                                 continue;
987
988                         /* Skip over country code */
989                         p += strcspn(p, WHITESPACE);
990                         p += strspn(p, WHITESPACE);
991
992                         /* Skip over coordinates */
993                         p += strcspn(p, WHITESPACE);
994                         p += strspn(p, WHITESPACE);
995
996                         /* Found timezone name */
997                         k = strcspn(p, WHITESPACE);
998                         if (k <= 0)
999                                 continue;
1000
1001                         w = strndup(p, k);
1002                         if (!w)
1003                                 return -ENOMEM;
1004
1005                         if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1006                                 free(w);
1007                                 return -ENOMEM;
1008                         }
1009
1010                         zones[n_zones++] = w;
1011                         zones[n_zones] = NULL;
1012                 }
1013
1014                 strv_sort(zones);
1015
1016         } else if (errno != ENOENT)
1017                 return -errno;
1018
1019         *ret = zones;
1020         zones = NULL;
1021
1022         return 0;
1023 }
1024
1025 bool timezone_is_valid(const char *name) {
1026         bool slash = false;
1027         const char *p, *t;
1028         struct stat st;
1029
1030         if (isempty(name))
1031                 return false;
1032
1033         if (name[0] == '/')
1034                 return false;
1035
1036         for (p = name; *p; p++) {
1037                 if (!(*p >= '0' && *p <= '9') &&
1038                     !(*p >= 'a' && *p <= 'z') &&
1039                     !(*p >= 'A' && *p <= 'Z') &&
1040                     !(*p == '-' || *p == '_' || *p == '+' || *p == '/'))
1041                         return false;
1042
1043                 if (*p == '/') {
1044
1045                         if (slash)
1046                                 return false;
1047
1048                         slash = true;
1049                 } else
1050                         slash = false;
1051         }
1052
1053         if (slash)
1054                 return false;
1055
1056         t = strjoina("/usr/share/zoneinfo/", name);
1057         if (stat(t, &st) < 0)
1058                 return false;
1059
1060         if (!S_ISREG(st.st_mode))
1061                 return false;
1062
1063         return true;
1064 }
1065
1066 clockid_t clock_boottime_or_monotonic(void) {
1067         static clockid_t clock = -1;
1068         int fd;
1069
1070         if (clock != -1)
1071                 return clock;
1072
1073         fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1074         if (fd < 0)
1075                 clock = CLOCK_MONOTONIC;
1076         else {
1077                 safe_close(fd);
1078                 clock = CLOCK_BOOTTIME;
1079         }
1080
1081         return clock;
1082 }
1083
1084 int get_timezone(char **tz) {
1085         _cleanup_free_ char *t = NULL;
1086         const char *e;
1087         char *z;
1088         int r;
1089
1090         r = readlink_malloc("/etc/localtime", &t);
1091         if (r < 0)
1092                 return r; /* returns EINVAL if not a symlink */
1093
1094         e = path_startswith(t, "/usr/share/zoneinfo/");
1095         if (!e)
1096                 e = path_startswith(t, "../usr/share/zoneinfo/");
1097         if (!e)
1098                 return -EINVAL;
1099
1100         if (!timezone_is_valid(e))
1101                 return -EINVAL;
1102
1103         z = strdup(e);
1104         if (!z)
1105                 return -ENOMEM;
1106
1107         *tz = z;
1108         return 0;
1109 }
1110
1111 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1112         return utc ? timegm(tm) : mktime(tm);
1113 }
1114 #endif // 0
1115
1116 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1117         return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1118 }
1119
1120 #if 0 /// UNNEEDED by elogind
1121 unsigned long usec_to_jiffies(usec_t u) {
1122         static thread_local unsigned long hz = 0;
1123         long r;
1124
1125         if (hz == 0) {
1126                 r = sysconf(_SC_CLK_TCK);
1127
1128                 assert(r > 0);
1129                 hz = (unsigned long) r;
1130         }
1131
1132         return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1133 }
1134 #endif // 0