xref: /netbsd-src/external/mpl/bind/dist/lib/isc/stdtime.c (revision bcda20f65a8566e103791ec395f7f499ef322704)
1*bcda20f6Schristos /*	$NetBSD: stdtime.c,v 1.4 2025/01/26 16:25:38 christos Exp $	*/
28aaca124Schristos 
38aaca124Schristos /*
48aaca124Schristos  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
58aaca124Schristos  *
68aaca124Schristos  * SPDX-License-Identifier: MPL-2.0
78aaca124Schristos  *
88aaca124Schristos  * This Source Code Form is subject to the terms of the Mozilla Public
98aaca124Schristos  * License, v. 2.0. If a copy of the MPL was not distributed with this
108aaca124Schristos  * file, you can obtain one at https://mozilla.org/MPL/2.0/.
118aaca124Schristos  *
128aaca124Schristos  * See the COPYRIGHT file distributed with this work for additional
138aaca124Schristos  * information regarding copyright ownership.
148aaca124Schristos  */
158aaca124Schristos 
168aaca124Schristos /*! \file */
178aaca124Schristos 
188aaca124Schristos #include <errno.h>
198aaca124Schristos #include <stdbool.h>
208aaca124Schristos #include <stddef.h> /* NULL */
218aaca124Schristos #include <stdlib.h> /* NULL */
228aaca124Schristos #include <syslog.h>
238aaca124Schristos #include <time.h>
248aaca124Schristos 
258aaca124Schristos #include <isc/stdtime.h>
26*bcda20f6Schristos #include <isc/strerr.h>
278aaca124Schristos #include <isc/time.h>
288aaca124Schristos #include <isc/util.h>
298aaca124Schristos 
308aaca124Schristos #if defined(CLOCK_REALTIME_COARSE)
318aaca124Schristos #define CLOCKSOURCE CLOCK_REALTIME_COARSE
328aaca124Schristos #elif defined(CLOCK_REALTIME_FAST)
338aaca124Schristos #define CLOCKSOURCE CLOCK_REALTIME_FAST
348aaca124Schristos #else /* if defined(CLOCK_REALTIME_COARSE) */
358aaca124Schristos #define CLOCKSOURCE CLOCK_REALTIME
368aaca124Schristos #endif /* if defined(CLOCK_REALTIME_COARSE) */
378aaca124Schristos 
38*bcda20f6Schristos isc_stdtime_t
39*bcda20f6Schristos isc_stdtime_now(void) {
408aaca124Schristos 	struct timespec ts;
418aaca124Schristos 
428aaca124Schristos 	if (clock_gettime(CLOCKSOURCE, &ts) == -1) {
438aaca124Schristos 		FATAL_SYSERROR(errno, "clock_gettime()");
448aaca124Schristos 	}
45*bcda20f6Schristos 	INSIST(ts.tv_sec > 0 && ts.tv_nsec >= 0 &&
46dff692fcSchristos 	       ts.tv_nsec < (long)NS_PER_SEC);
478aaca124Schristos 
48*bcda20f6Schristos 	return (isc_stdtime_t)ts.tv_sec;
498aaca124Schristos }
508aaca124Schristos 
518aaca124Schristos void
528aaca124Schristos isc_stdtime_tostring(isc_stdtime_t t, char *out, size_t outlen) {
538aaca124Schristos 	time_t when;
548aaca124Schristos 
558aaca124Schristos 	REQUIRE(out != NULL);
568aaca124Schristos 	REQUIRE(outlen >= 26);
578aaca124Schristos 
588aaca124Schristos 	/* time_t and isc_stdtime_t might be different sizes */
598aaca124Schristos 	when = t;
60*bcda20f6Schristos 	INSIST(ctime_r(&when, out) != NULL);
618aaca124Schristos 	*(out + strlen(out) - 1) = '\0';
628aaca124Schristos }
63