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