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