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