chiark / gitweb /
core: rework how we flush incoming traffic when a socket unit goes down
[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 dual timestamp value \"%s\": %m", value);
446                 return -EINVAL;
447         }
448
449         t->realtime = a;
450         t->monotonic = b;
451
452         return 0;
453 }
454
455 int timestamp_deserialize(const char *value, usec_t *timestamp) {
456         int r;
457
458         assert(value);
459
460         r = safe_atou64(value, timestamp);
461         if (r < 0)
462                 return log_debug_errno(r, "Failed to parse timestamp value \"%s\": %m", value);
463
464         return r;
465 }
466
467 int parse_timestamp(const char *t, usec_t *usec) {
468         static const struct {
469                 const char *name;
470                 const int nr;
471         } day_nr[] = {
472                 { "Sunday",    0 },
473                 { "Sun",       0 },
474                 { "Monday",    1 },
475                 { "Mon",       1 },
476                 { "Tuesday",   2 },
477                 { "Tue",       2 },
478                 { "Wednesday", 3 },
479                 { "Wed",       3 },
480                 { "Thursday",  4 },
481                 { "Thu",       4 },
482                 { "Friday",    5 },
483                 { "Fri",       5 },
484                 { "Saturday",  6 },
485                 { "Sat",       6 },
486         };
487
488         const char *k;
489         const char *utc;
490         struct tm tm, copy;
491         time_t x;
492         usec_t x_usec, plus = 0, minus = 0, ret;
493         int r, weekday = -1;
494         unsigned i;
495
496         /*
497          * Allowed syntaxes:
498          *
499          *   2012-09-22 16:34:22
500          *   2012-09-22 16:34     (seconds will be set to 0)
501          *   2012-09-22           (time will be set to 00:00:00)
502          *   16:34:22             (date will be set to today)
503          *   16:34                (date will be set to today, seconds to 0)
504          *   now
505          *   yesterday            (time is set to 00:00:00)
506          *   today                (time is set to 00:00:00)
507          *   tomorrow             (time is set to 00:00:00)
508          *   +5min
509          *   -5days
510          *   @2147483647          (seconds since epoch)
511          *
512          */
513
514         assert(t);
515         assert(usec);
516
517         if (t[0] == '@')
518                 return parse_sec(t + 1, usec);
519
520         ret = now(CLOCK_REALTIME);
521
522         if (streq(t, "now"))
523                 goto finish;
524
525         else if (t[0] == '+') {
526                 r = parse_sec(t+1, &plus);
527                 if (r < 0)
528                         return r;
529
530                 goto finish;
531
532         } else if (t[0] == '-') {
533                 r = parse_sec(t+1, &minus);
534                 if (r < 0)
535                         return r;
536
537                 goto finish;
538
539         } else if ((k = endswith(t, " ago"))) {
540                 t = strndupa(t, k - t);
541
542                 r = parse_sec(t, &minus);
543                 if (r < 0)
544                         return r;
545
546                 goto finish;
547
548         } else if ((k = endswith(t, " left"))) {
549                 t = strndupa(t, k - t);
550
551                 r = parse_sec(t, &plus);
552                 if (r < 0)
553                         return r;
554
555                 goto finish;
556         }
557
558         utc = endswith_no_case(t, " UTC");
559         if (utc)
560                 t = strndupa(t, utc - t);
561
562         x = ret / USEC_PER_SEC;
563         x_usec = 0;
564
565         assert_se(localtime_or_gmtime_r(&x, &tm, utc));
566         tm.tm_isdst = -1;
567
568         if (streq(t, "today")) {
569                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
570                 goto from_tm;
571
572         } else if (streq(t, "yesterday")) {
573                 tm.tm_mday--;
574                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
575                 goto from_tm;
576
577         } else if (streq(t, "tomorrow")) {
578                 tm.tm_mday++;
579                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
580                 goto from_tm;
581         }
582
583
584         for (i = 0; i < ELEMENTSOF(day_nr); i++) {
585                 size_t skip;
586
587                 if (!startswith_no_case(t, day_nr[i].name))
588                         continue;
589
590                 skip = strlen(day_nr[i].name);
591                 if (t[skip] != ' ')
592                         continue;
593
594                 weekday = day_nr[i].nr;
595                 t += skip + 1;
596                 break;
597         }
598
599         copy = tm;
600         k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
601         if (k) {
602                 if (*k == '.')
603                         goto parse_usec;
604                 else if (*k == 0)
605                         goto from_tm;
606         }
607
608         tm = copy;
609         k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
610         if (k) {
611                 if (*k == '.')
612                         goto parse_usec;
613                 else if (*k == 0)
614                         goto from_tm;
615         }
616
617         tm = copy;
618         k = strptime(t, "%y-%m-%d %H:%M", &tm);
619         if (k && *k == 0) {
620                 tm.tm_sec = 0;
621                 goto from_tm;
622         }
623
624         tm = copy;
625         k = strptime(t, "%Y-%m-%d %H:%M", &tm);
626         if (k && *k == 0) {
627                 tm.tm_sec = 0;
628                 goto from_tm;
629         }
630
631         tm = copy;
632         k = strptime(t, "%y-%m-%d", &tm);
633         if (k && *k == 0) {
634                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
635                 goto from_tm;
636         }
637
638         tm = copy;
639         k = strptime(t, "%Y-%m-%d", &tm);
640         if (k && *k == 0) {
641                 tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
642                 goto from_tm;
643         }
644
645         tm = copy;
646         k = strptime(t, "%H:%M:%S", &tm);
647         if (k) {
648                 if (*k == '.')
649                         goto parse_usec;
650                 else if (*k == 0)
651                         goto from_tm;
652         }
653
654         tm = copy;
655         k = strptime(t, "%H:%M", &tm);
656         if (k && *k == 0) {
657                 tm.tm_sec = 0;
658                 goto from_tm;
659         }
660
661         return -EINVAL;
662
663 parse_usec:
664         {
665                 unsigned add;
666
667                 k++;
668                 r = parse_fractional_part_u(&k, 6, &add);
669                 if (r < 0)
670                         return -EINVAL;
671
672                 if (*k)
673                         return -EINVAL;
674
675                 x_usec = add;
676
677         }
678
679 from_tm:
680         x = mktime_or_timegm(&tm, utc);
681         if (x == (time_t) -1)
682                 return -EINVAL;
683
684         if (weekday >= 0 && tm.tm_wday != weekday)
685                 return -EINVAL;
686
687         ret = (usec_t) x * USEC_PER_SEC + x_usec;
688
689 finish:
690         ret += plus;
691         if (ret > minus)
692                 ret -= minus;
693         else
694                 ret = 0;
695
696         *usec = ret;
697
698         return 0;
699 }
700 #endif // 0
701
702 int parse_time(const char *t, usec_t *usec, usec_t default_unit) {
703
704         static const struct {
705                 const char *suffix;
706                 usec_t usec;
707         } table[] = {
708                 { "seconds", USEC_PER_SEC },
709                 { "second", USEC_PER_SEC },
710                 { "sec", USEC_PER_SEC },
711                 { "s", USEC_PER_SEC },
712                 { "minutes", USEC_PER_MINUTE },
713                 { "minute", USEC_PER_MINUTE },
714                 { "min", USEC_PER_MINUTE },
715                 { "months", USEC_PER_MONTH },
716                 { "month", USEC_PER_MONTH },
717                 { "M",       USEC_PER_MONTH  },
718                 { "msec", USEC_PER_MSEC },
719                 { "ms", USEC_PER_MSEC },
720                 { "m", USEC_PER_MINUTE },
721                 { "hours", USEC_PER_HOUR },
722                 { "hour", USEC_PER_HOUR },
723                 { "hr", USEC_PER_HOUR },
724                 { "h", USEC_PER_HOUR },
725                 { "days", USEC_PER_DAY },
726                 { "day", USEC_PER_DAY },
727                 { "d", USEC_PER_DAY },
728                 { "weeks", USEC_PER_WEEK },
729                 { "week", USEC_PER_WEEK },
730                 { "w", USEC_PER_WEEK },
731                 { "years", USEC_PER_YEAR },
732                 { "year", USEC_PER_YEAR },
733                 { "y", USEC_PER_YEAR },
734                 { "usec", 1ULL },
735                 { "us", 1ULL },
736         };
737
738         const char *p, *s;
739         usec_t r = 0;
740         bool something = false;
741
742         assert(t);
743         assert(usec);
744         assert(default_unit > 0);
745
746         p = t;
747
748         p += strspn(p, WHITESPACE);
749         s = startswith(p, "infinity");
750         if (s) {
751                 s += strspn(s, WHITESPACE);
752                 if (*s != 0)
753                         return -EINVAL;
754
755                 *usec = USEC_INFINITY;
756                 return 0;
757         }
758
759         for (;;) {
760                 long long l, z = 0;
761                 char *e;
762                 unsigned i, n = 0;
763                 usec_t multiplier, k;
764
765                 p += strspn(p, WHITESPACE);
766
767                 if (*p == 0) {
768                         if (!something)
769                                 return -EINVAL;
770
771                         break;
772                 }
773
774                 errno = 0;
775                 l = strtoll(p, &e, 10);
776
777                 if (errno > 0)
778                         return -errno;
779
780                 if (l < 0)
781                         return -ERANGE;
782
783                 if (*e == '.') {
784                         char *b = e + 1;
785
786                         errno = 0;
787                         z = strtoll(b, &e, 10);
788                         if (errno > 0)
789                                 return -errno;
790
791                         if (z < 0)
792                                 return -ERANGE;
793
794                         if (e == b)
795                                 return -EINVAL;
796
797                         n = e - b;
798
799                 } else if (e == p)
800                         return -EINVAL;
801
802                 e += strspn(e, WHITESPACE);
803
804                 for (i = 0; i < ELEMENTSOF(table); i++)
805                         if (startswith(e, table[i].suffix)) {
806                                 multiplier = table[i].usec;
807                                 p = e + strlen(table[i].suffix);
808                                 break;
809                         }
810
811                 if (i >= ELEMENTSOF(table)) {
812                         multiplier = default_unit;
813                         p = e;
814                 }
815
816                 something = true;
817
818                 k = (usec_t) z * multiplier;
819
820                 for (; n > 0; n--)
821                         k /= 10;
822
823                 r += (usec_t) l * multiplier + k;
824         }
825
826         *usec = r;
827
828         return 0;
829 }
830
831 int parse_sec(const char *t, usec_t *usec) {
832         return parse_time(t, usec, USEC_PER_SEC);
833 }
834
835 #if 0 /// UNNEEDED by elogind
836 int parse_nsec(const char *t, nsec_t *nsec) {
837         static const struct {
838                 const char *suffix;
839                 nsec_t nsec;
840         } table[] = {
841                 { "seconds", NSEC_PER_SEC },
842                 { "second", NSEC_PER_SEC },
843                 { "sec", NSEC_PER_SEC },
844                 { "s", NSEC_PER_SEC },
845                 { "minutes", NSEC_PER_MINUTE },
846                 { "minute", NSEC_PER_MINUTE },
847                 { "min", NSEC_PER_MINUTE },
848                 { "months", NSEC_PER_MONTH },
849                 { "month", NSEC_PER_MONTH },
850                 { "msec", NSEC_PER_MSEC },
851                 { "ms", NSEC_PER_MSEC },
852                 { "m", NSEC_PER_MINUTE },
853                 { "hours", NSEC_PER_HOUR },
854                 { "hour", NSEC_PER_HOUR },
855                 { "hr", NSEC_PER_HOUR },
856                 { "h", NSEC_PER_HOUR },
857                 { "days", NSEC_PER_DAY },
858                 { "day", NSEC_PER_DAY },
859                 { "d", NSEC_PER_DAY },
860                 { "weeks", NSEC_PER_WEEK },
861                 { "week", NSEC_PER_WEEK },
862                 { "w", NSEC_PER_WEEK },
863                 { "years", NSEC_PER_YEAR },
864                 { "year", NSEC_PER_YEAR },
865                 { "y", NSEC_PER_YEAR },
866                 { "usec", NSEC_PER_USEC },
867                 { "us", NSEC_PER_USEC },
868                 { "nsec", 1ULL },
869                 { "ns", 1ULL },
870                 { "", 1ULL }, /* default is nsec */
871         };
872
873         const char *p, *s;
874         nsec_t r = 0;
875         bool something = false;
876
877         assert(t);
878         assert(nsec);
879
880         p = t;
881
882         p += strspn(p, WHITESPACE);
883         s = startswith(p, "infinity");
884         if (s) {
885                 s += strspn(s, WHITESPACE);
886                 if (*s != 0)
887                         return -EINVAL;
888
889                 *nsec = NSEC_INFINITY;
890                 return 0;
891         }
892
893         for (;;) {
894                 long long l, z = 0;
895                 char *e;
896                 unsigned i, n = 0;
897
898                 p += strspn(p, WHITESPACE);
899
900                 if (*p == 0) {
901                         if (!something)
902                                 return -EINVAL;
903
904                         break;
905                 }
906
907                 errno = 0;
908                 l = strtoll(p, &e, 10);
909
910                 if (errno > 0)
911                         return -errno;
912
913                 if (l < 0)
914                         return -ERANGE;
915
916                 if (*e == '.') {
917                         char *b = e + 1;
918
919                         errno = 0;
920                         z = strtoll(b, &e, 10);
921                         if (errno > 0)
922                                 return -errno;
923
924                         if (z < 0)
925                                 return -ERANGE;
926
927                         if (e == b)
928                                 return -EINVAL;
929
930                         n = e - b;
931
932                 } else if (e == p)
933                         return -EINVAL;
934
935                 e += strspn(e, WHITESPACE);
936
937                 for (i = 0; i < ELEMENTSOF(table); i++)
938                         if (startswith(e, table[i].suffix)) {
939                                 nsec_t k = (nsec_t) z * table[i].nsec;
940
941                                 for (; n > 0; n--)
942                                         k /= 10;
943
944                                 r += (nsec_t) l * table[i].nsec + k;
945                                 p = e + strlen(table[i].suffix);
946
947                                 something = true;
948                                 break;
949                         }
950
951                 if (i >= ELEMENTSOF(table))
952                         return -EINVAL;
953
954         }
955
956         *nsec = r;
957
958         return 0;
959 }
960
961 bool ntp_synced(void) {
962         struct timex txc = {};
963
964         if (adjtimex(&txc) < 0)
965                 return false;
966
967         if (txc.status & STA_UNSYNC)
968                 return false;
969
970         return true;
971 }
972
973 int get_timezones(char ***ret) {
974         _cleanup_fclose_ FILE *f = NULL;
975         _cleanup_strv_free_ char **zones = NULL;
976         size_t n_zones = 0, n_allocated = 0;
977
978         assert(ret);
979
980         zones = strv_new("UTC", NULL);
981         if (!zones)
982                 return -ENOMEM;
983
984         n_allocated = 2;
985         n_zones = 1;
986
987         f = fopen("/usr/share/zoneinfo/zone.tab", "re");
988         if (f) {
989                 char l[LINE_MAX];
990
991                 FOREACH_LINE(l, f, return -errno) {
992                         char *p, *w;
993                         size_t k;
994
995                         p = strstrip(l);
996
997                         if (isempty(p) || *p == '#')
998                                 continue;
999
1000                         /* Skip over country code */
1001                         p += strcspn(p, WHITESPACE);
1002                         p += strspn(p, WHITESPACE);
1003
1004                         /* Skip over coordinates */
1005                         p += strcspn(p, WHITESPACE);
1006                         p += strspn(p, WHITESPACE);
1007
1008                         /* Found timezone name */
1009                         k = strcspn(p, WHITESPACE);
1010                         if (k <= 0)
1011                                 continue;
1012
1013                         w = strndup(p, k);
1014                         if (!w)
1015                                 return -ENOMEM;
1016
1017                         if (!GREEDY_REALLOC(zones, n_allocated, n_zones + 2)) {
1018                                 free(w);
1019                                 return -ENOMEM;
1020                         }
1021
1022                         zones[n_zones++] = w;
1023                         zones[n_zones] = NULL;
1024                 }
1025
1026                 strv_sort(zones);
1027
1028         } else if (errno != ENOENT)
1029                 return -errno;
1030
1031         *ret = zones;
1032         zones = NULL;
1033
1034         return 0;
1035 }
1036
1037 bool timezone_is_valid(const char *name) {
1038         bool slash = false;
1039         const char *p, *t;
1040         struct stat st;
1041
1042         if (isempty(name))
1043                 return false;
1044
1045         if (name[0] == '/')
1046                 return false;
1047
1048         for (p = name; *p; p++) {
1049                 if (!(*p >= '0' && *p <= '9') &&
1050                     !(*p >= 'a' && *p <= 'z') &&
1051                     !(*p >= 'A' && *p <= 'Z') &&
1052                     !(*p == '-' || *p == '_' || *p == '+' || *p == '/'))
1053                         return false;
1054
1055                 if (*p == '/') {
1056
1057                         if (slash)
1058                                 return false;
1059
1060                         slash = true;
1061                 } else
1062                         slash = false;
1063         }
1064
1065         if (slash)
1066                 return false;
1067
1068         t = strjoina("/usr/share/zoneinfo/", name);
1069         if (stat(t, &st) < 0)
1070                 return false;
1071
1072         if (!S_ISREG(st.st_mode))
1073                 return false;
1074
1075         return true;
1076 }
1077
1078 bool clock_boottime_supported(void) {
1079         static int supported = -1;
1080
1081         /* Note that this checks whether CLOCK_BOOTTIME is available in general as well as available for timerfds()! */
1082
1083         if (supported < 0) {
1084                 int fd;
1085
1086                 fd = timerfd_create(CLOCK_BOOTTIME, TFD_NONBLOCK|TFD_CLOEXEC);
1087                 if (fd < 0)
1088                         supported = false;
1089                 else {
1090                         safe_close(fd);
1091                         supported = true;
1092                 }
1093         }
1094
1095         return supported;
1096 }
1097
1098 clockid_t clock_boottime_or_monotonic(void) {
1099         if (clock_boottime_supported())
1100                 return CLOCK_BOOTTIME;
1101         else
1102                 return CLOCK_MONOTONIC;
1103 }
1104
1105 int get_timezone(char **tz) {
1106         _cleanup_free_ char *t = NULL;
1107         const char *e;
1108         char *z;
1109         int r;
1110
1111         r = readlink_malloc("/etc/localtime", &t);
1112         if (r < 0)
1113                 return r; /* returns EINVAL if not a symlink */
1114
1115         e = path_startswith(t, "/usr/share/zoneinfo/");
1116         if (!e)
1117                 e = path_startswith(t, "../usr/share/zoneinfo/");
1118         if (!e)
1119                 return -EINVAL;
1120
1121         if (!timezone_is_valid(e))
1122                 return -EINVAL;
1123
1124         z = strdup(e);
1125         if (!z)
1126                 return -ENOMEM;
1127
1128         *tz = z;
1129         return 0;
1130 }
1131
1132 time_t mktime_or_timegm(struct tm *tm, bool utc) {
1133         return utc ? timegm(tm) : mktime(tm);
1134 }
1135 #endif // 0
1136
1137 struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc) {
1138         return utc ? gmtime_r(t, tm) : localtime_r(t, tm);
1139 }
1140
1141 #if 0 /// UNNEEDED by elogind
1142 unsigned long usec_to_jiffies(usec_t u) {
1143         static thread_local unsigned long hz = 0;
1144         long r;
1145
1146         if (hz == 0) {
1147                 r = sysconf(_SC_CLK_TCK);
1148
1149                 assert(r > 0);
1150                 hz = (unsigned long) r;
1151         }
1152
1153         return DIV_ROUND_UP(u , USEC_PER_SEC / hz);
1154 }
1155 #endif // 0