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