xref: /netbsd-src/lib/libc/time/localtime.c (revision 466a16a118933bd295a8a104f095714fadf9cf68)
1 /*	$NetBSD: localtime.c,v 1.41 2008/08/27 08:49:03 christos Exp $	*/
2 
3 /*
4 ** This file is in the public domain, so clarified as of
5 ** 1996-06-05 by Arthur David Olson (arthur_david_olson@nih.gov).
6 */
7 
8 #include <sys/cdefs.h>
9 #if defined(LIBC_SCCS) && !defined(lint)
10 #if 0
11 static char	elsieid[] = "@(#)localtime.c	7.78";
12 #else
13 __RCSID("$NetBSD: localtime.c,v 1.41 2008/08/27 08:49:03 christos Exp $");
14 #endif
15 #endif /* LIBC_SCCS and not lint */
16 
17 /*
18 ** Leap second handling from Bradley White (bww@k.gp.cs.cmu.edu).
19 ** POSIX-style TZ environment variable handling from Guy Harris
20 ** (guy@auspex.com).
21 */
22 
23 /*LINTLIBRARY*/
24 
25 #include "namespace.h"
26 #include "private.h"
27 #include "tzfile.h"
28 #include "fcntl.h"
29 #include "reentrant.h"
30 
31 #ifdef __weak_alias
32 __weak_alias(ctime_r,_ctime_r)
33 __weak_alias(daylight,_daylight)
34 __weak_alias(gmtime_r,_gmtime_r)
35 __weak_alias(localtime_r,_localtime_r)
36 __weak_alias(offtime,_offtime)
37 __weak_alias(posix2time,_posix2time)
38 __weak_alias(time2posix,_time2posix)
39 __weak_alias(timegm,_timegm)
40 __weak_alias(timelocal,_timelocal)
41 __weak_alias(timeoff,_timeoff)
42 __weak_alias(tzname,_tzname)
43 __weak_alias(tzset,_tzset)
44 __weak_alias(tzsetwall,_tzsetwall)
45 #endif
46 
47 /*
48 ** SunOS 4.1.1 headers lack O_BINARY.
49 */
50 
51 #ifdef O_BINARY
52 #define OPEN_MODE	(O_RDONLY | O_BINARY)
53 #endif /* defined O_BINARY */
54 #ifndef O_BINARY
55 #define OPEN_MODE	O_RDONLY
56 #endif /* !defined O_BINARY */
57 
58 #ifndef WILDABBR
59 /*
60 ** Someone might make incorrect use of a time zone abbreviation:
61 **	1.	They might reference tzname[0] before calling tzset (explicitly
62 **		or implicitly).
63 **	2.	They might reference tzname[1] before calling tzset (explicitly
64 **		or implicitly).
65 **	3.	They might reference tzname[1] after setting to a time zone
66 **		in which Daylight Saving Time is never observed.
67 **	4.	They might reference tzname[0] after setting to a time zone
68 **		in which Standard Time is never observed.
69 **	5.	They might reference tm.TM_ZONE after calling offtime.
70 ** What's best to do in the above cases is open to debate;
71 ** for now, we just set things up so that in any of the five cases
72 ** WILDABBR is used.  Another possibility:  initialize tzname[0] to the
73 ** string "tzname[0] used before set", and similarly for the other cases.
74 ** And another:  initialize tzname[0] to "ERA", with an explanation in the
75 ** manual page of what this "time zone abbreviation" means (doing this so
76 ** that tzname[0] has the "normal" length of three characters).
77 */
78 #define WILDABBR	"   "
79 #endif /* !defined WILDABBR */
80 
81 static const char	wildabbr[] = "WILDABBR";
82 
83 static const char	gmt[] = "GMT";
84 
85 /*
86 ** The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
87 ** We default to US rules as of 1999-08-17.
88 ** POSIX 1003.1 section 8.1.1 says that the default DST rules are
89 ** implementation dependent; for historical reasons, US rules are a
90 ** common default.
91 */
92 #ifndef TZDEFRULESTRING
93 #define TZDEFRULESTRING ",M4.1.0,M10.5.0"
94 #endif /* !defined TZDEFDST */
95 
96 struct ttinfo {				/* time type information */
97 	long		tt_gmtoff;	/* UTC offset in seconds */
98 	int		tt_isdst;	/* used to set tm_isdst */
99 	int		tt_abbrind;	/* abbreviation list index */
100 	int		tt_ttisstd;	/* TRUE if transition is std time */
101 	int		tt_ttisgmt;	/* TRUE if transition is UTC */
102 };
103 
104 struct lsinfo {				/* leap second information */
105 	time_t		ls_trans;	/* transition time */
106 	long		ls_corr;	/* correction to apply */
107 };
108 
109 #define BIGGEST(a, b)	(((a) > (b)) ? (a) : (b))
110 
111 #ifdef TZNAME_MAX
112 #define MY_TZNAME_MAX	TZNAME_MAX
113 #endif /* defined TZNAME_MAX */
114 #ifndef TZNAME_MAX
115 #define MY_TZNAME_MAX	255
116 #endif /* !defined TZNAME_MAX */
117 
118 struct state {
119 	int		leapcnt;
120 	int		timecnt;
121 	int		typecnt;
122 	int		charcnt;
123 	time_t		ats[TZ_MAX_TIMES];
124 	unsigned char	types[TZ_MAX_TIMES];
125 	struct ttinfo	ttis[TZ_MAX_TYPES];
126 	char		chars[/*CONSTCOND*/BIGGEST(BIGGEST(TZ_MAX_CHARS + 1, sizeof gmt),
127 				(2 * (MY_TZNAME_MAX + 1)))];
128 	struct lsinfo	lsis[TZ_MAX_LEAPS];
129 };
130 
131 struct rule {
132 	int		r_type;		/* type of rule--see below */
133 	int		r_day;		/* day number of rule */
134 	int		r_week;		/* week number of rule */
135 	int		r_mon;		/* month number of rule */
136 	long		r_time;		/* transition time of rule */
137 };
138 
139 #define JULIAN_DAY		0	/* Jn - Julian day */
140 #define DAY_OF_YEAR		1	/* n - day of year */
141 #define MONTH_NTH_DAY_OF_WEEK	2	/* Mm.n.d - month, week, day of week */
142 
143 /*
144 ** Prototypes for static functions.
145 */
146 
147 static long		detzcode P((const char * codep));
148 static const char *	getzname P((const char * strp));
149 static const char *	getnum P((const char * strp, int * nump, int min,
150 				int max));
151 static const char *	getsecs P((const char * strp, long * secsp));
152 static const char *	getoffset P((const char * strp, long * offsetp));
153 static const char *	getrule P((const char * strp, struct rule * rulep));
154 static void		gmtload P((struct state * sp));
155 static void		gmtsub P((const time_t * timep, long offset,
156 				struct tm * tmp));
157 static void		localsub P((const time_t * timep, long offset,
158 				struct tm * tmp));
159 static int		increment_overflow P((int * number, int delta));
160 static int		normalize_overflow P((int * tensptr, int * unitsptr,
161 				int base));
162 static void		settzname P((void));
163 static time_t		time1 P((struct tm * tmp,
164 				void(*funcp) P((const time_t *,
165 				long, struct tm *)),
166 				long offset));
167 static time_t		time2 P((struct tm *tmp,
168 				void(*funcp) P((const time_t *,
169 				long, struct tm*)),
170 				long offset, int * okayp));
171 static time_t		time2sub P((struct tm *tmp,
172 				void(*funcp) P((const time_t *,
173 				long, struct tm*)),
174 				long offset, int * okayp, int do_norm_secs));
175 static void		timesub P((const time_t * timep, long offset,
176 				const struct state * sp, struct tm * tmp));
177 static int		tmcomp P((const struct tm * atmp,
178 				const struct tm * btmp));
179 static time_t		transtime P((time_t janfirst, int year,
180 				const struct rule * rulep, long offset));
181 static int		tzload P((const char * name, struct state * sp));
182 static int		tzparse P((const char * name, struct state * sp,
183 				int lastditch));
184 static void		tzset_unlocked P((void));
185 static void		tzsetwall_unlocked P((void));
186 #ifdef STD_INSPIRED
187 static long		leapcorr P((time_t * timep));
188 #endif
189 
190 #ifdef ALL_STATE
191 static struct state *	lclptr;
192 static struct state *	gmtptr;
193 #endif /* defined ALL_STATE */
194 
195 #ifndef ALL_STATE
196 static struct state	lclmem;
197 static struct state	gmtmem;
198 #define lclptr		(&lclmem)
199 #define gmtptr		(&gmtmem)
200 #endif /* State Farm */
201 
202 #ifndef TZ_STRLEN_MAX
203 #define TZ_STRLEN_MAX 255
204 #endif /* !defined TZ_STRLEN_MAX */
205 
206 static char		lcl_TZname[TZ_STRLEN_MAX + 1];
207 static int		lcl_is_set;
208 static int		gmt_is_set;
209 
210 __aconst char *		tzname[2] = {
211 	(__aconst char *)__UNCONST(wildabbr),
212 	(__aconst char *)__UNCONST(wildabbr)
213 };
214 
215 #ifdef _REENTRANT
216 static rwlock_t lcl_lock = RWLOCK_INITIALIZER;
217 #endif
218 
219 /*
220 ** Section 4.12.3 of X3.159-1989 requires that
221 **	Except for the strftime function, these functions [asctime,
222 **	ctime, gmtime, localtime] return values in one of two static
223 **	objects: a broken-down time structure and an array of char.
224 ** Thanks to Paul Eggert (eggert@twinsun.com) for noting this.
225 */
226 
227 static struct tm	tm;
228 
229 #ifdef USG_COMPAT
230 long int		timezone = 0;
231 int			daylight = 0;
232 #endif /* defined USG_COMPAT */
233 
234 #ifdef ALTZONE
235 time_t			altzone = 0;
236 #endif /* defined ALTZONE */
237 
238 static long
239 detzcode(codep)
240 const char * const	codep;
241 {
242 	register long	result;
243 
244 	/*
245         ** The first character must be sign extended on systems with >32bit
246         ** longs.  This was solved differently in the master tzcode sources
247         ** (the fix first appeared in tzcode95c.tar.gz).  But I believe
248 	** that this implementation is superior.
249         */
250 
251 #define SIGN_EXTEND_CHAR(x)	((signed char) x)
252 
253 	result = (SIGN_EXTEND_CHAR(codep[0]) << 24) \
254 	       | (codep[1] & 0xff) << 16 \
255 	       | (codep[2] & 0xff) << 8
256 	       | (codep[3] & 0xff);
257 	return result;
258 }
259 
260 static void
261 settzname P((void))
262 {
263 	register struct state * const	sp = lclptr;
264 	register int			i;
265 
266 	tzname[0] = (__aconst char *)__UNCONST(wildabbr);
267 	tzname[1] = (__aconst char *)__UNCONST(wildabbr);
268 #ifdef USG_COMPAT
269 	daylight = 0;
270 	timezone = 0;
271 #endif /* defined USG_COMPAT */
272 #ifdef ALTZONE
273 	altzone = 0;
274 #endif /* defined ALTZONE */
275 #ifdef ALL_STATE
276 	if (sp == NULL) {
277 		tzname[0] = tzname[1] = (__aconst char *)__UNCONST(gmt);
278 		return;
279 	}
280 #endif /* defined ALL_STATE */
281 	for (i = 0; i < sp->typecnt; ++i) {
282 		register const struct ttinfo * const	ttisp = &sp->ttis[i];
283 
284 		tzname[ttisp->tt_isdst] =
285 			&sp->chars[ttisp->tt_abbrind];
286 	}
287 	/*
288 	** And to get the latest zone names into tzname. . .
289 	*/
290 	for (i = 0; i < sp->timecnt; ++i) {
291 		register const struct ttinfo * const	ttisp =
292 							&sp->ttis[
293 								sp->types[i]];
294 
295 		tzname[ttisp->tt_isdst] =
296 			&sp->chars[ttisp->tt_abbrind];
297 #ifdef USG_COMPAT
298 		if (ttisp->tt_isdst)
299 			daylight = 1;
300 		if (i == 0 || !ttisp->tt_isdst)
301 			timezone = -(ttisp->tt_gmtoff);
302 #endif /* defined USG_COMPAT */
303 #ifdef ALTZONE
304 		if (i == 0 || ttisp->tt_isdst)
305 			altzone = -(ttisp->tt_gmtoff);
306 #endif /* defined ALTZONE */
307 	}
308 }
309 
310 static int
311 tzload(name, sp)
312 register const char *		name;
313 register struct state * const	sp;
314 {
315 	register const char *	p;
316 	register int		i;
317 	register int		fid;
318 
319 	if (name == NULL && (name = TZDEFAULT) == NULL)
320 		return -1;
321 
322 	{
323 		register int	doaccess;
324 		/*
325 		** Section 4.9.1 of the C standard says that
326 		** "FILENAME_MAX expands to an integral constant expression
327 		** that is the size needed for an array of char large enough
328 		** to hold the longest file name string that the implementation
329 		** guarantees can be opened."
330 		*/
331 		char		fullname[FILENAME_MAX + 1];
332 
333 		if (name[0] == ':')
334 			++name;
335 		doaccess = name[0] == '/';
336 		if (!doaccess) {
337 			if ((p = TZDIR) == NULL)
338 				return -1;
339 			if ((strlen(p) + strlen(name) + 1) >= sizeof fullname)
340 				return -1;
341 			(void) strcpy(fullname, p);	/* XXX strcpy is safe */
342 			(void) strcat(fullname, "/");	/* XXX strcat is safe */
343 			(void) strcat(fullname, name);	/* XXX strcat is safe */
344 			/*
345 			** Set doaccess if '.' (as in "../") shows up in name.
346 			*/
347 			if (strchr(name, '.') != NULL)
348 				doaccess = TRUE;
349 			name = fullname;
350 		}
351 		if (doaccess && access(name, R_OK) != 0)
352 			return -1;
353 		/*
354 		 * XXX potential security problem here if user of a set-id
355 		 * program has set TZ (which is passed in as name) here,
356 		 * and uses a race condition trick to defeat the access(2)
357 		 * above.
358 		 */
359 		if ((fid = open(name, OPEN_MODE)) == -1)
360 			return -1;
361 	}
362 	{
363 		struct tzhead *	tzhp;
364 		union {
365 			struct tzhead	tzhead;
366 			char		buf[sizeof *sp + sizeof *tzhp];
367 		} u;
368 		int		ttisstdcnt;
369 		int		ttisgmtcnt;
370 
371 		i = read(fid, u.buf, sizeof u.buf);
372 		if (close(fid) != 0)
373 			return -1;
374 		ttisstdcnt = (int) detzcode(u.tzhead.tzh_ttisstdcnt);
375 		ttisgmtcnt = (int) detzcode(u.tzhead.tzh_ttisgmtcnt);
376 		sp->leapcnt = (int) detzcode(u.tzhead.tzh_leapcnt);
377 		sp->timecnt = (int) detzcode(u.tzhead.tzh_timecnt);
378 		sp->typecnt = (int) detzcode(u.tzhead.tzh_typecnt);
379 		sp->charcnt = (int) detzcode(u.tzhead.tzh_charcnt);
380 		p = u.tzhead.tzh_charcnt + sizeof u.tzhead.tzh_charcnt;
381 		if (sp->leapcnt < 0 || sp->leapcnt > TZ_MAX_LEAPS ||
382 			sp->typecnt <= 0 || sp->typecnt > TZ_MAX_TYPES ||
383 			sp->timecnt < 0 || sp->timecnt > TZ_MAX_TIMES ||
384 			sp->charcnt < 0 || sp->charcnt > TZ_MAX_CHARS ||
385 			(ttisstdcnt != sp->typecnt && ttisstdcnt != 0) ||
386 			(ttisgmtcnt != sp->typecnt && ttisgmtcnt != 0))
387 				return -1;
388 		if (i - (p - u.buf) < sp->timecnt * 4 +	/* ats */
389 			sp->timecnt +			/* types */
390 			sp->typecnt * (4 + 2) +		/* ttinfos */
391 			sp->charcnt +			/* chars */
392 			sp->leapcnt * (4 + 4) +		/* lsinfos */
393 			ttisstdcnt +			/* ttisstds */
394 			ttisgmtcnt)			/* ttisgmts */
395 				return -1;
396 		for (i = 0; i < sp->timecnt; ++i) {
397 			sp->ats[i] = detzcode(p);
398 			p += 4;
399 		}
400 		for (i = 0; i < sp->timecnt; ++i) {
401 			sp->types[i] = (unsigned char) *p++;
402 			if (sp->types[i] >= sp->typecnt)
403 				return -1;
404 		}
405 		for (i = 0; i < sp->typecnt; ++i) {
406 			register struct ttinfo *	ttisp;
407 
408 			ttisp = &sp->ttis[i];
409 			ttisp->tt_gmtoff = detzcode(p);
410 			p += 4;
411 			ttisp->tt_isdst = (unsigned char) *p++;
412 			if (ttisp->tt_isdst != 0 && ttisp->tt_isdst != 1)
413 				return -1;
414 			ttisp->tt_abbrind = (unsigned char) *p++;
415 			if (ttisp->tt_abbrind < 0 ||
416 				ttisp->tt_abbrind > sp->charcnt)
417 					return -1;
418 		}
419 		for (i = 0; i < sp->charcnt; ++i)
420 			sp->chars[i] = *p++;
421 		sp->chars[i] = '\0';	/* ensure '\0' at end */
422 		for (i = 0; i < sp->leapcnt; ++i) {
423 			register struct lsinfo *	lsisp;
424 
425 			lsisp = &sp->lsis[i];
426 			lsisp->ls_trans = detzcode(p);
427 			p += 4;
428 			lsisp->ls_corr = detzcode(p);
429 			p += 4;
430 		}
431 		for (i = 0; i < sp->typecnt; ++i) {
432 			register struct ttinfo *	ttisp;
433 
434 			ttisp = &sp->ttis[i];
435 			if (ttisstdcnt == 0)
436 				ttisp->tt_ttisstd = FALSE;
437 			else {
438 				ttisp->tt_ttisstd = *p++;
439 				if (ttisp->tt_ttisstd != TRUE &&
440 					ttisp->tt_ttisstd != FALSE)
441 						return -1;
442 			}
443 		}
444 		for (i = 0; i < sp->typecnt; ++i) {
445 			register struct ttinfo *	ttisp;
446 
447 			ttisp = &sp->ttis[i];
448 			if (ttisgmtcnt == 0)
449 				ttisp->tt_ttisgmt = FALSE;
450 			else {
451 				ttisp->tt_ttisgmt = *p++;
452 				if (ttisp->tt_ttisgmt != TRUE &&
453 					ttisp->tt_ttisgmt != FALSE)
454 						return -1;
455 			}
456 		}
457 	}
458 	return 0;
459 }
460 
461 static const int	mon_lengths[2][MONSPERYEAR] = {
462 	{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
463 	{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
464 };
465 
466 static const int	year_lengths[2] = {
467 	DAYSPERNYEAR, DAYSPERLYEAR
468 };
469 
470 /*
471 ** Given a pointer into a time zone string, scan until a character that is not
472 ** a valid character in a zone name is found.  Return a pointer to that
473 ** character.
474 */
475 
476 static const char *
477 getzname(strp)
478 register const char *	strp;
479 {
480 	register char	c;
481 
482 	while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
483 		c != '+')
484 			++strp;
485 	return strp;
486 }
487 
488 /*
489 ** Given a pointer into a time zone string, extract a number from that string.
490 ** Check that the number is within a specified range; if it is not, return
491 ** NULL.
492 ** Otherwise, return a pointer to the first character not part of the number.
493 */
494 
495 static const char *
496 getnum(strp, nump, min, max)
497 register const char *	strp;
498 int * const		nump;
499 const int		min;
500 const int		max;
501 {
502 	register char	c;
503 	register int	num;
504 
505 	if (strp == NULL || !is_digit(c = *strp))
506 		return NULL;
507 	num = 0;
508 	do {
509 		num = num * 10 + (c - '0');
510 		if (num > max)
511 			return NULL;	/* illegal value */
512 		c = *++strp;
513 	} while (is_digit(c));
514 	if (num < min)
515 		return NULL;		/* illegal value */
516 	*nump = num;
517 	return strp;
518 }
519 
520 /*
521 ** Given a pointer into a time zone string, extract a number of seconds,
522 ** in hh[:mm[:ss]] form, from the string.
523 ** If any error occurs, return NULL.
524 ** Otherwise, return a pointer to the first character not part of the number
525 ** of seconds.
526 */
527 
528 static const char *
529 getsecs(strp, secsp)
530 register const char *	strp;
531 long * const		secsp;
532 {
533 	int	num;
534 
535 	/*
536 	** `HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
537 	** "M10.4.6/26", which does not conform to Posix,
538 	** but which specifies the equivalent of
539 	** ``02:00 on the first Sunday on or after 23 Oct''.
540 	*/
541 	strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
542 	if (strp == NULL)
543 		return NULL;
544 	*secsp = num * (long) SECSPERHOUR;
545 	if (*strp == ':') {
546 		++strp;
547 		strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
548 		if (strp == NULL)
549 			return NULL;
550 		*secsp += num * SECSPERMIN;
551 		if (*strp == ':') {
552 			++strp;
553 			/* `SECSPERMIN' allows for leap seconds.  */
554 			strp = getnum(strp, &num, 0, SECSPERMIN);
555 			if (strp == NULL)
556 				return NULL;
557 			*secsp += num;
558 		}
559 	}
560 	return strp;
561 }
562 
563 /*
564 ** Given a pointer into a time zone string, extract an offset, in
565 ** [+-]hh[:mm[:ss]] form, from the string.
566 ** If any error occurs, return NULL.
567 ** Otherwise, return a pointer to the first character not part of the time.
568 */
569 
570 static const char *
571 getoffset(strp, offsetp)
572 register const char *	strp;
573 long * const		offsetp;
574 {
575 	register int	neg = 0;
576 
577 	if (*strp == '-') {
578 		neg = 1;
579 		++strp;
580 	} else if (*strp == '+')
581 		++strp;
582 	strp = getsecs(strp, offsetp);
583 	if (strp == NULL)
584 		return NULL;		/* illegal time */
585 	if (neg)
586 		*offsetp = -*offsetp;
587 	return strp;
588 }
589 
590 /*
591 ** Given a pointer into a time zone string, extract a rule in the form
592 ** date[/time].  See POSIX section 8 for the format of "date" and "time".
593 ** If a valid rule is not found, return NULL.
594 ** Otherwise, return a pointer to the first character not part of the rule.
595 */
596 
597 static const char *
598 getrule(strp, rulep)
599 const char *			strp;
600 register struct rule * const	rulep;
601 {
602 	if (*strp == 'J') {
603 		/*
604 		** Julian day.
605 		*/
606 		rulep->r_type = JULIAN_DAY;
607 		++strp;
608 		strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
609 	} else if (*strp == 'M') {
610 		/*
611 		** Month, week, day.
612 		*/
613 		rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
614 		++strp;
615 		strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
616 		if (strp == NULL)
617 			return NULL;
618 		if (*strp++ != '.')
619 			return NULL;
620 		strp = getnum(strp, &rulep->r_week, 1, 5);
621 		if (strp == NULL)
622 			return NULL;
623 		if (*strp++ != '.')
624 			return NULL;
625 		strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
626 	} else if (is_digit(*strp)) {
627 		/*
628 		** Day of year.
629 		*/
630 		rulep->r_type = DAY_OF_YEAR;
631 		strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
632 	} else	return NULL;		/* invalid format */
633 	if (strp == NULL)
634 		return NULL;
635 	if (*strp == '/') {
636 		/*
637 		** Time specified.
638 		*/
639 		++strp;
640 		strp = getsecs(strp, &rulep->r_time);
641 	} else	rulep->r_time = 2 * SECSPERHOUR;	/* default = 2:00:00 */
642 	return strp;
643 }
644 
645 /*
646 ** Given the Epoch-relative time of January 1, 00:00:00 UTC, in a year, the
647 ** year, a rule, and the offset from UTC at the time that rule takes effect,
648 ** calculate the Epoch-relative time that rule takes effect.
649 */
650 
651 static time_t
652 transtime(janfirst, year, rulep, offset)
653 const time_t				janfirst;
654 const int				year;
655 register const struct rule * const	rulep;
656 const long				offset;
657 {
658 	register int	leapyear;
659 	register time_t	value;
660 	register int	i;
661 	int		d, m1, yy0, yy1, yy2, dow;
662 
663 	INITIALIZE(value);
664 	leapyear = isleap(year);
665 	switch (rulep->r_type) {
666 
667 	case JULIAN_DAY:
668 		/*
669 		** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
670 		** years.
671 		** In non-leap years, or if the day number is 59 or less, just
672 		** add SECSPERDAY times the day number-1 to the time of
673 		** January 1, midnight, to get the day.
674 		*/
675 		value = janfirst + (rulep->r_day - 1) * SECSPERDAY;
676 		if (leapyear && rulep->r_day >= 60)
677 			value += SECSPERDAY;
678 		break;
679 
680 	case DAY_OF_YEAR:
681 		/*
682 		** n - day of year.
683 		** Just add SECSPERDAY times the day number to the time of
684 		** January 1, midnight, to get the day.
685 		*/
686 		value = janfirst + rulep->r_day * SECSPERDAY;
687 		break;
688 
689 	case MONTH_NTH_DAY_OF_WEEK:
690 		/*
691 		** Mm.n.d - nth "dth day" of month m.
692 		*/
693 		value = janfirst;
694 		for (i = 0; i < rulep->r_mon - 1; ++i)
695 			value += mon_lengths[leapyear][i] * SECSPERDAY;
696 
697 		/*
698 		** Use Zeller's Congruence to get day-of-week of first day of
699 		** month.
700 		*/
701 		m1 = (rulep->r_mon + 9) % 12 + 1;
702 		yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
703 		yy1 = yy0 / 100;
704 		yy2 = yy0 % 100;
705 		dow = ((26 * m1 - 2) / 10 +
706 			1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
707 		if (dow < 0)
708 			dow += DAYSPERWEEK;
709 
710 		/*
711 		** "dow" is the day-of-week of the first day of the month.  Get
712 		** the day-of-month (zero-origin) of the first "dow" day of the
713 		** month.
714 		*/
715 		d = rulep->r_day - dow;
716 		if (d < 0)
717 			d += DAYSPERWEEK;
718 		for (i = 1; i < rulep->r_week; ++i) {
719 			if (d + DAYSPERWEEK >=
720 				mon_lengths[leapyear][rulep->r_mon - 1])
721 					break;
722 			d += DAYSPERWEEK;
723 		}
724 
725 		/*
726 		** "d" is the day-of-month (zero-origin) of the day we want.
727 		*/
728 		value += d * SECSPERDAY;
729 		break;
730 	}
731 
732 	/*
733 	** "value" is the Epoch-relative time of 00:00:00 UTC on the day in
734 	** question.  To get the Epoch-relative time of the specified local
735 	** time on that day, add the transition time and the current offset
736 	** from UTC.
737 	*/
738 	return value + rulep->r_time + offset;
739 }
740 
741 /*
742 ** Given a POSIX section 8-style TZ string, fill in the rule tables as
743 ** appropriate.
744 */
745 
746 static int
747 tzparse(name, sp, lastditch)
748 const char *			name;
749 register struct state * const	sp;
750 const int			lastditch;
751 {
752 	const char *			stdname;
753 	const char *			dstname;
754 	size_t				stdlen;
755 	size_t				dstlen;
756 	long				stdoffset;
757 	long				dstoffset;
758 	register time_t *		atp;
759 	register unsigned char *	typep;
760 	register char *			cp;
761 	register int			load_result;
762 
763 	INITIALIZE(dstname);
764 	stdname = name;
765 	if (lastditch) {
766 		stdlen = strlen(name);	/* length of standard zone name */
767 		name += stdlen;
768 		if (stdlen >= sizeof sp->chars)
769 			stdlen = (sizeof sp->chars) - 1;
770 		stdoffset = 0;
771 	} else {
772 		name = getzname(name);
773 		stdlen = name - stdname;
774 		if (stdlen < 3)
775 			return -1;
776 		if (*name == '\0')
777 			return -1;
778 		name = getoffset(name, &stdoffset);
779 		if (name == NULL)
780 			return -1;
781 	}
782 	load_result = tzload(TZDEFRULES, sp);
783 	if (load_result != 0)
784 		sp->leapcnt = 0;		/* so, we're off a little */
785 	if (*name != '\0') {
786 		dstname = name;
787 		name = getzname(name);
788 		dstlen = name - dstname;	/* length of DST zone name */
789 		if (dstlen < 3)
790 			return -1;
791 		if (*name != '\0' && *name != ',' && *name != ';') {
792 			name = getoffset(name, &dstoffset);
793 			if (name == NULL)
794 				return -1;
795 		} else	dstoffset = stdoffset - SECSPERHOUR;
796 		if (*name == '\0' && load_result != 0)
797 			name = TZDEFRULESTRING;
798 		if (*name == ',' || *name == ';') {
799 			struct rule	start;
800 			struct rule	end;
801 			register int	year;
802 			register time_t	janfirst;
803 			time_t		starttime;
804 			time_t		endtime;
805 
806 			++name;
807 			if ((name = getrule(name, &start)) == NULL)
808 				return -1;
809 			if (*name++ != ',')
810 				return -1;
811 			if ((name = getrule(name, &end)) == NULL)
812 				return -1;
813 			if (*name != '\0')
814 				return -1;
815 			sp->typecnt = 2;	/* standard time and DST */
816 			/*
817 			** Two transitions per year, from EPOCH_YEAR to 2037.
818 			*/
819 			sp->timecnt = 2 * (2037 - EPOCH_YEAR + 1);
820 			if (sp->timecnt > TZ_MAX_TIMES)
821 				return -1;
822 			sp->ttis[0].tt_gmtoff = -dstoffset;
823 			sp->ttis[0].tt_isdst = 1;
824 			sp->ttis[0].tt_abbrind = stdlen + 1;
825 			sp->ttis[1].tt_gmtoff = -stdoffset;
826 			sp->ttis[1].tt_isdst = 0;
827 			sp->ttis[1].tt_abbrind = 0;
828 			atp = sp->ats;
829 			typep = sp->types;
830 			janfirst = 0;
831 			for (year = EPOCH_YEAR; year <= 2037; ++year) {
832 				starttime = transtime(janfirst, year, &start,
833 					stdoffset);
834 				endtime = transtime(janfirst, year, &end,
835 					dstoffset);
836 				if (starttime > endtime) {
837 					*atp++ = endtime;
838 					*typep++ = 1;	/* DST ends */
839 					*atp++ = starttime;
840 					*typep++ = 0;	/* DST begins */
841 				} else {
842 					*atp++ = starttime;
843 					*typep++ = 0;	/* DST begins */
844 					*atp++ = endtime;
845 					*typep++ = 1;	/* DST ends */
846 				}
847 				janfirst += year_lengths[isleap(year)] *
848 					SECSPERDAY;
849 			}
850 		} else {
851 			register long	theirstdoffset;
852 			register long	theiroffset;
853 			register int	i;
854 			register int	j;
855 
856 			if (*name != '\0')
857 				return -1;
858 			/*
859 			** Initial values of theirstdoffset
860 			*/
861 			theirstdoffset = 0;
862 			for (i = 0; i < sp->timecnt; ++i) {
863 				j = sp->types[i];
864 				if (!sp->ttis[j].tt_isdst) {
865 					theirstdoffset =
866 						-sp->ttis[j].tt_gmtoff;
867 					break;
868 				}
869 			}
870 			/*
871 			** Initially we're assumed to be in standard time.
872 			*/
873 			theiroffset = theirstdoffset;
874 			/*
875 			** Now juggle transition times and types
876 			** tracking offsets as you do.
877 			*/
878 			for (i = 0; i < sp->timecnt; ++i) {
879 				j = sp->types[i];
880 				sp->types[i] = sp->ttis[j].tt_isdst;
881 				if (sp->ttis[j].tt_ttisgmt) {
882 					/* No adjustment to transition time */
883 				} else {
884 					/*
885 					** If summer time is in effect, and the
886 					** transition time was not specified as
887 					** standard time, add the summer time
888 					** offset to the transition time;
889 					** otherwise, add the standard time
890 					** offset to the transition time.
891 					*/
892 					/*
893 					** Transitions from DST to DDST
894 					** will effectively disappear since
895 					** POSIX provides for only one DST
896 					** offset.
897 					*/
898 					sp->ats[i] += stdoffset -
899 					    theirstdoffset;
900 				}
901 				theiroffset = -sp->ttis[j].tt_gmtoff;
902 				if (!sp->ttis[j].tt_isdst)
903 					theirstdoffset = theiroffset;
904 			}
905 			/*
906 			** Finally, fill in ttis.
907 			** ttisstd and ttisgmt need not be handled.
908 			*/
909 			sp->ttis[0].tt_gmtoff = -stdoffset;
910 			sp->ttis[0].tt_isdst = FALSE;
911 			sp->ttis[0].tt_abbrind = 0;
912 			sp->ttis[1].tt_gmtoff = -dstoffset;
913 			sp->ttis[1].tt_isdst = TRUE;
914 			sp->ttis[1].tt_abbrind = stdlen + 1;
915 			sp->typecnt = 2;
916 		}
917 	} else {
918 		dstlen = 0;
919 		sp->typecnt = 1;		/* only standard time */
920 		sp->timecnt = 0;
921 		sp->ttis[0].tt_gmtoff = -stdoffset;
922 		sp->ttis[0].tt_isdst = 0;
923 		sp->ttis[0].tt_abbrind = 0;
924 	}
925 	sp->charcnt = stdlen + 1;
926 	if (dstlen != 0)
927 		sp->charcnt += dstlen + 1;
928 	if ((size_t) sp->charcnt > sizeof sp->chars)
929 		return -1;
930 	cp = sp->chars;
931 	(void) strncpy(cp, stdname, stdlen);
932 	cp += stdlen;
933 	*cp++ = '\0';
934 	if (dstlen != 0) {
935 		(void) strncpy(cp, dstname, dstlen);
936 		*(cp + dstlen) = '\0';
937 	}
938 	return 0;
939 }
940 
941 static void
942 gmtload(sp)
943 struct state * const	sp;
944 {
945 	if (tzload(gmt, sp) != 0)
946 		(void) tzparse(gmt, sp, TRUE);
947 }
948 
949 static void
950 tzsetwall_unlocked P((void))
951 {
952 	if (lcl_is_set < 0)
953 		return;
954 	lcl_is_set = -1;
955 
956 #ifdef ALL_STATE
957 	if (lclptr == NULL) {
958 		int saveerrno = errno;
959 		lclptr = (struct state *) malloc(sizeof *lclptr);
960 		errno = saveerrno;
961 		if (lclptr == NULL) {
962 			settzname();	/* all we can do */
963 			return;
964 		}
965 	}
966 #endif /* defined ALL_STATE */
967 	if (tzload((char *) NULL, lclptr) != 0)
968 		gmtload(lclptr);
969 	settzname();
970 }
971 
972 #ifndef STD_INSPIRED
973 /*
974 ** A non-static declaration of tzsetwall in a system header file
975 ** may cause a warning about this upcoming static declaration...
976 */
977 static
978 #endif /* !defined STD_INSPIRED */
979 void
980 tzsetwall P((void))
981 {
982 	rwlock_wrlock(&lcl_lock);
983 	tzsetwall_unlocked();
984 	rwlock_unlock(&lcl_lock);
985 }
986 
987 static void
988 tzset_unlocked P((void))
989 {
990 	register const char *	name;
991 	int saveerrno;
992 
993 	saveerrno = errno;
994 	name = getenv("TZ");
995 	errno = saveerrno;
996 	if (name == NULL) {
997 		tzsetwall_unlocked();
998 		return;
999 	}
1000 
1001 	if (lcl_is_set > 0 && strcmp(lcl_TZname, name) == 0)
1002 		return;
1003 	lcl_is_set = strlen(name) < sizeof lcl_TZname;
1004 	if (lcl_is_set)
1005 		(void)strlcpy(lcl_TZname, name, sizeof(lcl_TZname));
1006 
1007 #ifdef ALL_STATE
1008 	if (lclptr == NULL) {
1009 		saveerrno = errno;
1010 		lclptr = (struct state *) malloc(sizeof *lclptr);
1011 		errno = saveerrno;
1012 		if (lclptr == NULL) {
1013 			settzname();	/* all we can do */
1014 			return;
1015 		}
1016 	}
1017 #endif /* defined ALL_STATE */
1018 	if (*name == '\0') {
1019 		/*
1020 		** User wants it fast rather than right.
1021 		*/
1022 		lclptr->leapcnt = 0;		/* so, we're off a little */
1023 		lclptr->timecnt = 0;
1024 		lclptr->typecnt = 0;
1025 		lclptr->ttis[0].tt_isdst = 0;
1026 		lclptr->ttis[0].tt_gmtoff = 0;
1027 		lclptr->ttis[0].tt_abbrind = 0;
1028 		(void)strlcpy(lclptr->chars, gmt, sizeof(lclptr->chars));
1029 	} else if (tzload(name, lclptr) != 0)
1030 		if (name[0] == ':' || tzparse(name, lclptr, FALSE) != 0)
1031 			(void) gmtload(lclptr);
1032 	settzname();
1033 }
1034 
1035 void
1036 tzset P((void))
1037 {
1038 	rwlock_wrlock(&lcl_lock);
1039 	tzset_unlocked();
1040 	rwlock_unlock(&lcl_lock);
1041 }
1042 
1043 /*
1044 ** The easy way to behave "as if no library function calls" localtime
1045 ** is to not call it--so we drop its guts into "localsub", which can be
1046 ** freely called.  (And no, the PANS doesn't require the above behavior--
1047 ** but it *is* desirable.)
1048 **
1049 ** The unused offset argument is for the benefit of mktime variants.
1050 */
1051 
1052 /*ARGSUSED*/
1053 static void
1054 localsub(timep, offset, tmp)
1055 const time_t * const	timep;
1056 const long		offset;
1057 struct tm * const	tmp;
1058 {
1059 	register struct state *		sp;
1060 	register const struct ttinfo *	ttisp;
1061 	register int			i;
1062 	const time_t			t = *timep;
1063 
1064 	sp = lclptr;
1065 #ifdef ALL_STATE
1066 	if (sp == NULL) {
1067 		gmtsub(timep, offset, tmp);
1068 		return;
1069 	}
1070 #endif /* defined ALL_STATE */
1071 	if (sp->timecnt == 0 || t < sp->ats[0]) {
1072 		i = 0;
1073 		while (sp->ttis[i].tt_isdst)
1074 			if (++i >= sp->typecnt) {
1075 				i = 0;
1076 				break;
1077 			}
1078 	} else {
1079 		for (i = 1; i < sp->timecnt; ++i)
1080 			if (t < sp->ats[i])
1081 				break;
1082 		i = sp->types[i - 1];
1083 	}
1084 	ttisp = &sp->ttis[i];
1085 	/*
1086 	** To get (wrong) behavior that's compatible with System V Release 2.0
1087 	** you'd replace the statement below with
1088 	**	t += ttisp->tt_gmtoff;
1089 	**	timesub(&t, 0L, sp, tmp);
1090 	*/
1091 	timesub(&t, ttisp->tt_gmtoff, sp, tmp);
1092 	tmp->tm_isdst = ttisp->tt_isdst;
1093 	tzname[tmp->tm_isdst] = &sp->chars[ttisp->tt_abbrind];
1094 #ifdef TM_ZONE
1095 	tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
1096 #endif /* defined TM_ZONE */
1097 }
1098 
1099 struct tm *
1100 localtime(timep)
1101 const time_t * const	timep;
1102 {
1103 	rwlock_wrlock(&lcl_lock);
1104 	tzset_unlocked();
1105 	localsub(timep, 0L, &tm);
1106 	rwlock_unlock(&lcl_lock);
1107 	return &tm;
1108 }
1109 
1110 /*
1111 ** Re-entrant version of localtime.
1112 */
1113 
1114 struct tm *
1115 localtime_r(timep, tmp)
1116 const time_t * const	timep;
1117 struct tm *		tmp;
1118 {
1119 	rwlock_rdlock(&lcl_lock);
1120 	tzset_unlocked();
1121 	localsub(timep, 0L, tmp);
1122 	rwlock_unlock(&lcl_lock);
1123 	return tmp;
1124 }
1125 
1126 /*
1127 ** gmtsub is to gmtime as localsub is to localtime.
1128 */
1129 
1130 static void
1131 gmtsub(timep, offset, tmp)
1132 const time_t * const	timep;
1133 const long		offset;
1134 struct tm * const	tmp;
1135 {
1136 #ifdef _REENTRANT
1137 	static mutex_t gmt_mutex = MUTEX_INITIALIZER;
1138 #endif
1139 
1140 	mutex_lock(&gmt_mutex);
1141 	if (!gmt_is_set) {
1142 #ifdef ALL_STATE
1143 		int saveerrno;
1144 #endif
1145 		gmt_is_set = TRUE;
1146 #ifdef ALL_STATE
1147 		saveerrno = errno;
1148 		gmtptr = (struct state *) malloc(sizeof *gmtptr);
1149 		errno = saveerrno;
1150 		if (gmtptr != NULL)
1151 #endif /* defined ALL_STATE */
1152 			gmtload(gmtptr);
1153 	}
1154 	mutex_unlock(&gmt_mutex);
1155 	timesub(timep, offset, gmtptr, tmp);
1156 #ifdef TM_ZONE
1157 	/*
1158 	** Could get fancy here and deliver something such as
1159 	** "UTC+xxxx" or "UTC-xxxx" if offset is non-zero,
1160 	** but this is no time for a treasure hunt.
1161 	*/
1162 	if (offset != 0)
1163 		tmp->TM_ZONE = (__aconst char *)__UNCONST(wildabbr);
1164 	else {
1165 #ifdef ALL_STATE
1166 		if (gmtptr == NULL)
1167 			tmp->TM_ZONE = (__aconst char *)__UNCONST(gmt);
1168 		else	tmp->TM_ZONE = gmtptr->chars;
1169 #endif /* defined ALL_STATE */
1170 #ifndef ALL_STATE
1171 		tmp->TM_ZONE = gmtptr->chars;
1172 #endif /* State Farm */
1173 	}
1174 #endif /* defined TM_ZONE */
1175 }
1176 
1177 struct tm *
1178 gmtime(timep)
1179 const time_t * const	timep;
1180 {
1181 	gmtsub(timep, 0L, &tm);
1182 	return &tm;
1183 }
1184 
1185 /*
1186 ** Re-entrant version of gmtime.
1187 */
1188 
1189 struct tm *
1190 gmtime_r(timep, tmp)
1191 const time_t * const	timep;
1192 struct tm *		tmp;
1193 {
1194 	gmtsub(timep, 0L, tmp);
1195 	return tmp;
1196 }
1197 
1198 #ifdef STD_INSPIRED
1199 
1200 struct tm *
1201 offtime(timep, offset)
1202 const time_t * const	timep;
1203 const long		offset;
1204 {
1205 	gmtsub(timep, offset, &tm);
1206 	return &tm;
1207 }
1208 
1209 #endif /* defined STD_INSPIRED */
1210 
1211 static void
1212 timesub(timep, offset, sp, tmp)
1213 const time_t * const			timep;
1214 const long				offset;
1215 register const struct state * const	sp;
1216 register struct tm * const		tmp;
1217 {
1218 	register const struct lsinfo *	lp;
1219 	register long			days;
1220 	register long			rem;
1221 	register int			y;
1222 	register int			yleap;
1223 	register const int *		ip;
1224 	register long			corr;
1225 	register int			hit;
1226 	register int			i;
1227 
1228 	corr = 0;
1229 	hit = 0;
1230 #ifdef ALL_STATE
1231 	i = (sp == NULL) ? 0 : sp->leapcnt;
1232 #endif /* defined ALL_STATE */
1233 #ifndef ALL_STATE
1234 	i = sp->leapcnt;
1235 #endif /* State Farm */
1236 	while (--i >= 0) {
1237 		lp = &sp->lsis[i];
1238 		if (*timep >= lp->ls_trans) {
1239 			if (*timep == lp->ls_trans) {
1240 				hit = ((i == 0 && lp->ls_corr > 0) ||
1241 					lp->ls_corr > sp->lsis[i - 1].ls_corr);
1242 				if (hit)
1243 					while (i > 0 &&
1244 						sp->lsis[i].ls_trans ==
1245 						sp->lsis[i - 1].ls_trans + 1 &&
1246 						sp->lsis[i].ls_corr ==
1247 						sp->lsis[i - 1].ls_corr + 1) {
1248 							++hit;
1249 							--i;
1250 					}
1251 			}
1252 			corr = lp->ls_corr;
1253 			break;
1254 		}
1255 	}
1256 	days = *timep / SECSPERDAY;
1257 	rem = *timep % SECSPERDAY;
1258 #ifdef mc68k
1259 	if (*timep == 0x80000000) {
1260 		/*
1261 		** A 3B1 muffs the division on the most negative number.
1262 		*/
1263 		days = -24855;
1264 		rem = -11648;
1265 	}
1266 #endif /* defined mc68k */
1267 	rem += (offset - corr);
1268 	while (rem < 0) {
1269 		rem += SECSPERDAY;
1270 		--days;
1271 	}
1272 	while (rem >= SECSPERDAY) {
1273 		rem -= SECSPERDAY;
1274 		++days;
1275 	}
1276 	tmp->tm_hour = (int) (rem / SECSPERHOUR);
1277 	rem = rem % SECSPERHOUR;
1278 	tmp->tm_min = (int) (rem / SECSPERMIN);
1279 	/*
1280 	** A positive leap second requires a special
1281 	** representation.  This uses "... ??:59:60" et seq.
1282 	*/
1283 	tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
1284 	tmp->tm_wday = (int) ((EPOCH_WDAY + days) % DAYSPERWEEK);
1285 	if (tmp->tm_wday < 0)
1286 		tmp->tm_wday += DAYSPERWEEK;
1287 	y = EPOCH_YEAR;
1288 #define LEAPS_THRU_END_OF(y)	((y) / 4 - (y) / 100 + (y) / 400)
1289 	while (days < 0 || days >= (long) year_lengths[yleap = isleap(y)]) {
1290 		register int	newy;
1291 
1292 		newy = (int)(y + days / DAYSPERNYEAR);
1293 		if (days < 0)
1294 			--newy;
1295 		days -= (newy - y) * DAYSPERNYEAR +
1296 			LEAPS_THRU_END_OF(newy - 1) -
1297 			LEAPS_THRU_END_OF(y - 1);
1298 		y = newy;
1299 	}
1300 	tmp->tm_year = y - TM_YEAR_BASE;
1301 	tmp->tm_yday = (int) days;
1302 	ip = mon_lengths[yleap];
1303 	for (tmp->tm_mon = 0; days >= (long) ip[tmp->tm_mon]; ++(tmp->tm_mon))
1304 		days = days - (long) ip[tmp->tm_mon];
1305 	tmp->tm_mday = (int) (days + 1);
1306 	tmp->tm_isdst = 0;
1307 #ifdef TM_GMTOFF
1308 	tmp->TM_GMTOFF = offset;
1309 #endif /* defined TM_GMTOFF */
1310 }
1311 
1312 char *
1313 ctime(timep)
1314 const time_t * const	timep;
1315 {
1316 /*
1317 ** Section 4.12.3.2 of X3.159-1989 requires that
1318 **	The ctime function converts the calendar time pointed to by timer
1319 **	to local time in the form of a string.  It is equivalent to
1320 **		asctime(localtime(timer))
1321 */
1322 	return asctime(localtime(timep));
1323 }
1324 
1325 char *
1326 ctime_r(timep, buf)
1327 const time_t * const	timep;
1328 char *			buf;
1329 {
1330 	struct tm	tmp;
1331 
1332 	return asctime_r(localtime_r(timep, &tmp), buf);
1333 }
1334 
1335 /*
1336 ** Adapted from code provided by Robert Elz, who writes:
1337 **	The "best" way to do mktime I think is based on an idea of Bob
1338 **	Kridle's (so its said...) from a long time ago.
1339 **	[kridle@xinet.com as of 1996-01-16.]
1340 **	It does a binary search of the time_t space.  Since time_t's are
1341 **	just 32 bits, its a max of 32 iterations (even at 64 bits it
1342 **	would still be very reasonable).
1343 */
1344 
1345 #ifndef WRONG
1346 #define WRONG	(-1)
1347 #endif /* !defined WRONG */
1348 
1349 /*
1350 ** Simplified normalize logic courtesy Paul Eggert (eggert@twinsun.com).
1351 */
1352 
1353 static int
1354 increment_overflow(number, delta)
1355 int *	number;
1356 int	delta;
1357 {
1358 	int	number0;
1359 
1360 	number0 = *number;
1361 	*number += delta;
1362 	return (*number < number0) != (delta < 0);
1363 }
1364 
1365 static int
1366 normalize_overflow(tensptr, unitsptr, base)
1367 int * const	tensptr;
1368 int * const	unitsptr;
1369 const int	base;
1370 {
1371 	register int	tensdelta;
1372 
1373 	tensdelta = (*unitsptr >= 0) ?
1374 		(*unitsptr / base) :
1375 		(-1 - (-1 - *unitsptr) / base);
1376 	*unitsptr -= tensdelta * base;
1377 	return increment_overflow(tensptr, tensdelta);
1378 }
1379 
1380 static int
1381 tmcomp(atmp, btmp)
1382 register const struct tm * const atmp;
1383 register const struct tm * const btmp;
1384 {
1385 	register int	result;
1386 
1387 	if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
1388 		(result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
1389 		(result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
1390 		(result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
1391 		(result = (atmp->tm_min - btmp->tm_min)) == 0)
1392 			result = atmp->tm_sec - btmp->tm_sec;
1393 	return result;
1394 }
1395 
1396 static time_t
1397 time2sub(tmp, funcp, offset, okayp, do_norm_secs)
1398 struct tm * const	tmp;
1399 void (* const		funcp) P((const time_t*, long, struct tm*));
1400 const long		offset;
1401 int * const		okayp;
1402 const int		do_norm_secs;
1403 {
1404 	register const struct state *	sp;
1405 	register int			dir;
1406 	register int			bits;
1407 	register int			i, j ;
1408 	register int			saved_seconds;
1409 	time_t				newt;
1410 	time_t				t;
1411 	struct tm			yourtm, mytm;
1412 
1413 	*okayp = FALSE;
1414 	yourtm = *tmp;
1415 	if (do_norm_secs) {
1416 		if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
1417 			SECSPERMIN))
1418 				return WRONG;
1419 	}
1420 	if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
1421 		return WRONG;
1422 	if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
1423 		return WRONG;
1424 	if (normalize_overflow(&yourtm.tm_year, &yourtm.tm_mon, MONSPERYEAR))
1425 		return WRONG;
1426 	/*
1427 	** Turn yourtm.tm_year into an actual year number for now.
1428 	** It is converted back to an offset from TM_YEAR_BASE later.
1429 	*/
1430 	if (increment_overflow(&yourtm.tm_year, TM_YEAR_BASE))
1431 		return WRONG;
1432 	while (yourtm.tm_mday <= 0) {
1433 		if (increment_overflow(&yourtm.tm_year, -1))
1434 			return WRONG;
1435 		i = yourtm.tm_year + (1 < yourtm.tm_mon);
1436 		yourtm.tm_mday += year_lengths[isleap(i)];
1437 	}
1438 	while (yourtm.tm_mday > DAYSPERLYEAR) {
1439 		i = yourtm.tm_year + (1 < yourtm.tm_mon);
1440 		yourtm.tm_mday -= year_lengths[isleap(i)];
1441 		if (increment_overflow(&yourtm.tm_year, 1))
1442 			return WRONG;
1443 	}
1444 	for ( ; ; ) {
1445 		i = mon_lengths[isleap(yourtm.tm_year)][yourtm.tm_mon];
1446 		if (yourtm.tm_mday <= i)
1447 			break;
1448 		yourtm.tm_mday -= i;
1449 		if (++yourtm.tm_mon >= MONSPERYEAR) {
1450 			yourtm.tm_mon = 0;
1451 			if (increment_overflow(&yourtm.tm_year, 1))
1452 				return WRONG;
1453 		}
1454 	}
1455 	if (increment_overflow(&yourtm.tm_year, -TM_YEAR_BASE))
1456 		return WRONG;
1457 	if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
1458 		saved_seconds = 0;
1459 	else if (yourtm.tm_year + TM_YEAR_BASE < EPOCH_YEAR) {
1460 		/*
1461 		** We can't set tm_sec to 0, because that might push the
1462 		** time below the minimum representable time.
1463 		** Set tm_sec to 59 instead.
1464 		** This assumes that the minimum representable time is
1465 		** not in the same minute that a leap second was deleted from,
1466 		** which is a safer assumption than using 58 would be.
1467 		*/
1468 		if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
1469 			return WRONG;
1470 		saved_seconds = yourtm.tm_sec;
1471 		yourtm.tm_sec = SECSPERMIN - 1;
1472 	} else {
1473 		saved_seconds = yourtm.tm_sec;
1474 		yourtm.tm_sec = 0;
1475 	}
1476 	/*
1477 	** Divide the search space in half
1478 	** (this works whether time_t is signed or unsigned).
1479 	*/
1480 	bits = TYPE_BIT(time_t) - 1;
1481 	/*
1482 	** If time_t is signed, then 0 is just above the median,
1483 	** assuming two's complement arithmetic.
1484 	** If time_t is unsigned, then (1 << bits) is just above the median.
1485 	*/
1486 	/*CONSTCOND*/
1487 	t = TYPE_SIGNED(time_t) ? 0 : (((time_t) 1) << bits);
1488 	for ( ; ; ) {
1489 		(*funcp)(&t, offset, &mytm);
1490 		dir = tmcomp(&mytm, &yourtm);
1491 		if (dir != 0) {
1492 			if (bits-- < 0)
1493 				return WRONG;
1494 			if (bits < 0)
1495 				--t; /* may be needed if new t is minimal */
1496 			else if (dir > 0)
1497 				t -= ((time_t) 1) << bits;
1498 			else	t += ((time_t) 1) << bits;
1499 			continue;
1500 		}
1501 		if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
1502 			break;
1503 		/*
1504 		** Right time, wrong type.
1505 		** Hunt for right time, right type.
1506 		** It's okay to guess wrong since the guess
1507 		** gets checked.
1508 		*/
1509 		/*
1510 		** The (void *) casts are the benefit of SunOS 3.3 on Sun 2's.
1511 		*/
1512 		sp = (const struct state *)
1513 			(((void *) funcp == (void *) localsub) ?
1514 			lclptr : gmtptr);
1515 #ifdef ALL_STATE
1516 		if (sp == NULL)
1517 			return WRONG;
1518 #endif /* defined ALL_STATE */
1519 		for (i = sp->typecnt - 1; i >= 0; --i) {
1520 			if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
1521 				continue;
1522 			for (j = sp->typecnt - 1; j >= 0; --j) {
1523 				if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
1524 					continue;
1525 				newt = t + sp->ttis[j].tt_gmtoff -
1526 					sp->ttis[i].tt_gmtoff;
1527 				(*funcp)(&newt, offset, &mytm);
1528 				if (tmcomp(&mytm, &yourtm) != 0)
1529 					continue;
1530 				if (mytm.tm_isdst != yourtm.tm_isdst)
1531 					continue;
1532 				/*
1533 				** We have a match.
1534 				*/
1535 				t = newt;
1536 				goto label;
1537 			}
1538 		}
1539 		return WRONG;
1540 	}
1541 label:
1542 	newt = t + saved_seconds;
1543 	if ((newt < t) != (saved_seconds < 0))
1544 		return WRONG;
1545 	t = newt;
1546 	(*funcp)(&t, offset, tmp);
1547 	*okayp = TRUE;
1548 	return t;
1549 }
1550 
1551 static time_t
1552 time2(tmp, funcp, offset, okayp)
1553 struct tm * const	tmp;
1554 void (* const		funcp) P((const time_t*, long, struct tm*));
1555 const long		offset;
1556 int * const		okayp;
1557 {
1558 	time_t	t;
1559 
1560 	/*
1561 	** First try without normalization of seconds
1562 	** (in case tm_sec contains a value associated with a leap second).
1563 	** If that fails, try with normalization of seconds.
1564 	*/
1565 	t = time2sub(tmp, funcp, offset, okayp, FALSE);
1566 	return *okayp ? t : time2sub(tmp, funcp, offset, okayp, TRUE);
1567 }
1568 
1569 static time_t
1570 time1(tmp, funcp, offset)
1571 struct tm * const	tmp;
1572 void (* const		funcp) P((const time_t *, long, struct tm *));
1573 const long		offset;
1574 {
1575 	register time_t			t;
1576 	register const struct state *	sp;
1577 	register int			samei, otheri;
1578 	register int			sameind, otherind;
1579 	register int			i;
1580 	register int			nseen;
1581 	int				seen[TZ_MAX_TYPES];
1582 	int				types[TZ_MAX_TYPES];
1583 	int				okay;
1584 
1585 	if (tmp->tm_isdst > 1)
1586 		tmp->tm_isdst = 1;
1587 	t = time2(tmp, funcp, offset, &okay);
1588 #ifdef PCTS
1589 	/*
1590 	** PCTS code courtesy Grant Sullivan (grant@osf.org).
1591 	*/
1592 	if (okay)
1593 		return t;
1594 	if (tmp->tm_isdst < 0)
1595 		tmp->tm_isdst = 0;	/* reset to std and try again */
1596 #endif /* defined PCTS */
1597 #ifndef PCTS
1598 	if (okay || tmp->tm_isdst < 0)
1599 		return t;
1600 #endif /* !defined PCTS */
1601 	/*
1602 	** We're supposed to assume that somebody took a time of one type
1603 	** and did some math on it that yielded a "struct tm" that's bad.
1604 	** We try to divine the type they started from and adjust to the
1605 	** type they need.
1606 	*/
1607 	/*
1608 	** The (void *) casts are the benefit of SunOS 3.3 on Sun 2's.
1609 	*/
1610 	sp = (const struct state *) (((void *) funcp == (void *) localsub) ?
1611 		lclptr : gmtptr);
1612 #ifdef ALL_STATE
1613 	if (sp == NULL)
1614 		return WRONG;
1615 #endif /* defined ALL_STATE */
1616 	for (i = 0; i < sp->typecnt; ++i)
1617 		seen[i] = FALSE;
1618 	nseen = 0;
1619 	for (i = sp->timecnt - 1; i >= 0; --i)
1620 		if (!seen[sp->types[i]]) {
1621 			seen[sp->types[i]] = TRUE;
1622 			types[nseen++] = sp->types[i];
1623 		}
1624 	for (sameind = 0; sameind < nseen; ++sameind) {
1625 		samei = types[sameind];
1626 		if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
1627 			continue;
1628 		for (otherind = 0; otherind < nseen; ++otherind) {
1629 			otheri = types[otherind];
1630 			if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
1631 				continue;
1632 			tmp->tm_sec += (int)(sp->ttis[otheri].tt_gmtoff -
1633 					sp->ttis[samei].tt_gmtoff);
1634 			tmp->tm_isdst = !tmp->tm_isdst;
1635 			t = time2(tmp, funcp, offset, &okay);
1636 			if (okay)
1637 				return t;
1638 			tmp->tm_sec -= (int)(sp->ttis[otheri].tt_gmtoff -
1639 					sp->ttis[samei].tt_gmtoff);
1640 			tmp->tm_isdst = !tmp->tm_isdst;
1641 		}
1642 	}
1643 	return WRONG;
1644 }
1645 
1646 time_t
1647 mktime(tmp)
1648 struct tm * const	tmp;
1649 {
1650 	time_t result;
1651 
1652 	rwlock_wrlock(&lcl_lock);
1653 	tzset_unlocked();
1654 	result = time1(tmp, localsub, 0L);
1655 	rwlock_unlock(&lcl_lock);
1656 	return (result);
1657 }
1658 
1659 #ifdef STD_INSPIRED
1660 
1661 time_t
1662 timelocal(tmp)
1663 struct tm * const	tmp;
1664 {
1665 	tmp->tm_isdst = -1;	/* in case it wasn't initialized */
1666 	return mktime(tmp);
1667 }
1668 
1669 time_t
1670 timegm(tmp)
1671 struct tm * const	tmp;
1672 {
1673 	tmp->tm_isdst = 0;
1674 	return time1(tmp, gmtsub, 0L);
1675 }
1676 
1677 time_t
1678 timeoff(tmp, offset)
1679 struct tm * const	tmp;
1680 const long		offset;
1681 {
1682 	tmp->tm_isdst = 0;
1683 	return time1(tmp, gmtsub, offset);
1684 }
1685 
1686 #endif /* defined STD_INSPIRED */
1687 
1688 #ifdef CMUCS
1689 
1690 /*
1691 ** The following is supplied for compatibility with
1692 ** previous versions of the CMUCS runtime library.
1693 */
1694 
1695 long
1696 gtime(tmp)
1697 struct tm * const	tmp;
1698 {
1699 	const time_t	t = mktime(tmp);
1700 
1701 	if (t == WRONG)
1702 		return -1;
1703 	return t;
1704 }
1705 
1706 #endif /* defined CMUCS */
1707 
1708 /*
1709 ** XXX--is the below the right way to conditionalize??
1710 */
1711 
1712 #ifdef STD_INSPIRED
1713 
1714 /*
1715 ** IEEE Std 1003.1-1988 (POSIX) legislates that 536457599
1716 ** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
1717 ** is not the case if we are accounting for leap seconds.
1718 ** So, we provide the following conversion routines for use
1719 ** when exchanging timestamps with POSIX conforming systems.
1720 */
1721 
1722 static long
1723 leapcorr(timep)
1724 time_t *	timep;
1725 {
1726 	register struct state *		sp;
1727 	register struct lsinfo *	lp;
1728 	register int			i;
1729 
1730 	sp = lclptr;
1731 	i = sp->leapcnt;
1732 	while (--i >= 0) {
1733 		lp = &sp->lsis[i];
1734 		if (*timep >= lp->ls_trans)
1735 			return lp->ls_corr;
1736 	}
1737 	return 0;
1738 }
1739 
1740 time_t
1741 time2posix(t)
1742 time_t	t;
1743 {
1744 	time_t result;
1745 
1746 	rwlock_wrlock(&lcl_lock);
1747 	tzset_unlocked();
1748 	result = t - leapcorr(&t);
1749 	rwlock_unlock(&lcl_lock);
1750 	return (result);
1751 }
1752 
1753 time_t
1754 posix2time(t)
1755 time_t	t;
1756 {
1757 	time_t	x;
1758 	time_t	y;
1759 
1760 	rwlock_wrlock(&lcl_lock);
1761 	tzset_unlocked();
1762 	/*
1763 	** For a positive leap second hit, the result
1764 	** is not unique.  For a negative leap second
1765 	** hit, the corresponding time doesn't exist,
1766 	** so we return an adjacent second.
1767 	*/
1768 	x = t + leapcorr(&t);
1769 	y = x - leapcorr(&x);
1770 	if (y < t) {
1771 		do {
1772 			x++;
1773 			y = x - leapcorr(&x);
1774 		} while (y < t);
1775 		if (t != y) {
1776 			rwlock_unlock(&lcl_lock);
1777 			return x - 1;
1778 		}
1779 	} else if (y > t) {
1780 		do {
1781 			--x;
1782 			y = x - leapcorr(&x);
1783 		} while (y > t);
1784 		if (t != y) {
1785 			rwlock_unlock(&lcl_lock);
1786 			return x + 1;
1787 		}
1788 	}
1789 	rwlock_unlock(&lcl_lock);
1790 	return x;
1791 }
1792 
1793 #endif /* defined STD_INSPIRED */
1794