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 "pdns.h"
29 #include "time.h"
30 #include "globals.h"
31 #include "ns_ttl.h"
32 
33 /* time_cmp -- compare two absolute timestamps, give -1, 0, or 1.
34  */
35 int
time_cmp(u_long a,u_long b)36 time_cmp(u_long a, u_long b) {
37 	if (a < b)
38 		return (-1);
39 	if (a > b)
40 		return (1);
41 	return (0);
42 }
43 
44 /* time_str -- format one (possibly relative) timestamp (returns static string)
45  */
46 const char *
time_str(u_long x)47 time_str(u_long x) {
48 	static char ret[sizeof "yyyy-mm-ddThh:mm:ssZ"];
49 
50 	if (x == 0) {
51 		strcpy(ret, "0");
52 	} else {
53 		time_t t = (time_t)x;
54 		struct tm result, *y = gmtime_r(&t, &result);
55 
56 		strftime(ret, sizeof ret, "%F %T", y);
57 	}
58 	return ret;
59 }
60 
61 /* time_get -- parse and return one (possibly relative) timestamp.
62  */
63 int
time_get(const char * src,u_long * dst)64 time_get(const char *src, u_long *dst) {
65 	struct tm tt;
66 	long long ll;
67 	u_long t;
68 	char *ep;
69 
70 	memset(&tt, 0, sizeof tt);
71 	if (((ep = strptime(src, "%F %T", &tt)) != NULL && *ep == '\0') ||
72 	    ((ep = strptime(src, "%F", &tt)) != NULL && *ep == '\0'))
73 	{
74 		*dst = (u_long)(timegm(&tt));
75 		return (1);
76 	}
77 	ll = strtoll(src, &ep, 10);
78 	if (*src != '\0' && *ep == '\0') {
79 		if (ll < 0)
80 			*dst = (u_long)startup_time.tv_sec -
81 				(u_long)imaxabs(ll);
82 		else
83 			*dst = (u_long)ll;
84 		return (1);
85 	}
86 	if (ns_parse_ttl(src, &t) == 0) {
87 		*dst = (u_long)startup_time.tv_sec - t;
88 		return (1);
89 	}
90 	return (0);
91 }
92 
93