1 /*
2  * Copyright (c) 2014-2020 by Farsight Security, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *    http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define _GNU_SOURCE
18 #define _BSD_SOURCE
19 #define _DEFAULT_SOURCE
20 
21 #include <sys/types.h>
22 #include <inttypes.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <time.h>
26 
27 #include "defs.h"
28 #include "time.h"
29 #include "globals.h"
30 #include "ns_ttl.h"
31 
32 /* time_cmp -- compare two absolute timestamps, give -1, 0, or 1.
33  */
34 int
time_cmp(u_long a,u_long b)35 time_cmp(u_long a, u_long b) {
36 	if (a < b)
37 		return -1;
38 	if (a > b)
39 		return 1;
40 	return 0;
41 }
42 
43 /* time_str -- format one (possibly zero) timestamp (returns static string)
44  */
45 const char *
time_str(u_long x,bool iso8601fmt)46 time_str(u_long x, bool iso8601fmt) {
47 	static char ret[sizeof "yyyy-mm-ddThh:mm:ssZ"];
48 
49 	if (x == 0) {
50 		strcpy(ret, "0");
51 	} else {
52 		time_t t = (time_t)x;
53 		struct tm result, *y = gmtime_r(&t, &result);
54 
55 		strftime(ret, sizeof ret, iso8601fmt ? "%FT%TZ" : "%F %T", y);
56 	}
57 	return ret;
58 }
59 
60 /* time_get -- parse and return one (possibly relative) timestamp.
61  */
62 int
time_get(const char * src,u_long * dst)63 time_get(const char *src, u_long *dst) {
64 	struct tm tt;
65 	long long ll;
66 	u_long t;
67 	char *ep;
68 
69 	memset(&tt, 0, sizeof tt);
70 	if (((ep = strptime(src, "%F %T", &tt)) != NULL && *ep == '\0') ||
71 	    ((ep = strptime(src, "%F", &tt)) != NULL && *ep == '\0'))
72 	{
73 		*dst = (u_long)(timegm(&tt));
74 		return 1;
75 	}
76 	ll = strtoll(src, &ep, 10);
77 	if (*src != '\0' && *ep == '\0') {
78 		if (ll < 0)
79 			*dst = (u_long)startup_time.tv_sec -
80 				(u_long)imaxabs(ll);
81 		else
82 			*dst = (u_long)ll;
83 		return 1;
84 	}
85 	if (ns_parse_ttl(src, &t) == 0) {
86 		*dst = (u_long)startup_time.tv_sec - t;
87 		return 1;
88 	}
89 	return 0;
90 }
91 
92