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