update epan/dissectors/pidl/drsuapi/drsuapi.idl from samba
[wireshark-sm.git] / wsutil / nstime.c
blob70890afa7f453785cd62cf4b50271d3b8cf58e8d
1 /* nstime.c
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
13 #include "nstime.h"
15 #include <stdio.h>
16 #include <string.h>
17 #include "epochs.h"
18 #include "time_util.h"
19 #include "to_str.h"
20 #include "strtoi.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
24 changing ;) */
25 #define NS_PER_S 1000000000
27 /* set the given nstime_t to zero */
28 void nstime_set_zero(nstime_t *nstime)
30 nstime->secs = 0;
31 nstime->nsecs = 0;
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)
46 nstime->secs = 0;
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) {
54 return true;
55 } else {
56 return false;
61 /** function: nstime_copy
63 * a = b
65 void nstime_copy(nstime_t *a, const nstime_t *b)
67 a->secs = b->secs;
68 a->nsecs = b->nsecs;
72 * function: nstime_delta
73 * delta = b - a
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
85 can never result. */
86 delta->secs = 0;
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
90 before a.
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;
100 delta->secs ++;
102 } else {
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;
107 delta->secs --;
113 * function: nstime_sum
114 * sum = a + b
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;
123 sum->secs++;
124 } else if(sum->nsecs<=-NS_PER_S || (sum->nsecs<0 && sum->secs>0)) {
125 sum->nsecs+=NS_PER_S;
126 sum->secs--;
131 * function: nstime_cmp
133 * a > b : > 0
134 * a = b : 0
135 * a < b : < 0
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" */
143 } else {
144 return -1; /* and is less than all time stamps */
146 } else {
147 if (G_UNLIKELY(nstime_is_unset(b))) {
148 return 1;
151 if (a->secs == b->secs) {
152 return a->nsecs - b->nsecs;
153 } else {
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.
191 * Version 1.9.
192 * time handling functions
193 * Copyright (C) Andrew Tridgell 1992-1998
196 #ifndef TIME_T_MIN
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))))
199 #endif
200 #ifndef TIME_T_MAX
201 #define TIME_T_MAX ((time_t) (~ (time_t) 0 - TIME_T_MIN))
202 #endif
204 static bool
205 common_filetime_to_nstime(nstime_t *nstime, uint64_t ftsecs, int nsecs)
207 int64_t secs;
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 */
222 return false;
226 * Get the time as seconds and nanoseconds.
228 nstime->secs = (time_t) secs;
229 nstime->nsecs = nsecs;
230 return true;
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
238 * underflows time_t)
240 bool
241 filetime_to_nstime(nstime_t *nstime, uint64_t filetime)
243 uint64_t ftsecs;
244 int nsecs;
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
262 * underflows time_t)
264 bool
265 filetime_ns_to_nstime(nstime_t *nstime, uint64_t nsfiletime)
267 uint64_t ftsecs;
268 int nsecs;
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
283 * underflows time_t)
285 bool
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
324 const char *
325 iso8601_to_nstime(nstime_t *nstime, const char *ptr, iso8601_fmt_e format)
327 struct tm tm;
328 int n_scanned = 0;
329 int n_chars = 0;
330 unsigned frac = 0;
331 int off_hr = 0;
332 int off_min = 0;
333 char sign = '\0';
334 bool has_separator = false;
335 bool have_offset = false;
337 memset(&tm, 0, sizeof(tm));
338 tm.tm_isdst = -1;
339 nstime_set_unset(nstime);
341 /* Verify that we start with a four digit year and then look for the
342 * separator. */
343 for (n_scanned = 0; n_scanned < 4; n_scanned++) {
344 if (!g_ascii_isdigit(*ptr)) {
345 return NULL;
347 tm.tm_year *= 10;
348 tm.tm_year += *ptr++ - '0';
350 if (*ptr == '-') {
351 switch (format) {
352 case ISO8601_DATETIME_BASIC:
353 return NULL;
355 case ISO8601_DATETIME:
356 case ISO8601_DATETIME_AUTO:
357 default:
358 has_separator = true;
359 ptr++;
361 } else if (g_ascii_isdigit(*ptr)) {
362 switch (format) {
363 case ISO8601_DATETIME:
364 return NULL;
366 case ISO8601_DATETIME_BASIC:
367 case ISO8601_DATETIME_AUTO:
368 default:
369 has_separator = false;
371 } else {
372 return NULL;
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
380 use '<'/'>='
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",
389 &tm.tm_mon,
390 &tm.tm_mday,
391 &n_chars);
392 if (n_scanned >= 2) {
393 /* Got year, month, and day */
394 tm.tm_mon--; /* struct tm expects 0-based month */
395 ptr += n_chars;
397 else {
398 return NULL;
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. */
405 ptr++;
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.) */
411 return NULL;
414 /* Now we're on to the time part. We'll require a minimum of hours and
415 minutes. */
417 n_scanned = sscanf(ptr, has_separator ? "%2u:%2u%n" : "%2u%2u%n",
418 &tm.tm_hour,
419 &tm.tm_min,
420 &n_chars);
421 if (n_scanned >= 2) {
422 ptr += n_chars;
424 else {
425 /* didn't get hours and minutes */
426 return NULL;
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 */
436 return NULL;
438 ptr += n_chars;
440 /* Now let's test for fractional seconds */
441 if (*ptr == '.' || *ptr == ',') {
442 /* Get fractional seconds */
443 ptr++;
444 if (1 <= sscanf(ptr, "%u%n", &frac, &n_chars)) {
445 /* normalize frac to nanoseconds */
446 if ((frac >= 1000000000) || (frac == 0)) {
447 frac = 0;
448 } else {
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;
458 default: break;
461 ptr += n_chars;
463 /* If we didn't get frac, it's still its default of 0 */
466 else {
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.
470 tm.tm_sec = 0;
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)) {
476 return NULL;
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
482 * some such. */
483 sign = *ptr;
484 /* We have a UTC-relative offset */
485 if (*ptr == 'Z') {
486 off_hr = off_min = 0;
487 have_offset = true;
488 ptr++;
490 else {
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 */
495 have_offset = true;
496 ptr += n_chars;
497 n_scanned = sscanf(ptr, *ptr == ':' ? ":%2d%n" : "%2d%n", &off_min, &n_chars);
498 if (n_scanned >= 1) {
499 /* Got minutes too */
500 ptr += n_chars;
503 else {
504 /* Didn't get a valid offset, treat as if there's none at all */
505 have_offset = false;
509 if (have_offset) {
510 nstime->secs = mktime_utc(&tm);
511 if (sign == '+') {
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
521 * the negative sign.
523 nstime->secs += ((-off_hr) * 3600) + (off_min * 60);
526 else {
527 /* No UTC offset given; ISO 8601 says this means local time */
528 nstime->secs = mktime(&tm);
530 nstime->nsecs = frac;
531 return ptr;
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
545 const char *
546 unix_epoch_to_nstime(nstime_t *nstime, const char *ptr)
548 int64_t secs;
549 const char *ptr_new;
551 int n_chars = 0;
552 unsigned frac = 0;
554 nstime_set_unset(nstime);
557 * Extract the seconds as a 64-bit signed number, as time_t
558 * might be 64-bit.
560 if (!ws_strtoi64(ptr, &ptr_new, &secs)) {
561 return NULL;
564 /* For now, reject times before the Epoch. */
565 if (secs < 0) {
566 return NULL;
569 /* Make sure it fits. */
570 nstime->secs = (time_t) secs;
571 if (nstime->secs != secs) {
572 return NULL;
575 /* Now let's test for fractional seconds */
576 if (*ptr_new == '.' || *ptr_new == ',') {
577 /* Get fractional seconds */
578 ptr_new++;
579 if (1 <= sscanf(ptr_new, "%u%n", &frac, &n_chars)) {
580 /* normalize frac to nanoseconds */
581 if ((frac >= 1000000000) || (frac == 0)) {
582 frac = 0;
583 } else {
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;
593 default: break;
596 ptr_new += n_chars;
598 /* If we didn't get frac, it's still its default of 0 */
600 else {
601 frac = 0;
603 nstime->nsecs = frac;
604 return ptr_new;
607 size_t nstime_to_iso8601(char *buf, size_t buf_size, const nstime_t *nstime)
609 struct tm *tm;
610 #ifndef _WIN32
611 struct tm tm_time;
612 #endif
613 size_t len;
615 #ifdef _WIN32
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 -
624 * fast!")
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);
631 #else
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);
639 #endif
640 if (tm == NULL) {
641 return 0;
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);
648 if (len == 0) {
649 return 0;
651 ws_assert(len < buf_size);
652 buf += len;
653 buf_size -= len;
654 len += snprintf(buf, buf_size, ".%09dZ", nstime->nsecs);
655 return len;
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);
664 * Editor modelines
666 * Local Variables:
667 * c-basic-offset: 4
668 * tab-width: 8
669 * indent-tabs-mode: nil
670 * End:
672 * ex: set shiftwidth=4 tabstop=8 expandtab:
673 * :indentSize=4:tabSize=8:noTabs=true: