1/* $NetBSD: stdtime.c,v 1.2.6.1 2012/06/05 21:15:23 bouyer Exp $ */ 2 3/* 4 * Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC") 5 * Copyright (C) 1999-2001 Internet Software Consortium. 6 * 7 * Permission to use, copy, modify, and/or distribute this software for any 8 * purpose with or without fee is hereby granted, provided that the above 9 * copyright notice and this permission notice appear in all copies. 10 * 11 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH 12 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY 13 * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, 14 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 15 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE 16 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR 17 * PERFORMANCE OF THIS SOFTWARE. 18 */ 19 20/* Id: stdtime.c,v 1.19 2007/06/19 23:47:18 tbox Exp */ 21 22/*! \file */ 23 24#include <config.h> 25 26#include <stddef.h> /* NULL */ 27#include <stdlib.h> /* NULL */ 28#include <syslog.h> 29 30#include <sys/time.h> 31 32#include <isc/stdtime.h> 33#include <isc/util.h> 34 35#ifndef ISC_FIX_TV_USEC 36#define ISC_FIX_TV_USEC 1 37#endif 38 39#define US_PER_S 1000000 40 41#if ISC_FIX_TV_USEC 42static inline void 43fix_tv_usec(struct timeval *tv) { 44 isc_boolean_t fixed = ISC_FALSE; 45 46 if (tv->tv_usec < 0) { 47 fixed = ISC_TRUE; 48 do { 49 tv->tv_sec -= 1; 50 tv->tv_usec += US_PER_S; 51 } while (tv->tv_usec < 0); 52 } else if (tv->tv_usec >= US_PER_S) { 53 fixed = ISC_TRUE; 54 do { 55 tv->tv_sec += 1; 56 tv->tv_usec -= US_PER_S; 57 } while (tv->tv_usec >=US_PER_S); 58 } 59 /* 60 * Call syslog directly as we are called from the logging functions. 61 */ 62 if (fixed) 63 (void)syslog(LOG_ERR, "gettimeofday returned bad tv_usec: corrected"); 64} 65#endif 66 67void 68isc_stdtime_get(isc_stdtime_t *t) { 69 struct timeval tv; 70 71 /* 72 * Set 't' to the number of seconds since 00:00:00 UTC, January 1, 73 * 1970. 74 */ 75 76 REQUIRE(t != NULL); 77 78 RUNTIME_CHECK(gettimeofday(&tv, NULL) != -1); 79 80#if ISC_FIX_TV_USEC 81 fix_tv_usec(&tv); 82 INSIST(tv.tv_usec >= 0); 83#else 84 INSIST(tv.tv_usec >= 0 && tv.tv_usec < US_PER_S); 85#endif 86 87 *t = (unsigned int)tv.tv_sec; 88} 89