1/* $NetBSD: stdtime.c,v 1.2 2024/02/21 22:52:29 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/time.h> 27#include <isc/util.h> 28 29#if defined(CLOCK_REALTIME_COARSE) 30#define CLOCKSOURCE CLOCK_REALTIME_COARSE 31#elif defined(CLOCK_REALTIME_FAST) 32#define CLOCKSOURCE CLOCK_REALTIME_FAST 33#else /* if defined(CLOCK_REALTIME_COARSE) */ 34#define CLOCKSOURCE CLOCK_REALTIME 35#endif /* if defined(CLOCK_REALTIME_COARSE) */ 36 37void 38isc_stdtime_get(isc_stdtime_t *t) { 39 REQUIRE(t != NULL); 40 41 struct timespec ts; 42 43 if (clock_gettime(CLOCKSOURCE, &ts) == -1) { 44 FATAL_SYSERROR(errno, "clock_gettime()"); 45 } 46 47 REQUIRE(ts.tv_sec > 0 && ts.tv_nsec >= 0 && ts.tv_nsec < NS_PER_SEC); 48 49 *t = (isc_stdtime_t)ts.tv_sec; 50} 51 52void 53isc_stdtime_tostring(isc_stdtime_t t, char *out, size_t outlen) { 54 time_t when; 55 56 REQUIRE(out != NULL); 57 REQUIRE(outlen >= 26); 58 59 UNUSED(outlen); 60 61 /* time_t and isc_stdtime_t might be different sizes */ 62 when = t; 63 INSIST((ctime_r(&when, out) != NULL)); 64 *(out + strlen(out) - 1) = '\0'; 65} 66