2 * Routines for manipulating nstime_t structures
4 * Copyright (c) 2005 MX Telecom Ltd. <richardv@mxtelecom.com>
6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
10 * SPDX-License-Identifier: GPL-2.0-or-later
18 #include "time_util.h"
22 /* this is #defined so that we can clearly see that we have the right number of
23 zeros, rather than as a guard against the number of nanoseconds in a second
25 #define NS_PER_S 1000000000
27 /* set the given nstime_t to zero */
28 void nstime_set_zero(nstime_t
*nstime
)
34 /* is the given nstime_t currently zero? */
35 bool nstime_is_zero(const nstime_t
*nstime
)
37 return nstime
->secs
== 0 && nstime
->nsecs
== 0;
40 /* set the given nstime_t to (0,maxint) to mark it as "unset"
41 * That way we can find the first frame even when a timestamp
42 * is zero (fix for bug 1056)
44 void nstime_set_unset(nstime_t
*nstime
)
47 nstime
->nsecs
= INT_MAX
;
50 /* is the given nstime_t currently (0,maxint)? */
51 bool nstime_is_unset(const nstime_t
*nstime
)
53 if(nstime
->secs
== 0 && nstime
->nsecs
== INT_MAX
) {
61 /** function: nstime_copy
65 void nstime_copy(nstime_t
*a
, const nstime_t
*b
)
72 * function: nstime_delta
76 void nstime_delta(nstime_t
*delta
, const nstime_t
*b
, const nstime_t
*a
)
78 if (b
->secs
== a
->secs
) {
79 /* The seconds part of b is the same as the seconds part of a, so if
80 the nanoseconds part of the first time is less than the nanoseconds
81 part of a, b is before a. The nanoseconds part of the delta should
82 just be the difference between the nanoseconds part of b and the
83 nanoseconds part of a; don't adjust the seconds part of the delta,
84 as it's OK if the nanoseconds part is negative, and an overflow
87 delta
->nsecs
= b
->nsecs
- a
->nsecs
;
88 } else if (b
->secs
< a
->secs
) {
89 /* The seconds part of b is less than the seconds part of a, so b is
92 Both the "seconds" and "nanoseconds" value of the delta
93 should have the same sign, so if the difference between the
94 nanoseconds values would be *positive*, subtract 1,000,000,000
95 from it, and add one to the seconds value. */
96 delta
->secs
= b
->secs
- a
->secs
;
97 delta
->nsecs
= b
->nsecs
- a
->nsecs
;
98 if(delta
->nsecs
> 0) {
99 delta
->nsecs
-= NS_PER_S
;
103 delta
->secs
= b
->secs
- a
->secs
;
104 delta
->nsecs
= b
->nsecs
- a
->nsecs
;
105 if(delta
->nsecs
< 0) {
106 delta
->nsecs
+= NS_PER_S
;
113 * function: nstime_sum
117 void nstime_sum(nstime_t
*sum
, const nstime_t
*a
, const nstime_t
*b
)
119 sum
->secs
= a
->secs
+ b
->secs
;
120 sum
->nsecs
= a
->nsecs
+ b
->nsecs
;
121 if(sum
->nsecs
>=NS_PER_S
|| (sum
->nsecs
>0 && sum
->secs
<0)){
122 sum
->nsecs
-=NS_PER_S
;
124 } else if(sum
->nsecs
<=-NS_PER_S
|| (sum
->nsecs
<0 && sum
->secs
>0)) {
125 sum
->nsecs
+=NS_PER_S
;
131 * function: nstime_cmp
138 int nstime_cmp (const nstime_t
*a
, const nstime_t
*b
)
140 if (G_UNLIKELY(nstime_is_unset(a
))) {
141 if (G_UNLIKELY(nstime_is_unset(b
))) {
142 return 0; /* "no time stamp" is "equal" to "no time stamp" */
144 return -1; /* and is less than all time stamps */
147 if (G_UNLIKELY(nstime_is_unset(b
))) {
151 if (a
->secs
== b
->secs
) {
152 return a
->nsecs
- b
->nsecs
;
154 return (int) (a
->secs
- b
->secs
);
158 unsigned nstime_hash(const nstime_t
*nstime
)
160 int64_t val1
= (int64_t)nstime
->secs
;
162 return g_int64_hash(&val1
) ^ g_int_hash(&nstime
->nsecs
);
166 * function: nstime_to_msec
167 * converts nstime to double, time base is milli seconds
170 double nstime_to_msec(const nstime_t
*nstime
)
172 return ((double)nstime
->secs
*1000 + (double)nstime
->nsecs
/1000000);
176 * function: nstime_to_sec
177 * converts nstime to double, time base is seconds
180 double nstime_to_sec(const nstime_t
*nstime
)
182 return ((double)nstime
->secs
+ (double)nstime
->nsecs
/NS_PER_S
);
186 * Compute the minimum and maximum time_t values.
188 * This code is based on the Samba code:
190 * Unix SMB/Netbios implementation.
192 * time handling functions
193 * Copyright (C) Andrew Tridgell 1992-1998
197 #define TIME_T_MIN ((time_t) ((time_t)0 < (time_t) -1 ? (time_t) 0 \
198 : (time_t) (~0ULL << (sizeof (time_t) * CHAR_BIT - 1))))
201 #define TIME_T_MAX ((time_t) (~ (time_t) 0 - TIME_T_MIN))
205 common_filetime_to_nstime(nstime_t
*nstime
, uint64_t ftsecs
, int nsecs
)
210 * Shift the seconds from the Windows epoch to the UN*X epoch.
211 * ftsecs's value should fit in a 64-bit signed variable, as
212 * ftsecs is derived from a 64-bit fractions-of-a-second value,
213 * and is far from the maximum 64-bit signed value, and
214 * EPOCH_DELTA_1601_01_01_00_00_00_UTC is also far from the
215 * maximum 64-bit signed value, so the difference between them
216 * should also fit in a 64-bit signed value.
218 secs
= (int64_t)ftsecs
- EPOCH_DELTA_1601_01_01_00_00_00_UTC
;
220 if (!(TIME_T_MIN
<= secs
&& secs
<= TIME_T_MAX
)) {
221 /* The result won't fit in a time_t */
226 * Get the time as seconds and nanoseconds.
228 nstime
->secs
= (time_t) secs
;
229 nstime
->nsecs
= nsecs
;
234 * function: filetime_to_nstime
235 * converts a Windows FILETIME value to an nstime_t
236 * returns true if the conversion succeeds, false if it doesn't
237 * (for example, with a 32-bit time_t, the time overflows or
241 filetime_to_nstime(nstime_t
*nstime
, uint64_t filetime
)
247 * Split into seconds and tenths of microseconds, and
248 * then convert tenths of microseconds to nanoseconds.
250 ftsecs
= filetime
/ 10000000;
251 nsecs
= (int)((filetime
% 10000000)*100);
253 return common_filetime_to_nstime(nstime
, ftsecs
, nsecs
);
257 * function: filetime_ns_to_nstime
258 * converts a Windows FILETIME-like value, but given in nanoseconds
259 * rather than 10ths of microseconds, to an nstime_t
260 * returns true if the conversion succeeds, false if it doesn't
261 * (for example, with a 32-bit time_t, the time overflows or
265 filetime_ns_to_nstime(nstime_t
*nstime
, uint64_t nsfiletime
)
270 /* Split into seconds and nanoseconds. */
271 ftsecs
= nsfiletime
/ NS_PER_S
;
272 nsecs
= (int)(nsfiletime
% NS_PER_S
);
274 return common_filetime_to_nstime(nstime
, ftsecs
, nsecs
);
278 * function: filetime_1sec_to_nstime
279 * converts a Windows FILETIME-like value, but given in seconds
280 * rather than 10ths of microseconds, to an nstime_t
281 * returns true if the conversion succeeds, false if it doesn't
282 * (for example, with a 32-bit time_t, the time overflows or
286 filetime_1sec_to_nstime(nstime_t
*nstime
, uint64_t filetime_1sec
)
289 * Make sure filetime_1sec fits in a 64-bit signed integer.
291 if (filetime_1sec
> INT64_MAX
)
292 return false; /* No, it doesn't */
293 return common_filetime_to_nstime(nstime
, filetime_1sec
, 0);
297 * function: iso8601_to_nstime
298 * parses a character string for a date and time given in
299 * ISO 8601 date-time format (eg: 2014-04-07T05:41:56.782+00:00)
300 * and converts to an nstime_t
301 * returns pointer to the first character after the last character
302 * parsed on success, or NULL on failure
304 * NB. ISO 8601 is actually a lot more flexible than the above format,
305 * much to a developer's chagrin. The "basic format" is distinguished from
306 * the "extended format" by lacking the - and : separators. This function
307 * supports both the basic and extended format (as well as both simultaneously)
308 * with several common options and extensions. Time resolution is supported
309 * up to nanoseconds (9 fractional digits) or down to whole minutes (omitting
310 * the seconds component in the latter case). The T separator can be replaced
311 * by a space in either format (a common extension not in ISO 8601 but found
312 * in, e.g., RFC 3339) or omitted entirely in the basic format.
314 * Many standards that use ISO 8601 implement profiles with additional
315 * constraints, such as requiring that the seconds field be present, only
316 * allowing "." as the decimal separator, or limiting the number of fractional
317 * digits. Callers that wish to check constraints not yet enforced by a
318 * profile supported by the function must do so themselves.
320 * Future improvements could parse other ISO 8601 formats, such as
321 * YYYY-Www-D, YYYY-DDD, etc. For a relatively easy introduction to
322 * these formats, see wikipedia: https://en.wikipedia.org/wiki/ISO_8601
325 iso8601_to_nstime(nstime_t
*nstime
, const char *ptr
, iso8601_fmt_e format
)
334 bool has_separator
= false;
335 bool have_offset
= false;
337 memset(&tm
, 0, sizeof(tm
));
339 nstime_set_unset(nstime
);
341 /* Verify that we start with a four digit year and then look for the
343 for (n_scanned
= 0; n_scanned
< 4; n_scanned
++) {
344 if (!g_ascii_isdigit(*ptr
)) {
348 tm
.tm_year
+= *ptr
++ - '0';
352 case ISO8601_DATETIME_BASIC
:
355 case ISO8601_DATETIME
:
356 case ISO8601_DATETIME_AUTO
:
358 has_separator
= true;
361 } else if (g_ascii_isdigit(*ptr
)) {
363 case ISO8601_DATETIME
:
366 case ISO8601_DATETIME_BASIC
:
367 case ISO8601_DATETIME_AUTO
:
369 has_separator
= false;
375 tm
.tm_year
-= 1900; /* struct tm expects number of years since 1900 */
377 /* Note: sscanf is known to be inconsistent across platforms with respect
378 to whether a %n is counted as a return value or not (XXX: Is this
379 still true, despite the express comments of C99 §7.19.6.2 12?), so we
382 /* XXX: sscanf allows an optional sign indicator before each integer
383 * converted (whether with %d or %u), so this will convert some bogus
384 * strings. Either checking afterwards or doing the whole thing by hand
385 * as with the year above is the only correct way. (strptime certainly
386 * can't handle the basic format.)
388 n_scanned
= sscanf(ptr
, has_separator
? "%2u-%2u%n" : "%2u%2u%n",
392 if (n_scanned
>= 2) {
393 /* Got year, month, and day */
394 tm
.tm_mon
--; /* struct tm expects 0-based month */
401 if (*ptr
== 'T' || *ptr
== ' ') {
402 /* The 'T' between date and time is optional if the meaning is
403 unambiguous. We also allow for ' ' here per RFC 3339 to support
404 formats such as editcap's -A/-B options. */
407 else if (has_separator
) {
408 /* Allow no separator between date and time iff we have no
409 separator between units. (Some extended formats may negotiate
410 no separator here, so this could be changed.) */
414 /* Now we're on to the time part. We'll require a minimum of hours and
417 n_scanned
= sscanf(ptr
, has_separator
? "%2u:%2u%n" : "%2u%2u%n",
421 if (n_scanned
>= 2) {
425 /* didn't get hours and minutes */
429 /* Test for (whole) seconds */
430 if ((has_separator
&& *ptr
== ':') ||
431 (!has_separator
&& g_ascii_isdigit(*ptr
))) {
432 /* Looks like we should have them */
433 if (1 > sscanf(ptr
, has_separator
? ":%2u%n" : "%2u%n",
434 &tm
.tm_sec
, &n_chars
)) {
435 /* Couldn't get them */
440 /* Now let's test for fractional seconds */
441 if (*ptr
== '.' || *ptr
== ',') {
442 /* Get fractional seconds */
444 if (1 <= sscanf(ptr
, "%u%n", &frac
, &n_chars
)) {
445 /* normalize frac to nanoseconds */
446 if ((frac
>= 1000000000) || (frac
== 0)) {
449 switch (n_chars
) { /* including leading zeros */
450 case 1: frac
*= 100000000; break;
451 case 2: frac
*= 10000000; break;
452 case 3: frac
*= 1000000; break;
453 case 4: frac
*= 100000; break;
454 case 5: frac
*= 10000; break;
455 case 6: frac
*= 1000; break;
456 case 7: frac
*= 100; break;
457 case 8: frac
*= 10; break;
463 /* If we didn't get frac, it's still its default of 0 */
467 /* No seconds. ISO 8601 allows decimal fractions of a minute here,
468 * but that's pretty rare in practice. Could be added later if needed.
473 /* Validate what we got so far. mktime() doesn't care about strange
474 values but we should at least start with something valid */
475 if (!tm_is_valid(&tm
)) {
479 /* Check for a time zone offset */
480 if (*ptr
== '-' || *ptr
== '+' || *ptr
== 'Z') {
481 /* Just in case somewhere decides to observe a timezone of -00:30 or
484 /* We have a UTC-relative offset */
486 off_hr
= off_min
= 0;
491 off_hr
= off_min
= 0;
492 n_scanned
= sscanf(ptr
, "%3d%n", &off_hr
, &n_chars
);
493 if (n_scanned
>= 1) {
494 /* Definitely got hours */
497 n_scanned
= sscanf(ptr
, *ptr
== ':' ? ":%2d%n" : "%2d%n", &off_min
, &n_chars
);
498 if (n_scanned
>= 1) {
499 /* Got minutes too */
504 /* Didn't get a valid offset, treat as if there's none at all */
510 nstime
->secs
= mktime_utc(&tm
);
512 nstime
->secs
-= (off_hr
* 3600) + (off_min
* 60);
513 } else if (sign
== '-') {
514 /* -00:00 is illegal according to ISO 8601, but RFC 3339 allows
515 * it under a convention where -00:00 means "time in UTC is known,
516 * local timezone is unknown." This has the same value as an
517 * offset of Z or +00:00, but semantically implies that UTC is
518 * not the preferred time zone, which is immaterial to us.
520 /* Add the time, but reverse the sign of off_hr, which includes
523 nstime
->secs
+= ((-off_hr
) * 3600) + (off_min
* 60);
527 /* No UTC offset given; ISO 8601 says this means local time */
528 nstime
->secs
= mktime(&tm
);
530 nstime
->nsecs
= frac
;
535 * function: unix_epoch_to_nstime
536 * parses a character string for a date and time given in
537 * a floating point number containing a Unix epoch date-time
538 * format (e.g. 1600000000.000 for Sun Sep 13 05:26:40 AM PDT 2020)
539 * and converts to an nstime_t
540 * returns pointer to the first character after the last character
541 * parsed on success, or NULL on failure
543 * Reference: https://en.wikipedia.org/wiki/Unix_time
546 unix_epoch_to_nstime(nstime_t
*nstime
, const char *ptr
)
554 nstime_set_unset(nstime
);
557 * Extract the seconds as a 64-bit signed number, as time_t
560 if (!ws_strtoi64(ptr
, &ptr_new
, &secs
)) {
564 /* For now, reject times before the Epoch. */
569 /* Make sure it fits. */
570 nstime
->secs
= (time_t) secs
;
571 if (nstime
->secs
!= secs
) {
575 /* Now let's test for fractional seconds */
576 if (*ptr_new
== '.' || *ptr_new
== ',') {
577 /* Get fractional seconds */
579 if (1 <= sscanf(ptr_new
, "%u%n", &frac
, &n_chars
)) {
580 /* normalize frac to nanoseconds */
581 if ((frac
>= 1000000000) || (frac
== 0)) {
584 switch (n_chars
) { /* including leading zeros */
585 case 1: frac
*= 100000000; break;
586 case 2: frac
*= 10000000; break;
587 case 3: frac
*= 1000000; break;
588 case 4: frac
*= 100000; break;
589 case 5: frac
*= 10000; break;
590 case 6: frac
*= 1000; break;
591 case 7: frac
*= 100; break;
592 case 8: frac
*= 10; break;
598 /* If we didn't get frac, it's still its default of 0 */
603 nstime
->nsecs
= frac
;
607 size_t nstime_to_iso8601(char *buf
, size_t buf_size
, const nstime_t
*nstime
)
617 * Do not use gmtime_s(), as it will call and
618 * exception handler if the time we're providing
619 * is < 0, and that will, by default, exit.
620 * ("Programmers not bothering to check return
621 * values? Try new Microsoft Visual Studio,
622 * with Parameter Validation(R)! Kill insufficiently
623 * careful programs - *and* the processes running them -
626 * We just want to report this as an unrepresentable
627 * time. It fills in a per-thread structure, which
628 * is sufficiently thread-safe for our purposes.
630 tm
= gmtime(&nstime
->secs
);
633 * Use gmtime_r(), because the Single UNIX Specification
634 * does *not* guarantee that gmtime() is thread-safe.
635 * Perhaps it is on all platforms on which we run, but
636 * this way we don't have to check.
638 tm
= gmtime_r(&nstime
->secs
, &tm_time
);
644 /* Some platforms (MinGW-w64) do not support %F or %T. */
645 /* Returns number of bytes, excluding terminaning null, placed in
646 * buf, or zero if there is not enough space for the whole string. */
647 len
= strftime(buf
, buf_size
, "%Y-%m-%dT%H:%M:%S", tm
);
651 ws_assert(len
< buf_size
);
654 len
+= snprintf(buf
, buf_size
, ".%09dZ", nstime
->nsecs
);
658 void nstime_to_unix(char *buf
, size_t buf_size
, const nstime_t
*nstime
)
660 display_signed_time(buf
, buf_size
, nstime
, WS_TSPREC_NSEC
);
669 * indent-tabs-mode: nil
672 * ex: set shiftwidth=4 tabstop=8 expandtab:
673 * :indentSize=4:tabSize=8:noTabs=true: