xref: /openbsd/usr.bin/dig/lib/dns/dns_time.c (revision 3ec2dc6f)
1 /*
2  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
9  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
10  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
11  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
13  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14  * PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 /* $Id: dns_time.c,v 1.7 2020/04/02 16:57:45 florian Exp $ */
18 
19 /*! \file */
20 
21 #include <stdio.h>
22 #include <string.h>
23 #include <time.h>
24 
25 #include <isc/region.h>
26 #include <isc/serial.h>
27 #include <isc/result.h>
28 
29 #include <dns/time.h>
30 
31 static isc_result_t
dns_time64_totext(time_t t,isc_buffer_t * target)32 dns_time64_totext(time_t t, isc_buffer_t *target) {
33 	struct tm *tm;
34 	char buf[sizeof("YYYYMMDDHHMMSS")];
35 	size_t l;
36 	isc_region_t region;
37 
38 	tm = gmtime(&t);
39 	if ((l = strftime(buf, sizeof(buf), "%Y%m%d%H%M%S", tm)) == 0)
40 		return (ISC_R_NOSPACE);
41 
42 	isc_buffer_availableregion(target, &region);
43 
44 	if (l > region.length)
45 		return (ISC_R_NOSPACE);
46 
47 	memmove(region.base, buf, l);
48 	isc_buffer_add(target, l);
49 	return (ISC_R_SUCCESS);
50 }
51 
52 static time_t
dns_time64_from32(uint32_t value)53 dns_time64_from32(uint32_t value) {
54 	uint32_t now32;
55 	time_t start;
56 	time_t t;
57 
58 	time(&start);
59 	now32 = (uint32_t) start;
60 
61 	/* Adjust the time to the closest epoch. */
62 	if (isc_serial_gt(value, now32))
63 		t = start + (value - now32);
64 	else
65 		t = start - (now32 - value);
66 
67 	return (t);
68 }
69 
70 isc_result_t
dns_time32_totext(uint32_t value,isc_buffer_t * target)71 dns_time32_totext(uint32_t value, isc_buffer_t *target) {
72 	return (dns_time64_totext(dns_time64_from32(value), target));
73 }
74