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