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