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