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