xref: /freebsd/contrib/ntp/libntp/mktime.c (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
1 /*
2  * Copyright (c) 1987, 1989 Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Arthur David Olson of the National Cancer Institute.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.  */
35 
36 /*static char *sccsid = "from: @(#)ctime.c	5.26 (Berkeley) 2/23/91";*/
37 
38 /*
39  * This implementation of mktime is lifted straight from the NetBSD (BSD 4.4)
40  * version.  I modified it slightly to divorce it from the internals of the
41  * ctime library.  Thus this version can't use details of the internal
42  * timezone state file to figure out strange unnormalized struct tm values,
43  * as might result from someone doing date math on the tm struct then passing
44  * it to mktime.
45  *
46  * It just does as well as it can at normalizing the tm input, then does a
47  * binary search of the time space using the system's localtime() function.
48  *
49  * The original binary search was defective in that it didn't consider the
50  * setting of tm_isdst when comparing tm values, causing the search to be
51  * flubbed for times near the dst/standard time changeover.  The original
52  * code seems to make up for this by grubbing through the timezone info
53  * whenever the binary search barfed.  Since I don't have that luxury in
54  * portable code, I have to take care of tm_isdst in the comparison routine.
55  * This requires knowing how many minutes offset dst is from standard time.
56  *
57  * So, if you live somewhere in the world where dst is not 60 minutes offset,
58  * and your vendor doesn't supply mktime(), you'll have to edit this variable
59  * by hand.  Sorry about that.
60  */
61 
62 #include <config.h>
63 #include "ntp_types.h"
64 
65 #if !defined(HAVE_MKTIME) || ( !defined(HAVE_TIMEGM) && defined(WANT_TIMEGM) )
66 
67 #if SIZEOF_TIME_T >= 8
68 #error libntp supplied mktime()/timegm() do not support 64-bit time_t
69 #endif
70 
71 #ifndef DSTMINUTES
72 #define DSTMINUTES 60
73 #endif
74 
75 #define FALSE 0
76 #define TRUE 1
77 
78 /* some constants from tzfile.h */
79 #define SECSPERMIN      60
80 #define MINSPERHOUR     60
81 #define HOURSPERDAY     24
82 #define DAYSPERWEEK     7
83 #define DAYSPERNYEAR    365
84 #define DAYSPERLYEAR    366
85 #define SECSPERHOUR     (SECSPERMIN * MINSPERHOUR)
86 #define SECSPERDAY      ((long) SECSPERHOUR * HOURSPERDAY)
87 #define MONSPERYEAR     12
88 #define TM_YEAR_BASE    1900
89 #define isleap(y) ((((y) % 4) == 0 && ((y) % 100) != 0) || ((y) % 400) == 0)
90 
91 static int	mon_lengths[2][MONSPERYEAR] = {
92 	{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
93 	{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
94 };
95 
96 static int	year_lengths[2] = {
97 	DAYSPERNYEAR, DAYSPERLYEAR
98 };
99 
100 /*
101 ** Adapted from code provided by Robert Elz, who writes:
102 **	The "best" way to do mktime I think is based on an idea of Bob
103 **	Kridle's (so its said...) from a long time ago. (mtxinu!kridle now).
104 **	It does a binary search of the time_t space.  Since time_t's are
105 **	just 32 bits, its a max of 32 iterations (even at 64 bits it
106 **	would still be very reasonable).
107 */
108 
109 #ifndef WRONG
110 #define WRONG	(-1)
111 #endif /* !defined WRONG */
112 
113 static void
114 normalize(
115 	int * tensptr,
116 	int * unitsptr,
117 	int	base
118 	)
119 {
120 	if (*unitsptr >= base) {
121 		*tensptr += *unitsptr / base;
122 		*unitsptr %= base;
123 	} else if (*unitsptr < 0) {
124 		--*tensptr;
125 		*unitsptr += base;
126 		if (*unitsptr < 0) {
127 			*tensptr -= 1 + (-*unitsptr) / base;
128 			*unitsptr = base - (-*unitsptr) % base;
129 		}
130 	}
131 }
132 
133 static struct tm *
134 mkdst(
135 	struct tm *	tmp
136 	)
137 {
138     /* jds */
139     static struct tm tmbuf;
140 
141     tmbuf = *tmp;
142     tmbuf.tm_isdst = 1;
143     tmbuf.tm_min += DSTMINUTES;
144     normalize(&tmbuf.tm_hour, &tmbuf.tm_min, MINSPERHOUR);
145     return &tmbuf;
146 }
147 
148 static int
149 tmcomp(
150 	register struct tm * atmp,
151 	register struct tm * btmp
152 	)
153 {
154 	register int	result;
155 
156 	/* compare down to the same day */
157 
158 	if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
159 	    (result = (atmp->tm_mon - btmp->tm_mon)) == 0)
160 	    result = (atmp->tm_mday - btmp->tm_mday);
161 
162 	if(result != 0)
163 	    return result;
164 
165 	/* get rid of one-sided dst bias */
166 
167 	if(atmp->tm_isdst == 1 && !btmp->tm_isdst)
168 	    btmp = mkdst(btmp);
169 	else if(btmp->tm_isdst == 1 && !atmp->tm_isdst)
170 	    atmp = mkdst(atmp);
171 
172 	/* compare the rest of the way */
173 
174 	if ((result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
175 	    (result = (atmp->tm_min - btmp->tm_min)) == 0)
176 	    result = atmp->tm_sec - btmp->tm_sec;
177 	return result;
178 }
179 
180 
181 static time_t
182 time2(
183 	struct tm *	tmp,
184 	int * 		okayp,
185 	int		usezn
186 	)
187 {
188 	register int			dir;
189 	register int			bits;
190 	register int			i;
191 	register int			saved_seconds;
192 	time_t				t;
193 	struct tm			yourtm, mytm;
194 
195 	*okayp = FALSE;
196 	yourtm = *tmp;
197 	if (yourtm.tm_sec >= SECSPERMIN + 2 || yourtm.tm_sec < 0)
198 		normalize(&yourtm.tm_min, &yourtm.tm_sec, SECSPERMIN);
199 	normalize(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR);
200 	normalize(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY);
201 	normalize(&yourtm.tm_year, &yourtm.tm_mon, MONSPERYEAR);
202 	while (yourtm.tm_mday <= 0) {
203 		--yourtm.tm_year;
204 		yourtm.tm_mday +=
205 			year_lengths[isleap(yourtm.tm_year + TM_YEAR_BASE)];
206 	}
207 	for ( ; ; ) {
208 		i = mon_lengths[isleap(yourtm.tm_year +
209 			TM_YEAR_BASE)][yourtm.tm_mon];
210 		if (yourtm.tm_mday <= i)
211 			break;
212 		yourtm.tm_mday -= i;
213 		if (++yourtm.tm_mon >= MONSPERYEAR) {
214 			yourtm.tm_mon = 0;
215 			++yourtm.tm_year;
216 		}
217 	}
218 	saved_seconds = yourtm.tm_sec;
219 	yourtm.tm_sec = 0;
220 	/*
221 	** Calculate the number of magnitude bits in a time_t
222 	** (this works regardless of whether time_t is
223 	** signed or unsigned, though lint complains if unsigned).
224 	*/
225 	for (bits = 0, t = 1; t > 0; ++bits, t <<= 1)
226 		;
227 	/*
228 	** If time_t is signed, then 0 is the median value,
229 	** if time_t is unsigned, then 1 << bits is median.
230 	*/
231 	t = (t < 0) ? 0 : ((time_t) 1 << bits);
232 	for ( ; ; ) {
233 		if (usezn)
234 			mytm = *localtime(&t);
235 		else
236 			mytm = *gmtime(&t);
237 		dir = tmcomp(&mytm, &yourtm);
238 		if (dir != 0) {
239 			if (bits-- < 0)
240 				return WRONG;
241 			if (bits < 0)
242 				--t;
243 			else if (dir > 0)
244 				t -= (time_t) 1 << bits;
245 			else	t += (time_t) 1 << bits;
246 			continue;
247 		}
248 		if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
249 			break;
250 
251 		return WRONG;
252 	}
253 	t += saved_seconds;
254 	if (usezn)
255 		*tmp = *localtime(&t);
256 	else
257 		*tmp = *gmtime(&t);
258 	*okayp = TRUE;
259 	return t;
260 }
261 #else
262 NONEMPTY_TRANSLATION_UNIT
263 #endif /* !HAVE_MKTIME || !HAVE_TIMEGM */
264 
265 #ifndef HAVE_MKTIME
266 static time_t
267 time1(
268 	struct tm * tmp
269 	)
270 {
271 	register time_t			t;
272 	int				okay;
273 
274 	if (tmp->tm_isdst > 1)
275 		tmp->tm_isdst = 1;
276 	t = time2(tmp, &okay, 1);
277 	if (okay || tmp->tm_isdst < 0)
278 		return t;
279 
280 	return WRONG;
281 }
282 
283 time_t
284 mktime(
285 	struct tm * tmp
286 	)
287 {
288 	return time1(tmp);
289 }
290 #endif /* !HAVE_MKTIME */
291 
292 #ifdef WANT_TIMEGM
293 #ifndef HAVE_TIMEGM
294 time_t
295 timegm(
296 	struct tm * tmp
297 	)
298 {
299 	register time_t			t;
300 	int				okay;
301 
302 	tmp->tm_isdst = 0;
303 	t = time2(tmp, &okay, 0);
304 	if (okay || tmp->tm_isdst < 0)
305 		return t;
306 
307 	return WRONG;
308 }
309 #endif /* !HAVE_TIMEGM */
310 #endif /* WANT_TIMEGM */
311