1 /* $NetBSD: stdtime.c,v 1.1 2024/02/18 20:57:57 christos Exp $ */
2
3 /*
4 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
5 *
6 * SPDX-License-Identifier: MPL-2.0
7 *
8 * This Source Code Form is subject to the terms of the Mozilla Public
9 * License, v. 2.0. If a copy of the MPL was not distributed with this
10 * file, you can obtain one at https://mozilla.org/MPL/2.0/.
11 *
12 * See the COPYRIGHT file distributed with this work for additional
13 * information regarding copyright ownership.
14 */
15
16 /*! \file */
17
18 #include <errno.h>
19 #include <stdbool.h>
20 #include <stddef.h> /* NULL */
21 #include <stdlib.h> /* NULL */
22 #include <syslog.h>
23 #include <time.h>
24
25 #include <isc/stdtime.h>
26 #include <isc/strerr.h>
27 #include <isc/util.h>
28
29 #define NS_PER_S 1000000000 /*%< Nanoseconds per second. */
30
31 #if defined(CLOCK_REALTIME_COARSE)
32 #define CLOCKSOURCE CLOCK_REALTIME_COARSE
33 #elif defined(CLOCK_REALTIME_FAST)
34 #define CLOCKSOURCE CLOCK_REALTIME_FAST
35 #else /* if defined(CLOCK_REALTIME_COARSE) */
36 #define CLOCKSOURCE CLOCK_REALTIME
37 #endif /* if defined(CLOCK_REALTIME_COARSE) */
38
39 void
isc_stdtime_get(isc_stdtime_t * t)40 isc_stdtime_get(isc_stdtime_t *t) {
41 REQUIRE(t != NULL);
42
43 struct timespec ts;
44
45 if (clock_gettime(CLOCKSOURCE, &ts) == -1) {
46 char strbuf[ISC_STRERRORSIZE];
47 strerror_r(errno, strbuf, sizeof(strbuf));
48 isc_error_fatal(__FILE__, __LINE__, "clock_gettime failed: %s",
49 strbuf);
50 }
51
52 REQUIRE(ts.tv_sec > 0 && ts.tv_nsec >= 0 && ts.tv_nsec < NS_PER_S);
53
54 *t = (isc_stdtime_t)ts.tv_sec;
55 }
56
57 void
isc_stdtime_tostring(isc_stdtime_t t,char * out,size_t outlen)58 isc_stdtime_tostring(isc_stdtime_t t, char *out, size_t outlen) {
59 time_t when;
60
61 REQUIRE(out != NULL);
62 REQUIRE(outlen >= 26);
63
64 UNUSED(outlen);
65
66 /* time_t and isc_stdtime_t might be different sizes */
67 when = t;
68 INSIST((ctime_r(&when, out) != NULL));
69 *(out + strlen(out) - 1) = '\0';
70 }
71