xref: /freebsd/contrib/ntp/libntp/mktime.c (revision 1e413cf93298b5b97441a21d9a50fdcd0ee9945e)
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 /*static char *rcsid = "mktime.c,v 1.1.1.3 1998/11/15 19:23:34 kardel RELEASE_19990228_A";*/
38 
39 /*
40  * This implementation of mktime is lifted straight from the NetBSD (BSD 4.4)
41  * version.  I modified it slightly to divorce it from the internals of the
42  * ctime library.  Thus this version can't use details of the internal
43  * timezone state file to figure out strange unnormalized struct tm values,
44  * as might result from someone doing date math on the tm struct then passing
45  * it to mktime.
46  *
47  * It just does as well as it can at normalizing the tm input, then does a
48  * binary search of the time space using the system's localtime() function.
49  *
50  * The original binary search was defective in that it didn't consider the
51  * setting of tm_isdst when comparing tm values, causing the search to be
52  * flubbed for times near the dst/standard time changeover.  The original
53  * code seems to make up for this by grubbing through the timezone info
54  * whenever the binary search barfed.  Since I don't have that luxury in
55  * portable code, I have to take care of tm_isdst in the comparison routine.
56  * This requires knowing how many minutes offset dst is from standard time.
57  *
58  * So, if you live somewhere in the world where dst is not 60 minutes offset,
59  * and your vendor doesn't supply mktime(), you'll have to edit this variable
60  * by hand.  Sorry about that.
61  */
62 
63 #include "ntp_machine.h"
64 
65 #if !HAVE_MKTIME || !HAVE_TIMEGM
66 
67 #ifndef DSTMINUTES
68 #define DSTMINUTES 60
69 #endif
70 
71 #define FALSE 0
72 #define TRUE 1
73 
74 /* some constants from tzfile.h */
75 #define SECSPERMIN      60
76 #define MINSPERHOUR     60
77 #define HOURSPERDAY     24
78 #define DAYSPERWEEK     7
79 #define DAYSPERNYEAR    365
80 #define DAYSPERLYEAR    366
81 #define SECSPERHOUR     (SECSPERMIN * MINSPERHOUR)
82 #define SECSPERDAY      ((long) SECSPERHOUR * HOURSPERDAY)
83 #define MONSPERYEAR     12
84 #define TM_YEAR_BASE    1900
85 #define isleap(y) ((((y) % 4) == 0 && ((y) % 100) != 0) || ((y) % 400) == 0)
86 
87 extern time_t	time P((time_t *));
88 
89 static int	mon_lengths[2][MONSPERYEAR] = {
90 	{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
91 	{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
92 };
93 
94 static int	year_lengths[2] = {
95 	DAYSPERNYEAR, DAYSPERLYEAR
96 };
97 
98 /*
99 ** Adapted from code provided by Robert Elz, who writes:
100 **	The "best" way to do mktime I think is based on an idea of Bob
101 **	Kridle's (so its said...) from a long time ago. (mtxinu!kridle now).
102 **	It does a binary search of the time_t space.  Since time_t's are
103 **	just 32 bits, its a max of 32 iterations (even at 64 bits it
104 **	would still be very reasonable).
105 */
106 
107 #ifndef WRONG
108 #define WRONG	(-1)
109 #endif /* !defined WRONG */
110 
111 static void
112 normalize(
113 	int * tensptr,
114 	int * unitsptr,
115 	int	base
116 	)
117 {
118 	if (*unitsptr >= base) {
119 		*tensptr += *unitsptr / base;
120 		*unitsptr %= base;
121 	} else if (*unitsptr < 0) {
122 		--*tensptr;
123 		*unitsptr += base;
124 		if (*unitsptr < 0) {
125 			*tensptr -= 1 + (-*unitsptr) / base;
126 			*unitsptr = base - (-*unitsptr) % base;
127 		}
128 	}
129 }
130 
131 static struct tm *
132 mkdst(
133 	struct tm *	tmp
134 	)
135 {
136     /* jds */
137     static struct tm tmbuf;
138 
139     tmbuf = *tmp;
140     tmbuf.tm_isdst = 1;
141     tmbuf.tm_min += DSTMINUTES;
142     normalize(&tmbuf.tm_hour, &tmbuf.tm_min, MINSPERHOUR);
143     return &tmbuf;
144 }
145 
146 static int
147 tmcomp(
148 	register struct tm * atmp,
149 	register struct tm * btmp
150 	)
151 {
152 	register int	result;
153 
154 	/* compare down to the same day */
155 
156 	if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
157 	    (result = (atmp->tm_mon - btmp->tm_mon)) == 0)
158 	    result = (atmp->tm_mday - btmp->tm_mday);
159 
160 	if(result != 0)
161 	    return result;
162 
163 	/* get rid of one-sided dst bias */
164 
165 	if(atmp->tm_isdst == 1 && !btmp->tm_isdst)
166 	    btmp = mkdst(btmp);
167 	else if(btmp->tm_isdst == 1 && !atmp->tm_isdst)
168 	    atmp = mkdst(atmp);
169 
170 	/* compare the rest of the way */
171 
172 	if ((result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
173 	    (result = (atmp->tm_min - btmp->tm_min)) == 0)
174 	    result = atmp->tm_sec - btmp->tm_sec;
175 	return result;
176 }
177 
178 
179 static time_t
180 time2(
181 	struct tm *	tmp,
182 	int * 		okayp,
183 	int		usezn
184 	)
185 {
186 	register int			dir;
187 	register int			bits;
188 	register int			i;
189 	register int			saved_seconds;
190 	time_t				t;
191 	struct tm			yourtm, mytm;
192 
193 	*okayp = FALSE;
194 	yourtm = *tmp;
195 	if (yourtm.tm_sec >= SECSPERMIN + 2 || yourtm.tm_sec < 0)
196 		normalize(&yourtm.tm_min, &yourtm.tm_sec, SECSPERMIN);
197 	normalize(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR);
198 	normalize(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY);
199 	normalize(&yourtm.tm_year, &yourtm.tm_mon, MONSPERYEAR);
200 	while (yourtm.tm_mday <= 0) {
201 		--yourtm.tm_year;
202 		yourtm.tm_mday +=
203 			year_lengths[isleap(yourtm.tm_year + TM_YEAR_BASE)];
204 	}
205 	for ( ; ; ) {
206 		i = mon_lengths[isleap(yourtm.tm_year +
207 			TM_YEAR_BASE)][yourtm.tm_mon];
208 		if (yourtm.tm_mday <= i)
209 			break;
210 		yourtm.tm_mday -= i;
211 		if (++yourtm.tm_mon >= MONSPERYEAR) {
212 			yourtm.tm_mon = 0;
213 			++yourtm.tm_year;
214 		}
215 	}
216 	saved_seconds = yourtm.tm_sec;
217 	yourtm.tm_sec = 0;
218 	/*
219 	** Calculate the number of magnitude bits in a time_t
220 	** (this works regardless of whether time_t is
221 	** signed or unsigned, though lint complains if unsigned).
222 	*/
223 	for (bits = 0, t = 1; t > 0; ++bits, t <<= 1)
224 		;
225 	/*
226 	** If time_t is signed, then 0 is the median value,
227 	** if time_t is unsigned, then 1 << bits is median.
228 	*/
229 	t = (t < 0) ? 0 : ((time_t) 1 << bits);
230 	for ( ; ; ) {
231 		if (usezn)
232 	        	mytm = *localtime(&t);
233 		else
234 	        	mytm = *gmtime(&t);
235 		dir = tmcomp(&mytm, &yourtm);
236 		if (dir != 0) {
237 			if (bits-- < 0)
238 				return WRONG;
239 			if (bits < 0)
240 				--t;
241 			else if (dir > 0)
242 				t -= (time_t) 1 << bits;
243 			else	t += (time_t) 1 << bits;
244 			continue;
245 		}
246 		if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
247 			break;
248 
249 		return WRONG;
250 	}
251 	t += saved_seconds;
252 	if (usezn)
253 		*tmp = *localtime(&t);
254 	else
255 		*tmp = *gmtime(&t);
256 	*okayp = TRUE;
257 	return t;
258 }
259 #else
260 int mktime_bs;
261 #endif /* !HAVE_MKTIME || !HAVE_TIMEGM */
262 
263 #if !HAVE_MKTIME
264 static time_t
265 time1(
266 	struct tm * tmp
267 	)
268 {
269 	register time_t			t;
270 	int				okay;
271 
272 	if (tmp->tm_isdst > 1)
273 		tmp->tm_isdst = 1;
274 	t = time2(tmp, &okay, 1);
275 	if (okay || tmp->tm_isdst < 0)
276 		return t;
277 
278 	return WRONG;
279 }
280 
281 time_t
282 mktime(
283 	struct tm * tmp
284 	)
285 {
286 	return time1(tmp);
287 }
288 #endif /* !HAVE_MKTIME */
289 
290 #if !HAVE_TIMEGM
291 time_t
292 timegm(
293 	struct tm * tmp
294 	)
295 {
296 	register time_t			t;
297 	int				okay;
298 
299 	tmp->tm_isdst = 0;
300 	t = time2(tmp, &okay, 0);
301 	if (okay || tmp->tm_isdst < 0)
302 		return t;
303 
304 	return WRONG;
305 }
306 #endif /* !HAVE_TIMEGM */
307