The FreeRADIUS server $Id: 15bac2a4c627c01d1aa2047687b3418955ac7f00 $
Loading...
Searching...
No Matches
time.c
Go to the documentation of this file.
1/*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17/**
18 * $Id: 6b431e9b9b29e12c9cbd1fbcfded53733177c2de $
19 *
20 * @brief Platform independent time functions
21 * @file lib/util/time.c
22 *
23 * @copyright 2016-2019 Alan DeKok (aland@freeradius.org)
24 * @copyright 2019-2020 Arran Cudbard-Bell (a.cudbardb@freeradius.org)
25 */
26RCSID("$Id: 6b431e9b9b29e12c9cbd1fbcfded53733177c2de $")
27
28#include <freeradius-devel/autoconf.h>
29#include <freeradius-devel/util/time.h>
30#include <freeradius-devel/util/skip.h>
31
32int64_t const fr_time_multiplier_by_res[] = {
33 [FR_TIME_RES_NSEC] = 1,
38 [FR_TIME_RES_MIN] = (int64_t)NSEC * 60,
39 [FR_TIME_RES_HOUR] = (int64_t)NSEC * 3600,
40 [FR_TIME_RES_DAY] = (int64_t)NSEC * 86400,
41 [FR_TIME_RES_WEEK] = (int64_t)NSEC * 86400 * 7,
44};
45
47 { L("microseconds"), FR_TIME_RES_USEC },
48 { L("us"), FR_TIME_RES_USEC },
49
50 { L("nanoseconds"), FR_TIME_RES_NSEC },
51 { L("ns"), FR_TIME_RES_NSEC },
52
53 { L("milliseconds"), FR_TIME_RES_MSEC },
54 { L("ms"), FR_TIME_RES_MSEC },
55
56 { L("centiseconds"), FR_TIME_RES_CSEC },
57 { L("cs"), FR_TIME_RES_CSEC },
58
59 { L("seconds"), FR_TIME_RES_SEC },
60 { L("s"), FR_TIME_RES_SEC },
61
62 { L("minutes"), FR_TIME_RES_MIN },
63 { L("m"), FR_TIME_RES_MIN },
64
65 { L("hours"), FR_TIME_RES_HOUR },
66 { L("h"), FR_TIME_RES_HOUR },
67
68 { L("days"), FR_TIME_RES_DAY },
69 { L("d"), FR_TIME_RES_DAY },
70
71 { L("weeks"), FR_TIME_RES_WEEK },
72 { L("w"), FR_TIME_RES_WEEK },
73
74 /*
75 * These use special values FR_TIME_DUR_MONTH and FR_TIME_DUR_YEAR
76 */
77 { L("months"), FR_TIME_RES_MONTH },
78 { L("M"), FR_TIME_RES_MONTH },
79
80 { L("years"), FR_TIME_RES_YEAR },
81 { L("y"), FR_TIME_RES_YEAR },
82
83};
85
86int64_t fr_time_epoch; //!< monotonic clock at boot, i.e. our epoch
87_Atomic int64_t fr_time_monotonic_to_realtime; //!< difference between the two clocks
88
89static char const *tz_names[2] = { NULL, NULL }; //!< normal, DST, from localtime_r(), tm_zone
90static long gmtoff[2] = {0, 0}; //!< from localtime_r(), tm_gmtoff
91static bool isdst = false; //!< from localtime_r(), tm_is_dst
92
93
94/** Get a new fr_time_monotonic_to_realtime value
95 *
96 * Should be done regularly to adjust for changes in system time.
97 *
98 * @return
99 * - 0 on success.
100 * - -1 on failure.
101 */
103{
104 struct tm tm;
105 time_t now;
106
107 /*
108 * fr_time_monotonic_to_realtime is the difference in nano
109 *
110 * So to convert a realtime timeval to fr_time we just subtract fr_time_monotonic_to_realtime from the timeval,
111 * which leaves the number of nanoseconds elapsed since our epoch.
112 */
113 struct timespec ts_realtime, ts_monotime;
114
115 /*
116 * Call these consecutively to minimise drift...
117 */
118 if (clock_gettime(CLOCK_REALTIME, &ts_realtime) < 0) return -1;
119 if (clock_gettime(CLOCK_MONOTONIC_RAW, &ts_monotime) < 0) return -1;
120
125
126 now = ts_realtime.tv_sec;
127
128 /*
129 * Get local time zone name, daylight savings, and GMT
130 * offsets.
131 */
132 (void) localtime_r(&now, &tm);
133
134 isdst = (tm.tm_isdst != 0);
135 tz_names[isdst] = tm.tm_zone;
136 gmtoff[isdst] = tm.tm_gmtoff * NSEC; /* they store seconds, we store nanoseconds */
137
138 return 0;
139}
140
141/** Initialize the local time.
142 *
143 * MUST be called when the program starts. MUST NOT be called after
144 * that.
145 *
146 * @return
147 * - <0 on error
148 * - 0 on success
149 */
151{
152 struct timespec ts;
153
154 tzset(); /* Populate timezone, daylight and tzname globals */
155
156 if (clock_gettime(CLOCK_MONOTONIC_RAW, &ts) < 0) return -1;
158
159 return fr_time_sync();
160}
161
162/** Return time delta from the time zone.
163 *
164 * Returns the delta between UTC and the timezone specified by tz
165 *
166 * @param[in] tz time zone name
167 * @param[out] delta the time delta
168 * @return
169 * - 0 converted OK
170 * - <0 on error
171 *
172 * @note This function ONLY handles a limited number of time
173 * zones: local and gmt. It is impossible in general to parse
174 * arbitrary time zone strings, as there are duplicates.
175 */
177{
178 *delta = fr_time_delta_wrap(0);
179
180 if ((strcmp(tz, "UTC") == 0) ||
181 (strcmp(tz, "GMT") == 0)) {
182 return 0;
183 }
184
185 /*
186 * Our local time zone OR time zone with daylight savings.
187 */
188 if (tz_names[0] && (strcmp(tz, tz_names[0]) == 0)) {
189 *delta = fr_time_delta_wrap(gmtoff[0]);
190 return 0;
191 }
192
193 if (tz_names[1] && (strcmp(tz, tz_names[1]) == 0)) {
194 *delta = fr_time_delta_wrap(gmtoff[1]);
195 return 0;
196 }
197
198 return -1;
199}
200
201/** Create fr_time_delta_t from a string
202 *
203 * @param[out] out Where to write fr_time_delta_t
204 * @param[in] in String to parse.
205 * @param[in] hint scale for the parsing. Default is "seconds".
206 * @param[in] no_trailing asserts that there should be a terminal sequence
207 * after the time delta. Allows us to produce
208 * better errors.
209 * @param[in] tt terminal sequences.
210 * @return
211 * - >= 0 on success.
212 * - <0 on failure.
213 */
215 bool no_trailing, fr_sbuff_term_t const *tt)
216{
217 fr_sbuff_t our_in = FR_SBUFF(in);
218 int64_t integer = 0; /* Whole units */
219 double f = 0.0;
220 fr_time_res_t res;
221 bool do_float;
222 bool negative;
224 bool overflow;
225 size_t match_len;
226
227 negative = fr_sbuff_is_char(&our_in, '-');
228 do_float = false;
229
230 if (fr_sbuff_is_char(&our_in, '.')) goto is_float;
231
232 /*
233 * Look for:
234 *
235 * <integer>[scale]
236 */
237 if (fr_sbuff_out(&sberr, &integer, &our_in) < 0) {
238 char const *err;
239
240 num_error:
241 if (sberr != FR_SBUFF_PARSE_ERROR_NOT_FOUND) {
243 } else {
244 err = "Invalid text, input should be a number";
245 }
246
247 fr_strerror_printf("Failed parsing time_delta: %s", err);
248 FR_SBUFF_ERROR_RETURN(&our_in);
249 }
250
251 /*
252 * hh:mm:ss
253 */
254 if (fr_sbuff_next_if_char(&our_in, ':')) goto do_timestamp;
255
256 /*
257 * If it's a fractional thing, then just parse it as a double.
258 *
259 * <float>[scale]
260 */
261 if (fr_sbuff_is_char(&our_in, '.')) {
262 our_in = FR_SBUFF(in);
263
264 is_float:
265 if (fr_sbuff_out(&sberr, &f, &our_in) < 0) goto num_error;
266
267 do_float = true;
268 }
269
270 /*
271 * Now look for the time resolution.
272 */
274
275 if (fr_sbuff_is_terminal(&our_in, tt)) {
276 if (match_len == 0) res = hint;
277
278 } else if (no_trailing) {
279 fail_trailing_data:
280 /* Got a qualifier but there is more text after it. */
281 if (res != FR_TIME_RES_INVALID) {
282 fr_strerror_const("Trailing data after time_delta");
283 FR_SBUFF_ERROR_RETURN(&our_in);
284 }
285
286 fr_strerror_const("Invalid precision qualifier for time_delta");
287 FR_SBUFF_ERROR_RETURN(&our_in);
288
289 } else if (match_len == 0) {
290 /*
291 * There is trailing data, but we don't care about it. Ensure that we have a time resolution.
292 */
293 res = hint;
294 }
295
297
298 /*
299 * For floating point numbers, we pre-multiply by the time resolution, and then override the time
300 * resolution to indicate that no further scaling is necessary.
301 *
302 * We check for overflow prior to multiplication, as doubles have ~53 bits of precision, while
303 * int64_t has 64 bits of precision. That way the comparison is more likely to be accurate.
304 */
305 if (do_float) {
306 if (f < ((double) INT64_MIN) / (double) fr_time_multiplier_by_res[res]) goto fail_overflow;
307 if (f > ((double) INT64_MAX) / (double) fr_time_multiplier_by_res[res]) goto fail_overflow;
308
310 res = FR_TIME_RES_NSEC;
311 integer = f;
312 }
313
314 /*
315 * We have a valid time scale. Let's use that.
316 */
317 *out = fr_time_delta_from_integer(&overflow, integer, res);
318 if (overflow) {
319 fail_overflow:
320 fr_strerror_printf("time_delta would %s", negative ? "underflow" : "overflow");
321 fr_sbuff_set_to_start(&our_in);
322 FR_SBUFF_ERROR_RETURN(&our_in);
323
324 }
325 FR_SBUFF_SET_RETURN(in, &our_in);
326
327do_timestamp:
328 res = hint;
329
330 /*
331 * It's a timestamp format
332 *
333 * [hours:]minutes:seconds
334 */
335 {
336 uint64_t hours, minutes, seconds;
338
339 fr_sbuff_marker(&m1, &our_in);
340
341 if (fr_sbuff_out(&sberr, &seconds, &our_in) < 0) goto num_error;
342
343 /*
344 * minutes:seconds
345 */
346 if (!fr_sbuff_next_if_char(&our_in, ':')) {
347 hours = 0;
348 minutes = negative ? -(integer) : integer;
349
350 if (minutes >= 60) {
351 fr_strerror_printf("minutes component of time_delta is too large");
352 fr_sbuff_set_to_start(&our_in);
353 FR_SBUFF_ERROR_RETURN(&our_in);
354 }
355
356 } else {
357 /*
358 * hours:minutes:seconds
359 */
360 hours = negative ? -(integer) : integer;
361 minutes = seconds;
362
363 if (fr_sbuff_out(&sberr, &seconds, &our_in) < 0) goto num_error;
364
365 /*
366 * We allow >24 hours. What the heck.
367 */
368 if (hours > UINT16_MAX) {
369 fr_strerror_printf("hours component of time_delta is too large");
370 fr_sbuff_set_to_start(&our_in);
371 FR_SBUFF_ERROR_RETURN(&our_in);
372 }
373
374 if (minutes >= 60) {
375 fr_strerror_printf("minutes component of time_delta is too large");
377 }
378
379 if (seconds >= 60) {
380 fr_strerror_printf("seconds component of time_delta is too large");
382 }
383 }
384
385 if (no_trailing && !fr_sbuff_is_terminal(&our_in, tt)) goto fail_trailing_data;
386
387 /*
388 * Add all the components together...
389 */
390 if (!fr_add(&integer, ((hours * 60) * 60) + (minutes * 60), seconds)) goto fail_overflow;
391
392 /*
393 * Flip the sign back to negative
394 */
395 if (negative) integer = -(integer);
396 }
397
398 *out = fr_time_delta_from_sec(integer);
399 FR_SBUFF_SET_RETURN(in, &our_in);
400}
401
402/** Create fr_time_delta_t from a string
403 *
404 * @param[out] out Where to write fr_time_delta_t
405 * @param[in] in String to parse.
406 * @param[in] inlen Length of string.
407 * @param[in] hint scale for the parsing. Default is "seconds"
408 * @return
409 * - >0 on success.
410 * - <0 on failure.
411 */
413{
414 fr_slen_t slen;
415
416 if (!*in) {
417 fr_strerror_const("Empty input is invalid");
418 return -1;
419 }
420
421 slen = fr_time_delta_from_substr(out, &FR_SBUFF_IN(in, inlen), hint, true, NULL);
422 if (slen < 0) return slen;
423 if (slen != (fr_slen_t)inlen) {
424 fr_strerror_const("trailing data after time_delta"); /* Shouldn't happen with no_trailing */
425 return -(inlen + 1);
426 }
427 return slen;
428}
429
430/** Print fr_time_delta_t to a string with an appropriate suffix
431 *
432 * @param[out] out Where to write the string version of the time delta.
433 * @param[in] delta to print.
434 * @param[in] res to print resolution with.
435 * @param[in] is_unsigned whether the value should be printed unsigned.
436 * @return
437 * - >0 the number of bytes written to out.
438 * - <0 how many additional bytes would have been required.
439 */
441{
442 fr_sbuff_t our_out = FR_SBUFF(out);
443 char *q;
444 int64_t lhs = 0;
445 uint64_t rhs = 0;
446
447/*
448 * The % operator can return a _signed_ value. This macro is
449 * correct for both positive and negative inputs.
450 */
451#define MOD(a,b) (((a<0) ? (-a) : (a))%(b))
452
453 lhs = fr_time_delta_to_integer(delta, res);
455
456 if (!is_unsigned) {
457 /*
458 * 0 is unsigned, but we want to print
459 * "-0.1" if necessary.
460 */
461 if ((lhs == 0) && fr_time_delta_isneg(delta)) {
462 FR_SBUFF_IN_CHAR_RETURN(&our_out, '-');
463 }
464
465 FR_SBUFF_IN_SPRINTF_RETURN(&our_out, "%" PRIi64 ".%09" PRIu64, lhs, rhs);
466 } else {
467 if (fr_time_delta_isneg(delta)) lhs = rhs = 0;
468
469 FR_SBUFF_IN_SPRINTF_RETURN(&our_out, "%" PRIu64 ".%09" PRIu64, lhs, rhs);
470 }
471 q = fr_sbuff_current(&our_out) - 1;
472
473 /*
474 * Truncate trailing zeros.
475 */
476 while (*q == '0') *(q--) = '\0';
477
478 /*
479 * If there's nothing after the decimal point,
480 * truncate the decimal point. i.e. Don't print
481 * "5."
482 */
483 if (*q == '.') {
484 *q = '\0';
485 } else {
486 q++; /* to account for q-- above */
487 }
488
490}
491
492DIAG_OFF(format-nonliteral)
493/** Copy a time string (local timezone) to an sbuff
494 *
495 * @note This function will attempt to extend the sbuff by double the length of
496 * the fmt string. It is recommended to either pre-extend the sbuff before
497 * calling this function, or avoid using format specifiers that expand to
498 * character strings longer than 4 bytes.
499 *
500 * @param[in] out Where to write the formatted time string.
501 * @param[in] time Internal server time to convert to wallclock
502 * time and copy out as formatted string.
503 * @param[in] fmt Time format string.
504 * @return
505 * - >0 the number of bytes written to the sbuff.
506 * - 0 if there's insufficient space in the sbuff.
507 */
509{
510 struct tm tm;
511 time_t utime = fr_time_to_sec(time);
512 size_t len;
513
514 localtime_r(&utime, &tm);
515
516 len = strftime(fr_sbuff_current(out), fr_sbuff_extend_lowat(NULL, out, strlen(fmt) * 2), fmt, &tm);
517 if (len == 0) return 0;
518
519 return fr_sbuff_advance(out, len);
520}
521
522/** Copy a time string (UTC) to an sbuff
523 *
524 * @note This function will attempt to extend the sbuff by double the length of
525 * the fmt string. It is recommended to either pre-extend the sbuff before
526 * calling this function, or avoid using format specifiers that expand to
527 * character strings longer than 4 bytes.
528 *
529 * @param[in] out Where to write the formatted time string.
530 * @param[in] time Internal server time to convert to wallclock
531 * time and copy out as formatted string.
532 * @param[in] fmt Time format string.
533 * @return
534 * - >0 the number of bytes written to the sbuff.
535 * - 0 if there's insufficient space in the sbuff.
536 */
538{
539 struct tm tm;
540 time_t utime = fr_time_to_sec(time);
541 size_t len;
542
543 gmtime_r(&utime, &tm);
544
545 len = strftime(fr_sbuff_current(out), fr_sbuff_extend_lowat(NULL, out, strlen(fmt) * 2), fmt, &tm);
546 if (len == 0) return 0;
547
548 return fr_sbuff_advance(out, len);
549}
550DIAG_ON(format-nonliteral)
551
553{
554 fr_time_delta_t delay;
555
556 if (fr_time_gteq(start, end)) {
557 delay = fr_time_delta_wrap(0);
558 } else {
559 delay = fr_time_sub(end, start);
560 }
561
562 if (fr_time_delta_lt(delay, fr_time_delta_wrap(1000))) { /* microseconds */
563 elapsed->array[0]++;
564
565 } else if (fr_time_delta_lt(delay, fr_time_delta_wrap(10000))) {
566 elapsed->array[1]++;
567
568 } else if (fr_time_delta_lt(delay, fr_time_delta_wrap(100000))) {
569 elapsed->array[2]++;
570
571 } else if (fr_time_delta_lt(delay, fr_time_delta_wrap(1000000))) { /* milliseconds */
572 elapsed->array[3]++;
573
574 } else if (fr_time_delta_lt(delay, fr_time_delta_wrap(10000000))) {
575 elapsed->array[4]++;
576
577 } else if (fr_time_delta_lt(delay, fr_time_delta_wrap(100000000))) {
578 elapsed->array[5]++;
579
580 } else if (fr_time_delta_lt(delay, fr_time_delta_wrap(1000000000))) { /* seconds */
581 elapsed->array[6]++;
582
583 } else { /* tens of seconds or more */
584 elapsed->array[7]++;
585
586 }
587}
588
589static const char *names[8] = {
590 "1us", "10us", "100us",
591 "1ms", "10ms", "100ms",
592 "1s", "10s"
593};
594
595static char const *tab_string = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
596
597void fr_time_elapsed_fprint(FILE *fp, fr_time_elapsed_t const *elapsed, char const *prefix, int tab_offset)
598{
599 int i;
600 size_t prefix_len;
601
602 if (!prefix) prefix = "elapsed";
603
604 prefix_len = strlen(prefix);
605
606 for (i = 0; i < 8; i++) {
607 size_t len;
608
609 if (!elapsed->array[i]) continue;
610
611 len = prefix_len + 1 + strlen(names[i]);
612
613 if (len >= (size_t) (tab_offset * 8)) {
614 fprintf(fp, "%s.%s %" PRIu64 "\n",
615 prefix, names[i], elapsed->array[i]);
616
617 } else {
618 int tabs;
619
620 tabs = ((tab_offset * 8) - len);
621 if ((tabs & 0x07) != 0) tabs += 7;
622 tabs >>= 3;
623
624 fprintf(fp, "%s.%s%.*s%" PRIu64 "\n",
625 prefix, names[i], tabs, tab_string, elapsed->array[i]);
626 }
627 }
628}
629
630/*
631 * Based on https://blog.reverberate.org/2020/05/12/optimizing-date-algorithms.html
632 */
634{
635 static const uint16_t month_yday[12] = {0, 31, 59, 90, 120, 151,
636 181, 212, 243, 273, 304, 334};
637
638 uint32_t year_adj;
639 uint32_t febs;
640 uint32_t leap_days;
641 uint32_t days;
642
643 /* Prevent crash if tm->tm_mon is invalid - seen in clusterfuzz */
644 if (unlikely(tm->tm_mon >= (__typeof__(tm->tm_mon))NUM_ELEMENTS(month_yday))) return fr_unix_time_min();
645
646 if (unlikely(tm->tm_year > 10000)) return fr_unix_time_min();
647
648 year_adj = tm->tm_year + 4800 + 1900; /* Ensure positive year, multiple of 400. */
649 febs = year_adj - (tm->tm_mon < 2 ? 1 : 0); /* Februaries since base. tm_mon is 0 - 11 */
650 leap_days = 1 + (febs / 4) - (febs / 100) + (febs / 400);
651
652 days = 365 * year_adj + leap_days + month_yday[tm->tm_mon] + tm->tm_mday - 1;
653
654#define CHECK(_x, _max) if ((tm->tm_ ## _x < 0) || (tm->tm_ ## _x >= _max)) tm->tm_ ## _x = _max - 1
655
656 CHECK(sec, 60);
657 CHECK(min, 60);
658 CHECK(hour, 24);
659 CHECK(mday, 32);
660 CHECK(mon, 12);
661 CHECK(year, 3000);
662 CHECK(wday, 7);
663 CHECK(mon, 12);
664 CHECK(yday, 366);
665 /* don't check gmtoff, it can be negative */
666
667 /*
668 * 2472692 adjusts the days for Unix epoch. It is calculated as
669 * (365.2425 * (4800 + 1970))
670 *
671 * We REMOVE the time zone offset in order to get internal unix times in UTC.
672 */
673 return fr_unix_time_from_sec((((days - 2472692) * 86400) + (tm->tm_hour * 3600) +
674 (tm->tm_min * 60) + tm->tm_sec) - tm->tm_gmtoff);
675}
676
677/** Scale an input time to NSEC, clamping it at max / min.
678 *
679 * @param t input time / time delta
680 * @param hint time resolution hint
681 * @return
682 * - INT64_MIN on underflow
683 * - 0 on invalid hint
684 * - INT64_MAX on overflow
685 * - otherwise a valid number, multiplied by the relevant scale,
686 * so that the result is in nanoseconds.
687 */
688int64_t fr_time_scale(int64_t t, fr_time_res_t hint)
689{
690 int64_t scale;
691
692 switch (hint) {
693 case FR_TIME_RES_SEC:
694 scale = NSEC;
695 break;
696
697 case FR_TIME_RES_MSEC:
698 scale = 1000000;
699 break;
700
701 case FR_TIME_RES_USEC:
702 scale = 1000;
703 break;
704
705 case FR_TIME_RES_NSEC:
706 return t;
707
708 default:
709 return 0;
710 }
711
712 if (t < 0) {
713 if (t < (INT64_MIN / scale)) {
714 return INT64_MIN;
715 }
716 } else if (t > 0) {
717 if (t > (INT64_MAX / scale)) {
718 return INT64_MAX;
719 }
720 }
721
722 return t * scale;
723}
724
725
726/*
727 * Sort of strtok/strsep function.
728 */
729static char *mystrtok(char **ptr, char const *sep)
730{
731 char *res;
732
733 if (**ptr == '\0') return NULL;
734
735 while (**ptr && strchr(sep, **ptr)) (*ptr)++;
736
737 if (**ptr == '\0') return NULL;
738
739 res = *ptr;
740 while (**ptr && strchr(sep, **ptr) == NULL) (*ptr)++;
741
742 if (**ptr != '\0') *(*ptr)++ = '\0';
743
744 return res;
745}
746
747/*
748 * Helper function to get a 2-digit date. With a maximum value,
749 * and a terminating character.
750 */
751static int get_part(char **str, int *date, int min, int max, char term, char const *name)
752{
753 char *p = *str;
754
755 if (!isdigit((uint8_t) *p) || !isdigit((uint8_t) p[1])) return -1;
756 *date = (p[0] - '0') * 10 + (p[1] - '0');
757
758 if (*date < min) {
759 fr_strerror_printf("Invalid %s (too small)", name);
760 return -1;
761 }
762
763 if (*date > max) {
764 fr_strerror_printf("Invalid %s (too large)", name);
765 return -1;
766 }
767
768 p += 2;
769 if (!term) {
770 *str = p;
771 return 0;
772 }
773
774 if (*p != term) {
775 fr_strerror_printf("Expected '%c' after %s, got '%c'",
776 term, name, *p);
777 return -1;
778 }
779 p++;
780
781 *str = p;
782 return 0;
783}
784
785static char const *months[] = {
786 "jan", "feb", "mar", "apr", "may", "jun",
787 "jul", "aug", "sep", "oct", "nov", "dec" };
788
789
790/** Convert string in various formats to a fr_unix_time_t
791 *
792 * @param date_str input date string.
793 * @param date time_t to write result to.
794 * @param[in] hint scale for the parsing. Default is "seconds"
795 * @return
796 * - 0 on success.
797 * - -1 on failure.
798 */
799int fr_unix_time_from_str(fr_unix_time_t *date, char const *date_str, fr_time_res_t hint)
800{
801 int i;
802 int64_t tmp;
803 struct tm *tm, s_tm;
804 char buf[64];
805 char *p;
806 char *f[4];
807 char *tail = NULL;
808 unsigned long l;
809 fr_time_delta_t gmt_delta = fr_time_delta_wrap(0);
810
811 if (!*date_str) {
812 fr_strerror_const("Empty input is invalid");
813 return -1;
814 }
815
816 /*
817 * Test for unix timestamp, which is just a number and
818 * nothing else.
819 */
820 tmp = strtoul(date_str, &tail, 10);
821 if (*tail == '\0') {
822 *date = fr_unix_time_from_nsec(fr_time_scale(tmp, hint));
823 return 0;
824 }
825
826 tm = &s_tm;
827 memset(tm, 0, sizeof(*tm));
828 tm->tm_isdst = -1; /* don't know, and don't care about DST */
829
830 /*
831 * Check for RFC 3339 dates. Note that we only support
832 * dates in a ~1000 year period. If the server is being
833 * used after 3000AD, someone can patch it then.
834 *
835 * %Y-%m-%dT%H:%M:%S
836 * [.%d] sub-seconds
837 * Z | (+/-)%H:%M time zone offset
838 *
839 */
840 if ((tmp > 1900) && (tmp < 3000) && *tail == '-') {
841 unsigned long subseconds;
842 int tz, tz_hour, tz_min;
843
844 p = tail + 1;
845 s_tm.tm_year = tmp - 1900; /* 'struct tm' starts years in 1900 */
846
847 if (get_part(&p, &s_tm.tm_mon, 1, 12, '-', "month") < 0) return -1;
848 s_tm.tm_mon--; /* ISO is 1..12, where 'struct tm' is 0..11 */
849
850 if (get_part(&p, &s_tm.tm_mday, 1, 31, 'T', "day") < 0) return -1;
851 if (get_part(&p, &s_tm.tm_hour, 0, 23, ':', "hour") < 0) return -1;
852 if (get_part(&p, &s_tm.tm_min, 0, 59, ':', "minute") < 0) return -1;
853 if (get_part(&p, &s_tm.tm_sec, 0, 60, '\0', "seconds") < 0) return -1;
854
855 if (*p == '.') {
856 p++;
857 subseconds = strtoul(p, &tail, 10);
858 if (subseconds > NSEC) {
859 fr_strerror_const("Invalid nanosecond specifier");
860 return -1;
861 }
862
863 /*
864 * Scale subseconds to nanoseconds by how
865 * many digits were parsed/
866 */
867 if ((tail - p) < 9) {
868 for (i = 0; i < 9 - (tail -p); i++) {
869 subseconds *= 10;
870 }
871 }
872
873 p = tail;
874 } else {
875 subseconds = 0;
876 }
877
878 /*
879 * Time zone is GMT. Leave well enough
880 * alone.
881 */
882 if (*p == 'Z') {
883 if (p[1] != '\0') {
884 fr_strerror_printf("Unexpected text '%c' after time zone", p[1]);
885 return -1;
886 }
887 tz = 0;
888 goto done;
889 }
890
891 if ((*p != '+') && (*p != '-')) {
892 fr_strerror_printf("Invalid time zone specifier '%c'", *p);
893 return -1;
894 }
895 tail = p; /* remember sign for later */
896 p++;
897
898 if (get_part(&p, &tz_hour, 0, 23, ':', "hour in time zone") < 0) return -1;
899 if (get_part(&p, &tz_min, 0, 59, '\0', "minute in time zone") < 0) return -1;
900
901 if (*p != '\0') {
902 fr_strerror_printf("Unexpected text '%c' after time zone", *p);
903 return -1;
904 }
905
906 /*
907 * We set the time zone, but the timegm()
908 * function ignores it. Note also that mktime()
909 * ignores it too, and treats the time zone as
910 * local.
911 *
912 * We can't store this value in s_tm.gtmoff,
913 * because the timegm() function helpfully zeros
914 * it out.
915 *
916 * So insyead of using stupid C library
917 * functions, we just roll our own.
918 */
919 tz = tz_hour * 3600 + tz_min;
920 if (*tail == '-') tz *= -1;
921
922 done:
923 /*
924 * We REMOVE the time zone offset in order to get internal unix times in UTC.
925 */
926 tm->tm_gmtoff = -tz;
928 return 0;
929 }
930
931 /*
932 * Try to parse dates via locale-specific names,
933 * using the same format string as strftime().
934 *
935 * If that fails, then we fall back to our parsing
936 * routine, which is much more forgiving.
937 */
938
939#ifdef __APPLE__
940 /*
941 * OSX "man strptime" says it only accepts the local time zone, and GMT.
942 *
943 * However, when printing dates via strftime(), it prints
944 * "UTC" instead of "GMT". So... we have to fix it up
945 * for stupid nonsense.
946 */
947 {
948 char const *tz = strstr(date_str, "UTC");
949 if (tz) {
950 char *my_str;
951
952 my_str = talloc_strdup(NULL, date_str);
953 if (my_str) {
954 p = my_str + (tz - date_str);
955 memcpy(p, "GMT", 3);
956
957 p = strptime(my_str, "%b %e %Y %H:%M:%S %Z", tm);
958 if (p && (*p == '\0')) {
959 talloc_free(my_str);
960 *date = fr_unix_time_from_tm(tm);
961 return 0;
962 }
963 talloc_free(my_str);
964 }
965 }
966 }
967#endif
968
969 p = strptime(date_str, "%b %e %Y %H:%M:%S %Z", tm);
970 if (p && (*p == '\0')) {
971 *date = fr_unix_time_from_tm(tm);
972 return 0;
973 }
974
975 strlcpy(buf, date_str, sizeof(buf));
976
977 p = buf;
978 f[0] = mystrtok(&p, " \t");
979 f[1] = mystrtok(&p, " \t");
980 f[2] = mystrtok(&p, " \t");
981 f[3] = mystrtok(&p, " \t"); /* may, or may not, be present */
982 if (!f[0] || !f[1] || !f[2]) {
983 fr_strerror_const("Too few fields");
984 return -1;
985 }
986
987 /*
988 * Try to parse the time zone. If it's GMT / UTC or a
989 * local time zone we're OK.
990 *
991 * Otherwise, ignore errors and assume GMT.
992 */
993 if (*p != '\0') {
995 (void) fr_time_delta_from_time_zone(p, &gmt_delta);
996 }
997
998 /*
999 * The time has a colon, where nothing else does.
1000 * So if we find it, bubble it to the back of the list.
1001 */
1002 if (f[3]) {
1003 for (i = 0; i < 3; i++) {
1004 if (strchr(f[i], ':')) {
1005 p = f[3];
1006 f[3] = f[i];
1007 f[i] = p;
1008 break;
1009 }
1010 }
1011 }
1012
1013 /*
1014 * The month is text, which allows us to find it easily.
1015 */
1016 tm->tm_mon = 12;
1017 for (i = 0; i < 3; i++) {
1018 if (isalpha((uint8_t) *f[i])) {
1019 int j;
1020
1021 /*
1022 * Bubble the month to the front of the list
1023 */
1024 p = f[0];
1025 f[0] = f[i];
1026 f[i] = p;
1027
1028 for (j = 0; j < 12; j++) {
1029 if (strncasecmp(months[j], f[0], 3) == 0) {
1030 tm->tm_mon = j;
1031 break;
1032 }
1033 }
1034 }
1035 }
1036
1037 /* month not found? */
1038 if (tm->tm_mon == 12) {
1039 fr_strerror_const("No month found");
1040 return -1;
1041 }
1042
1043 /*
1044 * Check for invalid text, or invalid trailing text.
1045 */
1046 l = strtoul(f[1], &tail, 10);
1047 if ((l == ULONG_MAX) || (*tail != '\0')) {
1048 fr_strerror_const("Invalid year string");
1049 return -1;
1050 }
1051 tm->tm_year = l;
1052
1053 l = strtoul(f[2], &tail, 10);
1054 if ((l == ULONG_MAX) || (*tail != '\0')) {
1055 fr_strerror_const("Invalid day of month string");
1056 return -1;
1057 }
1058 tm->tm_mday = l;
1059
1060 if (tm->tm_year >= 1900) {
1061 tm->tm_year -= 1900;
1062
1063 } else {
1064 /*
1065 * We can't use 2-digit years any more, they make it
1066 * impossible to tell what's the day, and what's the year.
1067 */
1068 if (tm->tm_mday < 1900) {
1069 fr_strerror_const("Invalid year < 1900");
1070 return -1;
1071 }
1072
1073 /*
1074 * Swap the year and the day.
1075 */
1076 i = tm->tm_year;
1077 tm->tm_year = tm->tm_mday - 1900;
1078 tm->tm_mday = i;
1079 }
1080
1081 if (tm->tm_year > 10000) {
1082 fr_strerror_const("Invalid value for year");
1083 return -1;
1084 }
1085
1086 /*
1087 * If the day is out of range, die.
1088 */
1089 if ((tm->tm_mday < 1) || (tm->tm_mday > 31)) {
1090 fr_strerror_const("Invalid value for day of month");
1091 return -1;
1092 }
1093
1094 /*
1095 * There may be %H:%M:%S. Parse it in a hacky way.
1096 */
1097 if (f[3]) {
1098 f[0] = f[3]; /* HH */
1099 f[1] = strchr(f[0], ':'); /* find : separator */
1100 if (!f[1]) {
1101 fr_strerror_const("No ':' after hour");
1102 return -1;
1103 }
1104
1105 *(f[1]++) = '\0'; /* nuke it, and point to MM:SS */
1106
1107 f[2] = strchr(f[1], ':'); /* find : separator */
1108 if (f[2]) {
1109 *(f[2]++) = '\0'; /* nuke it, and point to SS */
1110 tm->tm_sec = atoi(f[2]);
1111 } /* else leave it as zero */
1112
1113 tm->tm_hour = atoi(f[0]);
1114 tm->tm_min = atoi(f[1]);
1115 }
1116
1117 *date = fr_unix_time_add(fr_unix_time_from_tm(tm), gmt_delta);
1118
1119 return 0;
1120}
1121
1122/** Convert unix time to string
1123 *
1124 * @param[out] out Where to write the string.
1125 * @param[in] time to convert.
1126 * @param[in] res What base resolution to print the time as.
1127 * @param[in] utc If true, use UTC, otherwise local time.
1128 * @return
1129 * - 0 on success.
1130 * - -1 on failure.
1131 */
1133{
1134 fr_sbuff_t our_out = FR_SBUFF(out);
1135 int64_t subseconds;
1136 time_t t;
1137 struct tm s_tm;
1138 size_t len;
1139 char buf[128];
1140
1141 t = fr_unix_time_to_sec(time);
1142 if (utc) {
1143 (void) gmtime_r(&t, &s_tm);
1144 } else {
1145 (void) localtime_r(&t, &s_tm);
1146 }
1147
1148 len = strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &s_tm);
1149 FR_SBUFF_IN_BSTRNCPY_RETURN(&our_out, buf, len);
1150 subseconds = fr_unix_time_unwrap(time) % NSEC;
1151
1152 /*
1153 * Use RFC 3339 format, which is a
1154 * profile of ISO8601. The ISO standard
1155 * allows a much more complex set of date
1156 * formats. The RFC is much stricter.
1157 */
1158 switch (res) {
1160 case FR_TIME_RES_YEAR:
1161 case FR_TIME_RES_MONTH:
1162 case FR_TIME_RES_WEEK:
1163 case FR_TIME_RES_DAY:
1164 case FR_TIME_RES_HOUR:
1165 case FR_TIME_RES_MIN:
1166 case FR_TIME_RES_SEC:
1167 break;
1168
1169 case FR_TIME_RES_CSEC:
1170 subseconds /= (NSEC / CSEC);
1171 FR_SBUFF_IN_SPRINTF_RETURN(&our_out, ".%02" PRIi64, subseconds);
1172 break;
1173
1174 case FR_TIME_RES_MSEC:
1175 subseconds /= (NSEC / MSEC);
1176 FR_SBUFF_IN_SPRINTF_RETURN(&our_out, ".%03" PRIi64, subseconds);
1177 break;
1178
1179 case FR_TIME_RES_USEC:
1180 subseconds /= (NSEC / USEC);
1181 FR_SBUFF_IN_SPRINTF_RETURN(&our_out, ".%06" PRIi64, subseconds);
1182 break;
1183
1184 case FR_TIME_RES_NSEC:
1185 FR_SBUFF_IN_SPRINTF_RETURN(&our_out, ".%09" PRIi64, subseconds);
1186 break;
1187 }
1188
1189 /*
1190 * And time zone.
1191 */
1192 if (s_tm.tm_gmtoff != 0) {
1193 int hours, minutes;
1194
1195 hours = s_tm.tm_gmtoff / 3600;
1196 minutes = (s_tm.tm_gmtoff / 60) % 60;
1197
1198 FR_SBUFF_IN_SPRINTF_RETURN(&our_out, "%+03d:%02u", hours, minutes);
1199 } else {
1200 FR_SBUFF_IN_CHAR_RETURN(&our_out, 'Z');
1201 }
1202
1203 FR_SBUFF_SET_RETURN(out, &our_out);
1204}
1205
1206/** Get the offset to gmt.
1207 *
1208 */
1213
1214/** Whether or not we're daylight savings.
1215 *
1216 */
1218{
1219 return isdst;
1220}
static int const char * fmt
Definition acutest.h:573
#define RCSID(id)
Definition build.h:506
#define L(_str)
Helper for initialising arrays of string literals.
Definition build.h:228
#define DIAG_ON(_x)
Definition build.h:481
#define unlikely(_x)
Definition build.h:402
#define NUM_ELEMENTS(_t)
Definition build.h:358
#define DIAG_OFF(_x)
Definition build.h:480
static const char * tabs
Definition command.c:1589
static size_t min(size_t x, size_t y)
Definition dbuff.c:66
static fr_slen_t err
Definition dict.h:882
static fr_slen_t in
Definition dict.h:882
talloc_free(hp)
#define fr_add(_out, _a, _b)
Adds two integers.
Definition math.h:187
unsigned short uint16_t
unsigned int uint32_t
unsigned char uint8_t
ssize_t fr_slen_t
unsigned long int size_t
fr_sbuff_parse_error_t
@ FR_SBUFF_PARSE_ERROR_NOT_FOUND
String does not contain a token matching the output type.
int strncasecmp(char *s1, char *s2, int n)
Definition missing.c:35
struct tm * gmtime_r(time_t const *l_clock, struct tm *result)
Definition missing.c:205
struct tm * localtime_r(time_t const *l_clock, struct tm *result)
Definition missing.c:162
#define fr_assert(_expr)
Definition rad_assert.h:37
static bool done
Definition radclient.c:80
static char const * name
bool fr_sbuff_is_terminal(fr_sbuff_t *in, fr_sbuff_term_t const *tt)
Efficient terminal string search.
Definition sbuff.c:2193
fr_table_num_ordered_t const sbuff_parse_error_table[]
Definition sbuff.c:43
bool fr_sbuff_next_if_char(fr_sbuff_t *sbuff, char c)
Return true if the current char matches, and if it does, advance.
Definition sbuff.c:2129
#define fr_sbuff_out_by_longest_prefix(_match_len, _out, _table, _sbuff, _def)
#define FR_SBUFF_IN_CHAR_RETURN(_sbuff,...)
#define FR_SBUFF_IN(_start, _len_or_end)
#define fr_sbuff_current(_sbuff_or_marker)
#define fr_sbuff_is_char(_sbuff_or_marker, _c)
#define FR_SBUFF_ERROR_RETURN(_sbuff_or_marker)
#define FR_SBUFF_SET_RETURN(_dst, _src)
#define FR_SBUFF_IN_SPRINTF_RETURN(...)
#define FR_SBUFF(_sbuff_or_marker)
#define FR_SBUFF_IN_BSTRNCPY_RETURN(...)
#define fr_sbuff_advance(_sbuff_or_marker, _len)
#define fr_sbuff_out(_err, _out, _in)
#define fr_sbuff_extend_lowat(_status, _sbuff_or_marker, _lowat)
Set of terminal elements.
#define fr_skip_whitespace(_p)
Skip whitespace ('\t', '\n', '\v', '\f', '\r', ' ')
Definition skip.h:36
@ memory_order_release
Definition stdatomic.h:130
#define _Atomic(T)
Definition stdatomic.h:77
#define atomic_store_explicit(object, desired, order)
Definition stdatomic.h:314
size_t strlcpy(char *dst, char const *src, size_t siz)
Definition strlcpy.c:34
#define fr_table_str_by_value(_table, _number, _def)
Convert an integer to a string.
Definition table.h:772
An element in an arbitrarily ordered array of name to num mappings.
Definition table.h:57
#define talloc_strdup(_ctx, _str)
Definition talloc.h:142
static char * mystrtok(char **ptr, char const *sep)
Definition time.c:729
void fr_time_elapsed_update(fr_time_elapsed_t *elapsed, fr_time_t start, fr_time_t end)
Definition time.c:552
fr_unix_time_t fr_unix_time_from_tm(struct tm *tm)
Definition time.c:633
static char const * tab_string
Definition time.c:595
static const char * names[8]
Definition time.c:589
int fr_time_sync(void)
Get a new fr_time_monotonic_to_realtime value.
Definition time.c:102
static int get_part(char **str, int *date, int min, int max, char term, char const *name)
Definition time.c:751
static long gmtoff[2]
from localtime_r(), tm_gmtoff
Definition time.c:90
fr_table_num_ordered_t const fr_time_precision_table[]
Definition time.c:46
size_t fr_time_strftime_local(fr_sbuff_t *out, fr_time_t time, char const *fmt)
Copy a time string (local timezone) to an sbuff.
Definition time.c:508
#define CHECK(_x, _max)
fr_slen_t fr_time_delta_from_substr(fr_time_delta_t *out, fr_sbuff_t *in, fr_time_res_t hint, bool no_trailing, fr_sbuff_term_t const *tt)
Create fr_time_delta_t from a string.
Definition time.c:214
int fr_time_delta_from_time_zone(char const *tz, fr_time_delta_t *delta)
Return time delta from the time zone.
Definition time.c:176
fr_slen_t fr_time_delta_from_str(fr_time_delta_t *out, char const *in, size_t inlen, fr_time_res_t hint)
Create fr_time_delta_t from a string.
Definition time.c:412
bool fr_time_is_dst(void)
Whether or not we're daylight savings.
Definition time.c:1217
void fr_time_elapsed_fprint(FILE *fp, fr_time_elapsed_t const *elapsed, char const *prefix, int tab_offset)
Definition time.c:597
_Atomic int64_t fr_time_monotonic_to_realtime
difference between the two clocks
Definition time.c:87
int fr_unix_time_from_str(fr_unix_time_t *date, char const *date_str, fr_time_res_t hint)
Convert string in various formats to a fr_unix_time_t.
Definition time.c:799
int64_t fr_time_scale(int64_t t, fr_time_res_t hint)
Scale an input time to NSEC, clamping it at max / min.
Definition time.c:688
#define MOD(a, b)
static char const * months[]
Definition time.c:785
fr_time_delta_t fr_time_gmtoff(void)
Get the offset to gmt.
Definition time.c:1209
fr_slen_t fr_time_delta_to_str(fr_sbuff_t *out, fr_time_delta_t delta, fr_time_res_t res, bool is_unsigned)
Print fr_time_delta_t to a string with an appropriate suffix.
Definition time.c:440
size_t fr_time_precision_table_len
Definition time.c:84
static char const * tz_names[2]
normal, DST, from localtime_r(), tm_zone
Definition time.c:89
int fr_time_start(void)
Initialize the local time.
Definition time.c:150
static bool isdst
from localtime_r(), tm_is_dst
Definition time.c:91
fr_slen_t fr_unix_time_to_str(fr_sbuff_t *out, fr_unix_time_t time, fr_time_res_t res, bool utc)
Convert unix time to string.
Definition time.c:1132
int64_t fr_time_epoch
monotonic clock at boot, i.e. our epoch
Definition time.c:86
size_t fr_time_strftime_utc(fr_sbuff_t *out, fr_time_t time, char const *fmt)
Copy a time string (UTC) to an sbuff.
Definition time.c:537
int64_t const fr_time_multiplier_by_res[]
Definition time.c:32
static fr_time_delta_t fr_time_delta_from_integer(bool *overflow, int64_t integer, fr_time_res_t res)
Definition time.h:548
#define MSEC
Definition time.h:381
static int64_t fr_time_delta_to_integer(fr_time_delta_t delta, fr_time_res_t res)
Definition time.h:627
static int64_t fr_time_to_sec(fr_time_t when)
Convert an fr_time_t (internal time) to number of sec since the unix epoch (wallclock time)
Definition time.h:731
#define fr_time_gteq(_a, _b)
Definition time.h:238
static fr_unix_time_t fr_unix_time_from_nsec(int64_t nsec)
Definition time.h:423
static int64_t fr_time_delta_unwrap(fr_time_delta_t time)
Definition time.h:154
#define fr_time_delta_isneg(_a)
Definition time.h:291
#define fr_time_delta_lt(_a, _b)
Definition time.h:285
static fr_time_delta_t fr_time_delta_from_sec(int64_t sec)
Definition time.h:590
static int64_t fr_unix_time_to_sec(fr_unix_time_t delta)
Definition time.h:506
#define fr_time_delta_wrap(_time)
Definition time.h:152
#define fr_unix_time_min()
Definition time.h:159
fr_time_res_t
The base resolution for print parse operations.
Definition time.h:48
@ FR_TIME_RES_MONTH
Definition time.h:55
@ FR_TIME_RES_MSEC
Definition time.h:58
@ FR_TIME_RES_WEEK
Definition time.h:54
@ FR_TIME_RES_MIN
Definition time.h:51
@ FR_TIME_RES_CSEC
Definition time.h:57
@ FR_TIME_RES_HOUR
Definition time.h:52
@ FR_TIME_RES_YEAR
Definition time.h:56
@ FR_TIME_RES_DAY
Definition time.h:53
@ FR_TIME_RES_NSEC
Definition time.h:60
@ FR_TIME_RES_USEC
Definition time.h:59
@ FR_TIME_RES_SEC
Definition time.h:50
@ FR_TIME_RES_INVALID
Definition time.h:49
static fr_unix_time_t fr_unix_time_from_sec(int64_t sec)
Definition time.h:449
#define NSEC
Definition time.h:379
static uint64_t fr_unix_time_unwrap(fr_unix_time_t time)
Definition time.h:161
#define CLOCK_MONOTONIC_RAW
Definition time.h:950
uint64_t array[8]
100ns to 100s
Definition time.h:376
#define USEC
Definition time.h:380
#define fr_time_sub(_a, _b)
Subtract one time from another.
Definition time.h:229
#define FR_TIME_DUR_MONTH
Definition time.h:394
#define CSEC
Definition time.h:382
#define fr_unix_time_add(_a, _b)
Add a time/time delta together.
Definition time.h:324
static fr_time_delta_t fr_time_delta_from_timespec(struct timespec const *ts)
Definition time.h:614
#define FR_TIME_DUR_YEAR
Definition time.h:393
A time delta, a difference in time measured in nanoseconds.
Definition time.h:80
"server local" time.
Definition time.h:69
"Unix" time.
Definition time.h:95
#define fr_strerror_printf(_fmt,...)
Log to thread local error buffer.
Definition strerror.h:64
#define fr_strerror_const(_msg)
Definition strerror.h:223
static size_t char fr_sbuff_t size_t inlen
Definition value.h:1030
static size_t char ** out
Definition value.h:1030