summaryrefslogtreecommitdiffstats
path: root/epan/ftypes/ftype-time.c
blob: 568f9e009ecc422a6f1d76b91f61e1ccd73172c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
/*
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 2001 Gerald Combs
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#define _GNU_SOURCE
#include "config.h"
#include "ftypes-int.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <epan/to_str.h>
#include <wsutil/time_util.h>
#include <wsutil/ws_strptime.h>
#include <wsutil/safe-math.h>


static enum ft_result
cmp_order(const fvalue_t *a, const fvalue_t *b, int *cmp)
{
	*cmp = nstime_cmp(&(a->value.time), &(b->value.time));
	return FT_OK;
}

/*
 * Get a nanoseconds value, starting at "p".
 *
 * Returns true on success, false on failure.
 *
 * If successful endptr points to the first invalid character.
 */
static bool
get_nsecs(const char *startp, int *nsecs, const char **endptr)
{
	int ndigits = 0;
	int scale;
	const char *p;
	int val;
	int digit;
	int i;

	/*
	 * How many digits are in the string?
	 */
	for (p = startp; g_ascii_isdigit(*p); p++)
		ndigits++;

	/*
	 * If there are N characters in the string, the last of the
	 * characters would be the digit corresponding to 10^(9-N)
	 * nanoseconds.
	 */
	scale = 9 - ndigits;

	/*
	 * Start at the last character, and work backwards.
	 */
	val = 0;
	while (p != startp) {
		p--;

		if (!g_ascii_isdigit(*p)) {
			/*
			 * Not a digit - error.
			 */
			return false;
		}
		digit = *p - '0';
		if (digit != 0) {
			/*
			 * Non-zero digit corresponding to that number
			 * of (10^scale) units.
			 *
			 * If scale is less than zero, this digit corresponds
			 * to a value less than a nanosecond, so this number
			 * isn't valid.
			 */
			if (scale < 0)
				return false;
			for (i = 0; i < scale; i++)
				digit *= 10;
			val += digit;
		}
		scale++;
	}
	*nsecs = val;
	if (endptr)
		*endptr = startp + ndigits;
	return true;
}

static bool
val_from_unix_time(fvalue_t *fv, const char *s)
{
	const char    *curptr;
	char *endptr;
	bool negative = false;

	curptr = s;

	if (*curptr == '-') {
		negative = true;
		curptr++;
	}

	/*
	 * If it doesn't begin with ".", it should contain a seconds
	 * value.
	 */
	if (*curptr != '.') {
		/*
		 * Get the seconds value.
		 */
		fv->value.time.secs = strtoul(curptr, &endptr, 10);
		if (endptr == curptr || (*endptr != '\0' && *endptr != '.'))
			return false;
		curptr = endptr;
		if (*curptr == '.')
			curptr++;	/* skip the decimal point */
	} else {
		/*
		 * No seconds value - it's 0.
		 */
		fv->value.time.secs = 0;
		curptr++;		/* skip the decimal point */
	}

	/*
	 * If there's more stuff left in the string, it should be the
	 * nanoseconds value.
	 */
	if (*curptr != '\0') {
		/*
		 * Get the nanoseconds value.
		 */
		if (!get_nsecs(curptr, &fv->value.time.nsecs, NULL))
			return false;
	} else {
		/*
		 * No nanoseconds value - it's 0.
		 */
		fv->value.time.nsecs = 0;
	}

	if (negative) {
		fv->value.time.secs = -fv->value.time.secs;
		fv->value.time.nsecs = -fv->value.time.nsecs;
	}
	return true;
}

static bool
relative_val_from_literal(fvalue_t *fv, const char *s, bool allow_partial_value _U_, char **err_msg)
{
	if (val_from_unix_time(fv, s))
		return true;

	if (err_msg != NULL)
		*err_msg = ws_strdup_printf("\"%s\" is not a valid time.", s);
	return false;
}

/*
 * Parses an absolute time value from a string. The string can have
 * a UTC time zone suffix. In that case it is interpreted in UTC. Otherwise
 * it is interpreted in local time.
 *
 * OS-dependent; e.g., on 32 bit versions of Windows when compiled to use
 * _mktime32 treats dates before January 1, 1970 as invalid.
 * (https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/mktime-mktime32-mktime64)
 */

/*
 * Timezone support:
 *
     %z    an ISO 8601, RFC-2822, or RFC-3339 time zone specification.  (A
           NetBSD extension.)  This is one of the following:
                 -   The offset from Coordinated Universal Time (`UTC') speci-
                     fied as:
                           ·   [+-]hhmm
                           ·   [+-]hh:mm
                           ·   [+-]hh
                 -   `UTC' specified as:
                           ·   UTC (`Coordinated Universal Time')
                           ·   GMT (`Greenwich Mean Time')
                           ·   UT (`Universal Time')
                           ·   Z (`Zulu Time')
                 -   A three character US time zone specified as:
                           ·   EDT
                           ·   EST
                           ·   CDT
                           ·   CST
                           ·   MDT
                           ·   MST
                           ·   PDT
                           ·   PST
                     with the first letter standing for `Eastern' (``E''),
                     `Central' (``C''), `Mountain' (``M'') or `Pacific'
                     (``P''), and the second letter standing for `Daylight'
                     (``D'' or summer) time or `Standard' (``S'') time
                 -   a single letter military or nautical time zone specified
                     as:
                           ·   ``A'' through ``I''
                           ·   ``K'' through ``Y''
                           ·   ``J'' (non-nautical local time zone)

     %Z    time zone name or no characters when time zone information is
           unavailable.  (A NetBSD extension.)
*/

/*
 * POSIX and C11 calendar time APIs are limited, poorly documented and have
 * loads of bagage and surprising behavior and quirks (most stemming from
 * the fact that the struct tm argument is sometimes both input and output).
 * See the following reference for a reliable method of handling arbitrary timezones:
 *    C: Converting struct tm times with timezone to time_t
 *    http://kbyanc.blogspot.com/2007/06/c-converting-struct-tm-times-with.html
 * Relevant excerpt:
 *    "However, if your libc implements both tm_gmtoff and timegm(3) you are
 *    in luck. You just need to use timegm(3) to get the time_t representing
 *    the time in GMT and then subtract the offset stored in tm_gmtoff.
 *    The tricky part is that calling timegm(3) will modify the struct tm,
 *    clearing the tm_gmtoff field to zero."
 */

#define EXAMPLE "Example: \"Nov 12, 1999 08:55:44.123\" or \"2011-07-04 12:34:56\""

static bool
absolute_val_from_string(fvalue_t *fv, const char *s, size_t len _U_, char **err_msg_ptr)
{
	struct tm tm;
	const char *bufptr, *curptr = NULL;
	const char *endptr;
	bool has_seconds = true;
	bool has_timezone = true;
	char *err_msg = NULL;
	struct ws_timezone zoneinfo = { 0, NULL };

	/* Try Unix time first. */
	if (val_from_unix_time(fv, s))
		return true;

	/* Try ISO 8601 format. */
	endptr = iso8601_to_nstime(&fv->value.time, s, ISO8601_DATETIME);
	/* Check whether it parsed all of the string */
	if (endptr != NULL && *endptr == '\0')
		return true;

	/* No - try other legacy formats. */
	memset(&tm, 0, sizeof(tm));
	/* Let the computer figure out if it's DST. */
	tm.tm_isdst = -1;

	/* Parse the date. ws_strptime() always uses the "C" locale. */
	bufptr = s;
	curptr = ws_strptime(bufptr, "%b %d, %Y", &tm, &zoneinfo);
	if (curptr == NULL)
		curptr = ws_strptime(bufptr,"%Y-%m-%d", &tm, &zoneinfo);
	if (curptr == NULL)
		goto fail;

	/* Parse the time, it is optional. */
	bufptr = curptr;
	curptr = ws_strptime(bufptr, " %H:%M:%S", &tm, &zoneinfo);
	if (curptr == NULL) {
		has_seconds = false;
		/* Seconds can be omitted but minutes (and hours) are required
		 * for a valid time value. */
		curptr = ws_strptime(bufptr," %H:%M", &tm, &zoneinfo);
	}
	if (curptr == NULL)
		curptr = bufptr;

	if (*curptr == '.') {
		/* Nanoseconds */
		if (!has_seconds) {
			err_msg = ws_strdup("Subsecond precision requires a seconds field.");
			goto fail;	/* Requires seconds */
		}
		curptr++;	/* skip the "." */
		if (!g_ascii_isdigit((unsigned char)*curptr)) {
			/* not a digit, so not valid */
			err_msg = ws_strdup("Subseconds value is not a number.");
			goto fail;
		}
		if (!get_nsecs(curptr, &fv->value.time.nsecs, &endptr)) {
			err_msg = ws_strdup("Subseconds value is invalid.");
			goto fail;
		}
		curptr = endptr;
	}
	else {
		/*
		 * No nanoseconds value - it's 0.
		 */
		fv->value.time.nsecs = 0;
	}

	/* Timezone */
	bufptr = curptr;
	curptr = ws_strptime(bufptr, "%n%z", &tm, &zoneinfo);
	if (curptr == NULL) {
		/* No timezone, assume localtime. */
		has_timezone = false;
		curptr = bufptr;
	}

	/* Skip whitespace */
	while (g_ascii_isspace(*curptr)) {
		curptr++;
	}

	if (*curptr != '\0') {
		err_msg = ws_strdup("Unexpected data after time value.");
		goto fail;
	}

	if (has_timezone) {
		/* Convert our calendar time (presumed in UTC, possibly with
		 * an extra timezone offset correction datum) to epoch time. */
		fv->value.time.secs = mktime_utc(&tm);
	}
	else {
		/* Convert our calendar time (in the local timezone) to epoch time. */
		fv->value.time.secs = mktime(&tm);
	}
	if (fv->value.time.secs == (time_t)-1) {
		/*
		 * XXX - should we supply an error message that mentions
		 * that the time specified might be syntactically valid
		 * but might not actually have occurred, e.g. a time in
		 * the non-existent time range after the clocks are
		 * set forward during daylight savings time (or possibly
		 * that it's in the time range after the clocks are set
		 * backward, so that there are two different times that
		 * it could be)?
		 */
		err_msg = ws_strdup_printf("\"%s\" cannot be converted to a valid calendar time.", s);
		goto fail;
	}

	if (has_timezone) {
		/* Normalize to UTC with the offset we have saved. */
		fv->value.time.secs -= zoneinfo.tm_gmtoff;
	}

	return true;

fail:
	if (err_msg_ptr != NULL) {
		if (err_msg == NULL) {
			*err_msg_ptr = ws_strdup_printf("\"%s\" is not a valid absolute time. " EXAMPLE, s);
		}
		else {
			*err_msg_ptr = err_msg;
		}
	}
	else {
		g_free(err_msg);
	}

	return false;
}

static bool
absolute_val_from_literal(fvalue_t *fv, const char *s, bool allow_partial_value _U_, char **err_msg)
{
	return absolute_val_from_string(fv, s, 0, err_msg);
}

static void
time_fvalue_new(fvalue_t *fv)
{
	fv->value.time.secs = 0;
	fv->value.time.nsecs = 0;
}

static void
time_fvalue_copy(fvalue_t *dst, const fvalue_t *src)
{
	nstime_copy(&dst->value.time, &src->value.time);
}

static void
time_fvalue_set(fvalue_t *fv, const nstime_t *value)
{
	fv->value.time = *value;
}

static const nstime_t *
value_get(fvalue_t *fv)
{
	return &(fv->value.time);
}

static char *
abs_time_to_ftrepr_dfilter(wmem_allocator_t *scope,
			const nstime_t *nstime, bool use_utc)
{
	struct tm *tm;
	char datetime_format[128];
	char nsecs_buf[32];

	if (use_utc) {
		tm = gmtime(&nstime->secs);
		if (tm != NULL)
			strftime(datetime_format, sizeof(datetime_format), "\"%Y-%m-%d %H:%M:%S%%sZ\"", tm);
		else
			snprintf(datetime_format, sizeof(datetime_format), "Not representable");
	}
	else {
		tm = localtime(&nstime->secs);
		/* Displaying the timezone could be made into a preference. */
		if (tm != NULL)
			strftime(datetime_format, sizeof(datetime_format), "\"%Y-%m-%d %H:%M:%S%%s%z\"", tm);
		else
			snprintf(datetime_format, sizeof(datetime_format), "Not representable");
	}

	if (nstime->nsecs == 0)
		return wmem_strdup_printf(scope, datetime_format, "");

	snprintf(nsecs_buf, sizeof(nsecs_buf), ".%09d", nstime->nsecs);

	return wmem_strdup_printf(scope, datetime_format, nsecs_buf);
}

static char *
absolute_val_to_repr(wmem_allocator_t *scope, const fvalue_t *fv, ftrepr_t rtype, int field_display)
{
	char *rep;

	if (field_display == BASE_NONE)
		field_display = ABSOLUTE_TIME_LOCAL;

	switch (rtype) {
		case FTREPR_DISPLAY:
		case FTREPR_JSON:
			rep = abs_time_to_str_ex(scope, &fv->value.time,
					field_display, ABS_TIME_TO_STR_SHOW_ZONE);
			break;

		case FTREPR_DFILTER:
			if (field_display == ABSOLUTE_TIME_UNIX) {
				rep = abs_time_to_unix_str(scope, &fv->value.time);
			}
			else {
				/* Only ABSOLUTE_TIME_LOCAL and ABSOLUTE_TIME_UTC
				 * are supported. Normalize the field_display value. */
				if (field_display != ABSOLUTE_TIME_LOCAL)
					field_display = ABSOLUTE_TIME_UTC;
				rep = abs_time_to_ftrepr_dfilter(scope, &fv->value.time, field_display != ABSOLUTE_TIME_LOCAL);
			}
			break;

		default:
			ws_assert_not_reached();
			break;
	}

	return rep;
}

static char *
relative_val_to_repr(wmem_allocator_t *scope, const fvalue_t *fv, ftrepr_t rtype _U_, int field_display _U_)
{
	return rel_time_to_secs_str(scope, &fv->value.time);
}

static unsigned
time_hash(const fvalue_t *fv)
{
	return nstime_hash(&fv->value.time);
}

static bool
time_is_zero(const fvalue_t *fv)
{
	return nstime_is_zero(&fv->value.time);
}

static bool
time_is_negative(const fvalue_t *fv)
{
	return fv->value.time.secs < 0;
}

static enum ft_result
time_unary_minus(fvalue_t * dst, const fvalue_t *src, char **err_ptr _U_)
{
	dst->value.time.secs = -src->value.time.secs;
	dst->value.time.nsecs = -src->value.time.nsecs;
	return FT_OK;
}

#define NS_PER_S 1000000000

static void
check_ns_wraparound(nstime_t *ns, jmp_buf env)
{
	if (ns->nsecs >= NS_PER_S || (ns->nsecs > 0 && ns->secs < 0)) {
		ws_safe_sub_jmp(&ns->nsecs, ns->nsecs, NS_PER_S, env);
		ws_safe_add_jmp(&ns->secs, ns->secs, 1, env);
	}
	else if(ns->nsecs <= -NS_PER_S || (ns->nsecs < 0 && ns->secs > 0)) {
		ws_safe_add_jmp(&ns->nsecs, ns->nsecs, NS_PER_S, env);
		ws_safe_sub_jmp(&ns->secs, ns->secs, 1, env);
	}
}

static void
_nstime_add(nstime_t *res, nstime_t a, const nstime_t b, jmp_buf env)
{
	ws_safe_add_jmp(&res->secs, a.secs, b.secs, env);
	ws_safe_add_jmp(&res->nsecs, a.nsecs, b.nsecs, env);
	check_ns_wraparound(res, env);
}

static void
_nstime_sub(nstime_t *res, nstime_t a, const nstime_t b, jmp_buf env)
{
	ws_safe_sub_jmp(&res->secs, a.secs, b.secs, env);
	ws_safe_sub_jmp(&res->nsecs, a.nsecs, b.nsecs, env);
	check_ns_wraparound(res, env);
}

static enum ft_result
time_add(fvalue_t * dst, const fvalue_t *a, const fvalue_t *b, char **err_ptr)
{
	jmp_buf env;
	if (setjmp(env) != 0) {
		*err_ptr = ws_strdup_printf("time_add: overflow");
		return FT_ERROR;
	}
	_nstime_add(&dst->value.time, a->value.time, b->value.time, env);
	return FT_OK;
}

static enum ft_result
time_subtract(fvalue_t * dst, const fvalue_t *a, const fvalue_t *b, char **err_ptr)
{
	jmp_buf env;
	if (setjmp(env) != 0) {
		*err_ptr = ws_strdup_printf("time_subtract: overflow");
		return FT_ERROR;
	}
	_nstime_sub(&dst->value.time, a->value.time, b->value.time, env);
	return FT_OK;
}

void
ftype_register_time(void)
{

	static ftype_t abstime_type = {
		FT_ABSOLUTE_TIME,		/* ftype */
		"FT_ABSOLUTE_TIME",		/* name */
		"Date and time",		/* pretty_name */
		0,				/* wire_size */
		time_fvalue_new,		/* new_value */
		time_fvalue_copy,		/* copy_value */
		NULL,				/* free_value */
		absolute_val_from_literal,	/* val_from_literal */
		absolute_val_from_string,	/* val_from_string */
		NULL,				/* val_from_charconst */
		absolute_val_to_repr,		/* val_to_string_repr */

		NULL,				/* val_to_uinteger64 */
		NULL,				/* val_to_sinteger64 */

		{ .set_value_time = time_fvalue_set },	/* union set_value */
		{ .get_value_time = value_get },	/* union get_value */

		cmp_order,
		NULL,				/* cmp_contains */
		NULL,				/* cmp_matches */

		time_hash,			/* hash */
		time_is_zero,			/* is_zero */
		time_is_negative,		/* is_negative */
		NULL,
		NULL,
		NULL,				/* bitwise_and */
		time_unary_minus,		/* unary_minus */
		time_add,			/* add */
		time_subtract,			/* subtract */
		NULL,				/* multiply */
		NULL,				/* divide */
		NULL,				/* modulo */
	};
	static ftype_t reltime_type = {
		FT_RELATIVE_TIME,		/* ftype */
		"FT_RELATIVE_TIME",		/* name */
		"Time offset",			/* pretty_name */
		0,				/* wire_size */
		time_fvalue_new,		/* new_value */
		time_fvalue_copy,		/* copy_value */
		NULL,				/* free_value */
		relative_val_from_literal,	/* val_from_literal */
		NULL,				/* val_from_string */
		NULL,				/* val_from_charconst */
		relative_val_to_repr,		/* val_to_string_repr */

		NULL,				/* val_to_uinteger64 */
		NULL,				/* val_to_sinteger64 */

		{ .set_value_time = time_fvalue_set },	/* union set_value */
		{ .get_value_time = value_get },	/* union get_value */

		cmp_order,
		NULL,				/* cmp_contains */
		NULL,				/* cmp_matches */

		time_hash,			/* hash */
		time_is_zero,			/* is_zero */
		time_is_negative,		/* is_negative */
		NULL,
		NULL,
		NULL,				/* bitwise_and */
		time_unary_minus,		/* unary_minus */
		time_add,			/* add */
		time_subtract,			/* subtract */
		NULL,				/* multiply */
		NULL,				/* divide */
		NULL,				/* modulo */
	};

	ftype_register(FT_ABSOLUTE_TIME, &abstime_type);
	ftype_register(FT_RELATIVE_TIME, &reltime_type);
}

void
ftype_register_pseudofields_time(int proto)
{
	static int hf_ft_rel_time;
	static int hf_ft_abs_time;

	static hf_register_info hf_ftypes[] = {
		{ &hf_ft_abs_time,
		    { "FT_ABSOLUTE_TIME", "_ws.ftypes.abs_time",
			FT_ABSOLUTE_TIME, ABSOLUTE_TIME_UTC, NULL, 0x00,
			NULL, HFILL }
		},
		{ &hf_ft_rel_time,
		    { "FT_RELATIVE_TIME", "_ws.ftypes.rel_time",
			FT_RELATIVE_TIME, BASE_NONE, NULL, 0x00,
			NULL, HFILL }
		},
	};

	proto_register_field_array(proto, hf_ftypes, array_length(hf_ftypes));
}

/*
 * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
 *
 * Local variables:
 * c-basic-offset: 8
 * tab-width: 8
 * indent-tabs-mode: t
 * End:
 *
 * vi: set shiftwidth=8 tabstop=8 noexpandtab:
 * :indentSize=8:tabSize=8:noTabs=false:
 */