localtime.c revision 130461
18871Srgrimes/*
21558Srgrimes** This file is in the public domain, so clarified as of
31558Srgrimes** 1996-06-05 by Arthur David Olson (arthur_david_olson@nih.gov).
41558Srgrimes*/
51558Srgrimes
61558Srgrimes#include <sys/cdefs.h>
71558Srgrimes#ifndef lint
81558Srgrimes#ifndef NOID
91558Srgrimesstatic char	elsieid[] __unused = "@(#)localtime.c	7.78";
101558Srgrimes#endif /* !defined NOID */
111558Srgrimes#endif /* !defined lint */
121558Srgrimes__FBSDID("$FreeBSD: head/lib/libc/stdtime/localtime.c 130461 2004-06-14 10:31:52Z stefanf $");
131558Srgrimes
141558Srgrimes/*
151558Srgrimes** Leap second handling from Bradley White (bww@k.gp.cs.cmu.edu).
161558Srgrimes** POSIX-style TZ environment variable handling from Guy Harris
171558Srgrimes** (guy@auspex.com).
181558Srgrimes*/
191558Srgrimes
201558Srgrimes/*LINTLIBRARY*/
211558Srgrimes
221558Srgrimes#include "namespace.h"
231558Srgrimes#include <sys/types.h>
241558Srgrimes#include <sys/stat.h>
251558Srgrimes#include <fcntl.h>
261558Srgrimes#include <pthread.h>
271558Srgrimes#include "private.h"
281558Srgrimes#include "un-namespace.h"
291558Srgrimes
301558Srgrimes#include "tzfile.h"
311558Srgrimes
321558Srgrimes#include "libc_private.h"
331558Srgrimes
341558Srgrimes#define	_MUTEX_LOCK(x)		if (__isthreaded) _pthread_mutex_lock(x)
3541477Sjulian#define	_MUTEX_UNLOCK(x)	if (__isthreaded) _pthread_mutex_unlock(x)
3623675Speter
3741477Sjulian/*
3841477Sjulian** SunOS 4.1.1 headers lack O_BINARY.
3950476Speter*/
401558Srgrimes
411558Srgrimes#ifdef O_BINARY
421558Srgrimes#define OPEN_MODE	(O_RDONLY | O_BINARY)
4362668Smckusick#endif /* defined O_BINARY */
4474556Smckusick#ifndef O_BINARY
4523675Speter#define OPEN_MODE	O_RDONLY
461558Srgrimes#endif /* !defined O_BINARY */
471558Srgrimes
481558Srgrimes#ifndef WILDABBR
4923675Speter/*
5023675Speter** Someone might make incorrect use of a time zone abbreviation:
51101037Smux**	1.	They might reference tzname[0] before calling tzset (explicitly
521558Srgrimes**		or implicitly).
5323675Speter**	2.	They might reference tzname[1] before calling tzset (explicitly
541558Srgrimes**		or implicitly).
551558Srgrimes**	3.	They might reference tzname[1] after setting to a time zone
5698542Smckusick**		in which Daylight Saving Time is never observed.
5798542Smckusick**	4.	They might reference tzname[0] after setting to a time zone
5841474Sjulian**		in which Standard Time is never observed.
591558Srgrimes**	5.	They might reference tm.TM_ZONE after calling offtime.
6092839Simp** What's best to do in the above cases is open to debate;
617585Sbde** for now, we just set things up so that in any of the five cases
627585Sbde** WILDABBR is used.  Another possibility:  initialize tzname[0] to the
6392839Simp** string "tzname[0] used before set", and similarly for the other cases.
641558Srgrimes** And another:  initialize tzname[0] to "ERA", with an explanation in the
6541474Sjulian** manual page of what this "time zone abbreviation" means (doing this so
661558Srgrimes** that tzname[0] has the "normal" length of three characters).
6798542Smckusick*/
6898542Smckusick#define WILDABBR	"   "
6998542Smckusick#endif /* !defined WILDABBR */
7098542Smckusick
711558Srgrimesstatic char		wildabbr[] = "WILDABBR";
721558Srgrimes
73102231Strhodes/*
741558Srgrimes * In June 2004 it was decided UTC was a more appropriate default time
751558Srgrimes * zone than GMT.
761558Srgrimes */
771558Srgrimes
781558Srgrimesstatic const char	gmt[] = "UTC";
791558Srgrimes
801558Srgrimes/*
811558Srgrimes** The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
821558Srgrimes** We default to US rules as of 1999-08-17.
831558Srgrimes** POSIX 1003.1 section 8.1.1 says that the default DST rules are
8469800Stomsoft** implementation dependent; for historical reasons, US rules are a
8569800Stomsoft** common default.
8669800Stomsoft*/
8769800Stomsoft#ifndef TZDEFRULESTRING
8869800Stomsoft#define TZDEFRULESTRING ",M4.1.0,M10.5.0"
891558Srgrimes#endif /* !defined TZDEFDST */
901558Srgrimes
911558Srgrimesstruct ttinfo {				/* time type information */
9223675Speter	long		tt_gmtoff;	/* UTC offset in seconds */
931558Srgrimes	int		tt_isdst;	/* used to set tm_isdst */
941558Srgrimes	int		tt_abbrind;	/* abbreviation list index */
951558Srgrimes	int		tt_ttisstd;	/* TRUE if transition is std time */
9641474Sjulian	int		tt_ttisgmt;	/* TRUE if transition is UTC */
9741474Sjulian};
9898542Smckusick
9998542Smckusickstruct lsinfo {				/* leap second information */
10098542Smckusick	time_t		ls_trans;	/* transition time */
10198542Smckusick	long		ls_corr;	/* correction to apply */
10298542Smckusick};
10370050Siedowse
10470050Siedowse#define BIGGEST(a, b)	(((a) > (b)) ? (a) : (b))
10570050Siedowse
10670050Siedowse#ifdef TZNAME_MAX
10770050Siedowse#define MY_TZNAME_MAX	TZNAME_MAX
10870050Siedowse#endif /* defined TZNAME_MAX */
10941474Sjulian#ifndef TZNAME_MAX
11041474Sjulian#define MY_TZNAME_MAX	255
11141474Sjulian#endif /* !defined TZNAME_MAX */
11241474Sjulian
11341474Sjulianstruct state {
11441474Sjulian	int		leapcnt;
11541474Sjulian	int		timecnt;
11641474Sjulian	int		typecnt;
11741474Sjulian	int		charcnt;
11841474Sjulian	time_t		ats[TZ_MAX_TIMES];
11998542Smckusick	unsigned char	types[TZ_MAX_TIMES];
12041474Sjulian	struct ttinfo	ttis[TZ_MAX_TYPES];
12141474Sjulian	char		chars[BIGGEST(BIGGEST(TZ_MAX_CHARS + 1, sizeof gmt),
12241474Sjulian				(2 * (MY_TZNAME_MAX + 1)))];
12341474Sjulian	struct lsinfo	lsis[TZ_MAX_LEAPS];
12441474Sjulian};
12541474Sjulian
12641474Sjulianstruct rule {
12741474Sjulian	int		r_type;		/* type of rule--see below */
12841474Sjulian	int		r_day;		/* day number of rule */
12941474Sjulian	int		r_week;		/* week number of rule */
13041474Sjulian	int		r_mon;		/* month number of rule */
13141474Sjulian	long		r_time;		/* transition time of rule */
13241474Sjulian};
13341474Sjulian
13441474Sjulian#define JULIAN_DAY		0	/* Jn - Julian day */
13541474Sjulian#define DAY_OF_YEAR		1	/* n - day of year */
13641474Sjulian#define MONTH_NTH_DAY_OF_WEEK	2	/* Mm.n.d - month, week, day of week */
13741474Sjulian
13841474Sjulian/*
13941474Sjulian** Prototypes for static functions.
14041474Sjulian*/
14141474Sjulian
14241474Sjulianstatic long		detzcode(const char * codep);
14341474Sjulianstatic const char *	getzname(const char * strp);
14441474Sjulianstatic const char *	getnum(const char * strp, int * nump, int min,
14541474Sjulian				int max);
14641474Sjulianstatic const char *	getsecs(const char * strp, long * secsp);
14741474Sjulianstatic const char *	getoffset(const char * strp, long * offsetp);
14841474Sjulianstatic const char *	getrule(const char * strp, struct rule * rulep);
14941474Sjulianstatic void		gmtload(struct state * sp);
15041474Sjulianstatic void		gmtsub(const time_t * timep, long offset,
15141474Sjulian				struct tm * tmp);
1521558Srgrimesstatic void		localsub(const time_t * timep, long offset,
15341474Sjulian				struct tm * tmp);
1541558Srgrimesstatic int		increment_overflow(int * number, int delta);
1551558Srgrimesstatic int		normalize_overflow(int * tensptr, int * unitsptr,
15641474Sjulian				int base);
15741474Sjulianstatic void		settzname(void);
15841474Sjulianstatic time_t		time1(struct tm * tmp,
15941474Sjulian				void(*funcp) (const time_t *,
16041474Sjulian				long, struct tm *),
16141474Sjulian				long offset);
16241474Sjulianstatic time_t		time2(struct tm *tmp,
16341474Sjulian				void(*funcp) (const time_t *,
16441474Sjulian				long, struct tm*),
16598542Smckusick				long offset, int * okayp);
16641474Sjulianstatic time_t		time2sub(struct tm *tmp,
16798542Smckusick				void(*funcp) (const time_t *,
16898542Smckusick				long, struct tm*),
16941474Sjulian				long offset, int * okayp, int do_norm_secs);
17041474Sjulianstatic void		timesub(const time_t * timep, long offset,
17141474Sjulian				const struct state * sp, struct tm * tmp);
17241474Sjulianstatic int		tmcomp(const struct tm * atmp,
17341474Sjulian				const struct tm * btmp);
17441474Sjulianstatic time_t		transtime(time_t janfirst, int year,
17541474Sjulian				const struct rule * rulep, long offset);
17641474Sjulianstatic int		tzload(const char * name, struct state * sp);
17741474Sjulianstatic int		tzparse(const char * name, struct state * sp,
17841474Sjulian				int lastditch);
17941474Sjulian
18041474Sjulian#ifdef ALL_STATE
18141474Sjulianstatic struct state *	lclptr;
1821558Srgrimesstatic struct state *	gmtptr;
1831558Srgrimes#endif /* defined ALL_STATE */
1841558Srgrimes
1851558Srgrimes#ifndef ALL_STATE
18623675Speterstatic struct state	lclmem;
18792839Simpstatic struct state	gmtmem;
1881558Srgrimes#define lclptr		(&lclmem)
18998542Smckusick#define gmtptr		(&gmtmem)
1901558Srgrimes#endif /* State Farm */
19198542Smckusick
19298542Smckusick#ifndef TZ_STRLEN_MAX
1931558Srgrimes#define TZ_STRLEN_MAX 255
19498542Smckusick#endif /* !defined TZ_STRLEN_MAX */
1951558Srgrimes
1961558Srgrimesstatic char		lcl_TZname[TZ_STRLEN_MAX + 1];
19798542Smckusickstatic int		lcl_is_set;
1981558Srgrimesstatic int		gmt_is_set;
19998542Smckusickstatic pthread_mutex_t	lcl_mutex = PTHREAD_MUTEX_INITIALIZER;
20098542Smckusickstatic pthread_mutex_t	gmt_mutex = PTHREAD_MUTEX_INITIALIZER;
20198542Smckusick
20298542Smckusickchar *			tzname[2] = {
20398542Smckusick	wildabbr,
20498542Smckusick	wildabbr
20598542Smckusick};
20698542Smckusick
20798542Smckusick/*
20898542Smckusick** Section 4.12.3 of X3.159-1989 requires that
20998542Smckusick**	Except for the strftime function, these functions [asctime,
21098542Smckusick**	ctime, gmtime, localtime] return values in one of two static
21186514Siedowse**	objects: a broken-down time structure and an array of char.
21286514Siedowse** Thanks to Paul Eggert (eggert@twinsun.com) for noting this.
2131558Srgrimes*/
2141558Srgrimes
2151558Srgrimesstatic struct tm	tm;
2161558Srgrimes
2171558Srgrimes#ifdef USG_COMPAT
2181558Srgrimestime_t			timezone = 0;
21941474Sjulianint			daylight = 0;
2201558Srgrimes#endif /* defined USG_COMPAT */
2211558Srgrimes
2221558Srgrimes#ifdef ALTZONE
22371884Siedowsetime_t			altzone = 0;
22498888Siedowse#endif /* defined ALTZONE */
22598888Siedowse
22698888Siedowsestatic long
22798888Siedowsedetzcode(codep)
22898542Smckusickconst char * const	codep;
22998542Smckusick{
23098542Smckusick	long	result;
2311558Srgrimes	int	i;
232101037Smux
2331558Srgrimes	result = (codep[0] & 0x80) ? ~0L : 0L;
2341558Srgrimes	for (i = 0; i < 4; ++i)
2351558Srgrimes		result = (result << 8) | (codep[i] & 0xff);
2361558Srgrimes	return result;
23798542Smckusick}
23898542Smckusick
2391558Srgrimesstatic void
2401558Srgrimessettzname(void)
24163003Smckusick{
24298542Smckusick	struct state * 	sp = lclptr;
24363003Smckusick	int			i;
244101037Smux
245101037Smux	tzname[0] = wildabbr;
24663003Smckusick	tzname[1] = wildabbr;
24763003Smckusick#ifdef USG_COMPAT
24898542Smckusick	daylight = 0;
24998542Smckusick	timezone = 0;
25072525Stegge#endif /* defined USG_COMPAT */
25172525Stegge#ifdef ALTZONE
25272525Stegge	altzone = 0;
25372525Stegge#endif /* defined ALTZONE */
25498542Smckusick#ifdef ALL_STATE
2551558Srgrimes	if (sp == NULL) {
2561558Srgrimes		tzname[0] = tzname[1] = gmt;
257101037Smux		return;
258101037Smux	}
2591558Srgrimes#endif /* defined ALL_STATE */
2601558Srgrimes	for (i = 0; i < sp->typecnt; ++i) {
2611558Srgrimes		const struct ttinfo * const	ttisp = &sp->ttis[i];
2621558Srgrimes
2631558Srgrimes		tzname[ttisp->tt_isdst] =
2641558Srgrimes			&sp->chars[ttisp->tt_abbrind];
2651558Srgrimes#ifdef USG_COMPAT
2661558Srgrimes		if (ttisp->tt_isdst)
2671558Srgrimes			daylight = 1;
26898542Smckusick		if (i == 0 || !ttisp->tt_isdst)
26998542Smckusick			timezone = -(ttisp->tt_gmtoff);
27098542Smckusick#endif /* defined USG_COMPAT */
27198542Smckusick#ifdef ALTZONE
27298542Smckusick		if (i == 0 || ttisp->tt_isdst)
27398542Smckusick			altzone = -(ttisp->tt_gmtoff);
27498542Smckusick#endif /* defined ALTZONE */
2751558Srgrimes	}
2761558Srgrimes	/*
2771558Srgrimes	** And to get the latest zone names into tzname. . .
2781558Srgrimes	*/
2791558Srgrimes	for (i = 0; i < sp->timecnt; ++i) {
2801558Srgrimes		const struct ttinfo * const	ttisp =
2811558Srgrimes							&sp->ttis[
2821558Srgrimes								sp->types[i]];
28398879Siedowse
28498542Smckusick		tzname[ttisp->tt_isdst] =
2851558Srgrimes			&sp->chars[ttisp->tt_abbrind];
286101037Smux	}
287101037Smux}
2881558Srgrimes
2891558Srgrimesstatic int
2901558Srgrimestzload(name, sp)
2911558Srgrimesconst char *		name;
2921558Srgrimesstruct state * const	sp;
29398542Smckusick{
2941558Srgrimes	const char *	p;
295101037Smux	int		i;
296101037Smux	int		fid;
2971558Srgrimes
2981558Srgrimes	/* XXX The following is from OpenBSD, and I'm not sure it is correct */
2991558Srgrimes	if (name != NULL && issetugid() != 0)
3001558Srgrimes		if ((name[0] == ':' && name[1] == '/') ||
3011558Srgrimes		    name[0] == '/' || strchr(name, '.'))
30298542Smckusick			name = NULL;
30398542Smckusick	if (name == NULL && (name = TZDEFAULT) == NULL)
3041558Srgrimes		return -1;
3051558Srgrimes	{
3061558Srgrimes		int	doaccess;
30734266Sjulian		struct stat	stab;
30834266Sjulian		/*
30923675Speter		** Section 4.9.1 of the C standard says that
31034266Sjulian		** "FILENAME_MAX expands to an integral constant expression
3111558Srgrimes		** that is the size needed for an array of char large enough
3121558Srgrimes		** to hold the longest file name string that the implementation
3131558Srgrimes		** guarantees can be opened."
3141558Srgrimes		*/
3151558Srgrimes		char		fullname[FILENAME_MAX + 1];
3161558Srgrimes
3171558Srgrimes		if (name[0] == ':')
31898542Smckusick			++name;
31941474Sjulian		doaccess = name[0] == '/';
3201558Srgrimes		if (!doaccess) {
32141474Sjulian			if ((p = TZDIR) == NULL)
3221558Srgrimes				return -1;
32341474Sjulian			if ((strlen(p) + 1 + strlen(name) + 1) >= sizeof fullname)
3241558Srgrimes				return -1;
32541474Sjulian			(void) strcpy(fullname, p);
32641474Sjulian			(void) strcat(fullname, "/");
3271558Srgrimes			(void) strcat(fullname, name);
3281558Srgrimes			/*
32998542Smckusick			** Set doaccess if '.' (as in "../") shows up in name.
33062668Smckusick			*/
33162668Smckusick			if (strchr(name, '.') != NULL)
33262668Smckusick				doaccess = TRUE;
3331558Srgrimes			name = fullname;
334103398Sphk		}
335103398Sphk		if (doaccess && access(name, R_OK) != 0)
3361558Srgrimes		     	return -1;
33798542Smckusick		if ((fid = _open(name, OPEN_MODE)) == -1)
338101037Smux			return -1;
339101037Smux		if ((_fstat(fid, &stab) < 0) || !S_ISREG(stab.st_mode)) {
340101037Smux			_close(fid);
3411558Srgrimes			return -1;
3421558Srgrimes		}
3431558Srgrimes	}
3441558Srgrimes	{
34574556Smckusick		struct tzhead *	tzhp;
34674556Smckusick		union {
34798542Smckusick			struct tzhead	tzhead;
34874556Smckusick			char		buf[sizeof *sp + sizeof *tzhp];
34974556Smckusick		} u;
35074556Smckusick		int		ttisstdcnt;
35198542Smckusick		int		ttisgmtcnt;
35274556Smckusick
353101037Smux		i = _read(fid, u.buf, sizeof u.buf);
354101037Smux		if (_close(fid) != 0)
35574556Smckusick			return -1;
35674556Smckusick		ttisstdcnt = (int) detzcode(u.tzhead.tzh_ttisstdcnt);
35774556Smckusick		ttisgmtcnt = (int) detzcode(u.tzhead.tzh_ttisgmtcnt);
35874556Smckusick		sp->leapcnt = (int) detzcode(u.tzhead.tzh_leapcnt);
3591558Srgrimes		sp->timecnt = (int) detzcode(u.tzhead.tzh_timecnt);
3601558Srgrimes		sp->typecnt = (int) detzcode(u.tzhead.tzh_typecnt);
3611558Srgrimes		sp->charcnt = (int) detzcode(u.tzhead.tzh_charcnt);
36286514Siedowse		p = u.tzhead.tzh_charcnt + sizeof u.tzhead.tzh_charcnt;
36341474Sjulian		if (sp->leapcnt < 0 || sp->leapcnt > TZ_MAX_LEAPS ||
3641558Srgrimes			sp->typecnt <= 0 || sp->typecnt > TZ_MAX_TYPES ||
36541474Sjulian			sp->timecnt < 0 || sp->timecnt > TZ_MAX_TIMES ||
3661558Srgrimes			sp->charcnt < 0 || sp->charcnt > TZ_MAX_CHARS ||
3671558Srgrimes			(ttisstdcnt != sp->typecnt && ttisstdcnt != 0) ||
3681558Srgrimes			(ttisgmtcnt != sp->typecnt && ttisgmtcnt != 0))
3691558Srgrimes				return -1;
3701558Srgrimes		if (i - (p - u.buf) < sp->timecnt * 4 +	/* ats */
3711558Srgrimes			sp->timecnt +			/* types */
3727585Sbde			sp->typecnt * (4 + 2) +		/* ttinfos */
37392839Simp			sp->charcnt +			/* chars */
3741558Srgrimes			sp->leapcnt * (4 + 4) +		/* lsinfos */
3751558Srgrimes			ttisstdcnt +			/* ttisstds */
3761558Srgrimes			ttisgmtcnt)			/* ttisgmts */
37798542Smckusick				return -1;
37892806Sobrien		for (i = 0; i < sp->timecnt; ++i) {
3791558Srgrimes			sp->ats[i] = detzcode(p);
3801558Srgrimes			p += 4;
38162668Smckusick		}
38262668Smckusick		for (i = 0; i < sp->timecnt; ++i) {
38362668Smckusick			sp->types[i] = (unsigned char) *p++;
38462668Smckusick			if (sp->types[i] >= sp->typecnt)
38562668Smckusick				return -1;
38662668Smckusick		}
38762668Smckusick		for (i = 0; i < sp->typecnt; ++i) {
38862668Smckusick			struct ttinfo *	ttisp;
38962668Smckusick
39062668Smckusick			ttisp = &sp->ttis[i];
39162668Smckusick			ttisp->tt_gmtoff = detzcode(p);
39262668Smckusick			p += 4;
39362668Smckusick			ttisp->tt_isdst = (unsigned char) *p++;
39462668Smckusick			if (ttisp->tt_isdst != 0 && ttisp->tt_isdst != 1)
39562668Smckusick				return -1;
3961558Srgrimes			ttisp->tt_abbrind = (unsigned char) *p++;
3971558Srgrimes			if (ttisp->tt_abbrind < 0 ||
3981558Srgrimes				ttisp->tt_abbrind > sp->charcnt)
3991558Srgrimes					return -1;
40086514Siedowse		}
4011558Srgrimes		for (i = 0; i < sp->charcnt; ++i)
4021558Srgrimes			sp->chars[i] = *p++;
40334266Sjulian		sp->chars[i] = '\0';	/* ensure '\0' at end */
40434266Sjulian		for (i = 0; i < sp->leapcnt; ++i) {
40523675Speter			struct lsinfo *	lsisp;
40634266Sjulian
4071558Srgrimes			lsisp = &sp->lsis[i];
4081558Srgrimes			lsisp->ls_trans = detzcode(p);
4091558Srgrimes			p += 4;
4101558Srgrimes			lsisp->ls_corr = detzcode(p);
4111558Srgrimes			p += 4;
4121558Srgrimes		}
4131558Srgrimes		for (i = 0; i < sp->typecnt; ++i) {
4141558Srgrimes			struct ttinfo *	ttisp;
4151558Srgrimes
4161558Srgrimes			ttisp = &sp->ttis[i];
4171558Srgrimes			if (ttisstdcnt == 0)
4181558Srgrimes				ttisp->tt_ttisstd = FALSE;
4191558Srgrimes			else {
42086514Siedowse				ttisp->tt_ttisstd = *p++;
4211558Srgrimes				if (ttisp->tt_ttisstd != TRUE &&
4221558Srgrimes					ttisp->tt_ttisstd != FALSE)
42334266Sjulian						return -1;
42434266Sjulian			}
42523675Speter		}
42634266Sjulian		for (i = 0; i < sp->typecnt; ++i) {
4271558Srgrimes			struct ttinfo *	ttisp;
4281558Srgrimes
4291558Srgrimes			ttisp = &sp->ttis[i];
4301558Srgrimes			if (ttisgmtcnt == 0)
4311558Srgrimes				ttisp->tt_ttisgmt = FALSE;
43234266Sjulian			else {
43334266Sjulian				ttisp->tt_ttisgmt = *p++;
43423675Speter				if (ttisp->tt_ttisgmt != TRUE &&
43534266Sjulian					ttisp->tt_ttisgmt != FALSE)
4361558Srgrimes						return -1;
4371558Srgrimes			}
4381558Srgrimes		}
4391558Srgrimes	}
4401558Srgrimes	return 0;
4411558Srgrimes}
4421558Srgrimes
4431558Srgrimesstatic const int	mon_lengths[2][MONSPERYEAR] = {
4441558Srgrimes	{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
4451558Srgrimes	{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
4461558Srgrimes};
4471558Srgrimes
4481558Srgrimesstatic const int	year_lengths[2] = {
4491558Srgrimes	DAYSPERNYEAR, DAYSPERLYEAR
4501558Srgrimes};
4511558Srgrimes
4521558Srgrimes/*
4531558Srgrimes** Given a pointer into a time zone string, scan until a character that is not
4541558Srgrimes** a valid character in a zone name is found.  Return a pointer to that
4551558Srgrimes** character.
4561558Srgrimes*/
4571558Srgrimes
4581558Srgrimesstatic const char *
459getzname(strp)
460const char *	strp;
461{
462	char	c;
463
464	while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
465		c != '+')
466			++strp;
467	return strp;
468}
469
470/*
471** Given a pointer into a time zone string, extract a number from that string.
472** Check that the number is within a specified range; if it is not, return
473** NULL.
474** Otherwise, return a pointer to the first character not part of the number.
475*/
476
477static const char *
478getnum(strp, nump, min, max)
479const char *	strp;
480int * const		nump;
481const int		min;
482const int		max;
483{
484	char	c;
485	int	num;
486
487	if (strp == NULL || !is_digit(c = *strp))
488		return NULL;
489	num = 0;
490	do {
491		num = num * 10 + (c - '0');
492		if (num > max)
493			return NULL;	/* illegal value */
494		c = *++strp;
495	} while (is_digit(c));
496	if (num < min)
497		return NULL;		/* illegal value */
498	*nump = num;
499	return strp;
500}
501
502/*
503** Given a pointer into a time zone string, extract a number of seconds,
504** in hh[:mm[:ss]] form, from the string.
505** If any error occurs, return NULL.
506** Otherwise, return a pointer to the first character not part of the number
507** of seconds.
508*/
509
510static const char *
511getsecs(strp, secsp)
512const char *	strp;
513long * const		secsp;
514{
515	int	num;
516
517	/*
518	** `HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
519	** "M10.4.6/26", which does not conform to Posix,
520	** but which specifies the equivalent of
521	** ``02:00 on the first Sunday on or after 23 Oct''.
522	*/
523	strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
524	if (strp == NULL)
525		return NULL;
526	*secsp = num * (long) SECSPERHOUR;
527	if (*strp == ':') {
528		++strp;
529		strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
530		if (strp == NULL)
531			return NULL;
532		*secsp += num * SECSPERMIN;
533		if (*strp == ':') {
534			++strp;
535			/* `SECSPERMIN' allows for leap seconds.  */
536			strp = getnum(strp, &num, 0, SECSPERMIN);
537			if (strp == NULL)
538				return NULL;
539			*secsp += num;
540		}
541	}
542	return strp;
543}
544
545/*
546** Given a pointer into a time zone string, extract an offset, in
547** [+-]hh[:mm[:ss]] form, from the string.
548** If any error occurs, return NULL.
549** Otherwise, return a pointer to the first character not part of the time.
550*/
551
552static const char *
553getoffset(strp, offsetp)
554const char *	strp;
555long * const		offsetp;
556{
557	int	neg = 0;
558
559	if (*strp == '-') {
560		neg = 1;
561		++strp;
562	} else if (*strp == '+')
563		++strp;
564	strp = getsecs(strp, offsetp);
565	if (strp == NULL)
566		return NULL;		/* illegal time */
567	if (neg)
568		*offsetp = -*offsetp;
569	return strp;
570}
571
572/*
573** Given a pointer into a time zone string, extract a rule in the form
574** date[/time].  See POSIX section 8 for the format of "date" and "time".
575** If a valid rule is not found, return NULL.
576** Otherwise, return a pointer to the first character not part of the rule.
577*/
578
579static const char *
580getrule(strp, rulep)
581const char *			strp;
582struct rule * const	rulep;
583{
584	if (*strp == 'J') {
585		/*
586		** Julian day.
587		*/
588		rulep->r_type = JULIAN_DAY;
589		++strp;
590		strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
591	} else if (*strp == 'M') {
592		/*
593		** Month, week, day.
594		*/
595		rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
596		++strp;
597		strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
598		if (strp == NULL)
599			return NULL;
600		if (*strp++ != '.')
601			return NULL;
602		strp = getnum(strp, &rulep->r_week, 1, 5);
603		if (strp == NULL)
604			return NULL;
605		if (*strp++ != '.')
606			return NULL;
607		strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
608	} else if (is_digit(*strp)) {
609		/*
610		** Day of year.
611		*/
612		rulep->r_type = DAY_OF_YEAR;
613		strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
614	} else	return NULL;		/* invalid format */
615	if (strp == NULL)
616		return NULL;
617	if (*strp == '/') {
618		/*
619		** Time specified.
620		*/
621		++strp;
622		strp = getsecs(strp, &rulep->r_time);
623	} else	rulep->r_time = 2 * SECSPERHOUR;	/* default = 2:00:00 */
624	return strp;
625}
626
627/*
628** Given the Epoch-relative time of January 1, 00:00:00 UTC, in a year, the
629** year, a rule, and the offset from UTC at the time that rule takes effect,
630** calculate the Epoch-relative time that rule takes effect.
631*/
632
633static time_t
634transtime(janfirst, year, rulep, offset)
635const time_t				janfirst;
636const int				year;
637const struct rule * const	rulep;
638const long				offset;
639{
640	int	leapyear;
641	time_t	value;
642	int	i;
643	int		d, m1, yy0, yy1, yy2, dow;
644
645	INITIALIZE(value);
646	leapyear = isleap(year);
647	switch (rulep->r_type) {
648
649	case JULIAN_DAY:
650		/*
651		** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
652		** years.
653		** In non-leap years, or if the day number is 59 or less, just
654		** add SECSPERDAY times the day number-1 to the time of
655		** January 1, midnight, to get the day.
656		*/
657		value = janfirst + (rulep->r_day - 1) * SECSPERDAY;
658		if (leapyear && rulep->r_day >= 60)
659			value += SECSPERDAY;
660		break;
661
662	case DAY_OF_YEAR:
663		/*
664		** n - day of year.
665		** Just add SECSPERDAY times the day number to the time of
666		** January 1, midnight, to get the day.
667		*/
668		value = janfirst + rulep->r_day * SECSPERDAY;
669		break;
670
671	case MONTH_NTH_DAY_OF_WEEK:
672		/*
673		** Mm.n.d - nth "dth day" of month m.
674		*/
675		value = janfirst;
676		for (i = 0; i < rulep->r_mon - 1; ++i)
677			value += mon_lengths[leapyear][i] * SECSPERDAY;
678
679		/*
680		** Use Zeller's Congruence to get day-of-week of first day of
681		** month.
682		*/
683		m1 = (rulep->r_mon + 9) % 12 + 1;
684		yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
685		yy1 = yy0 / 100;
686		yy2 = yy0 % 100;
687		dow = ((26 * m1 - 2) / 10 +
688			1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
689		if (dow < 0)
690			dow += DAYSPERWEEK;
691
692		/*
693		** "dow" is the day-of-week of the first day of the month.  Get
694		** the day-of-month (zero-origin) of the first "dow" day of the
695		** month.
696		*/
697		d = rulep->r_day - dow;
698		if (d < 0)
699			d += DAYSPERWEEK;
700		for (i = 1; i < rulep->r_week; ++i) {
701			if (d + DAYSPERWEEK >=
702				mon_lengths[leapyear][rulep->r_mon - 1])
703					break;
704			d += DAYSPERWEEK;
705		}
706
707		/*
708		** "d" is the day-of-month (zero-origin) of the day we want.
709		*/
710		value += d * SECSPERDAY;
711		break;
712	}
713
714	/*
715	** "value" is the Epoch-relative time of 00:00:00 UTC on the day in
716	** question.  To get the Epoch-relative time of the specified local
717	** time on that day, add the transition time and the current offset
718	** from UTC.
719	*/
720	return value + rulep->r_time + offset;
721}
722
723/*
724** Given a POSIX section 8-style TZ string, fill in the rule tables as
725** appropriate.
726*/
727
728static int
729tzparse(name, sp, lastditch)
730const char *			name;
731struct state * const	sp;
732const int			lastditch;
733{
734	const char *			stdname;
735	const char *			dstname;
736	size_t				stdlen;
737	size_t				dstlen;
738	long				stdoffset;
739	long				dstoffset;
740	time_t *		atp;
741	unsigned char *	typep;
742	char *			cp;
743	int			load_result;
744
745	INITIALIZE(dstname);
746	stdname = name;
747	if (lastditch) {
748		stdlen = strlen(name);	/* length of standard zone name */
749		name += stdlen;
750		if (stdlen >= sizeof sp->chars)
751			stdlen = (sizeof sp->chars) - 1;
752		stdoffset = 0;
753	} else {
754		name = getzname(name);
755		stdlen = name - stdname;
756		if (stdlen < 3)
757			return -1;
758		if (*name == '\0')
759			return -1;	/* was "stdoffset = 0;" */
760		else {
761			name = getoffset(name, &stdoffset);
762			if (name == NULL)
763				return -1;
764		}
765	}
766	load_result = tzload(TZDEFRULES, sp);
767	if (load_result != 0)
768		sp->leapcnt = 0;		/* so, we're off a little */
769	if (*name != '\0') {
770		dstname = name;
771		name = getzname(name);
772		dstlen = name - dstname;	/* length of DST zone name */
773		if (dstlen < 3)
774			return -1;
775		if (*name != '\0' && *name != ',' && *name != ';') {
776			name = getoffset(name, &dstoffset);
777			if (name == NULL)
778				return -1;
779		} else	dstoffset = stdoffset - SECSPERHOUR;
780		if (*name == '\0' && load_result != 0)
781			name = TZDEFRULESTRING;
782		if (*name == ',' || *name == ';') {
783			struct rule	start;
784			struct rule	end;
785			int	year;
786			time_t	janfirst;
787			time_t		starttime;
788			time_t		endtime;
789
790			++name;
791			if ((name = getrule(name, &start)) == NULL)
792				return -1;
793			if (*name++ != ',')
794				return -1;
795			if ((name = getrule(name, &end)) == NULL)
796				return -1;
797			if (*name != '\0')
798				return -1;
799			sp->typecnt = 2;	/* standard time and DST */
800			/*
801			** Two transitions per year, from EPOCH_YEAR to 2037.
802			*/
803			sp->timecnt = 2 * (2037 - EPOCH_YEAR + 1);
804			if (sp->timecnt > TZ_MAX_TIMES)
805				return -1;
806			sp->ttis[0].tt_gmtoff = -dstoffset;
807			sp->ttis[0].tt_isdst = 1;
808			sp->ttis[0].tt_abbrind = stdlen + 1;
809			sp->ttis[1].tt_gmtoff = -stdoffset;
810			sp->ttis[1].tt_isdst = 0;
811			sp->ttis[1].tt_abbrind = 0;
812			atp = sp->ats;
813			typep = sp->types;
814			janfirst = 0;
815			for (year = EPOCH_YEAR; year <= 2037; ++year) {
816				starttime = transtime(janfirst, year, &start,
817					stdoffset);
818				endtime = transtime(janfirst, year, &end,
819					dstoffset);
820				if (starttime > endtime) {
821					*atp++ = endtime;
822					*typep++ = 1;	/* DST ends */
823					*atp++ = starttime;
824					*typep++ = 0;	/* DST begins */
825				} else {
826					*atp++ = starttime;
827					*typep++ = 0;	/* DST begins */
828					*atp++ = endtime;
829					*typep++ = 1;	/* DST ends */
830				}
831				janfirst += year_lengths[isleap(year)] *
832					SECSPERDAY;
833			}
834		} else {
835			long	theirstdoffset;
836			long	theirdstoffset;
837			long	theiroffset;
838			int	isdst;
839			int	i;
840			int	j;
841
842			if (*name != '\0')
843				return -1;
844			/*
845			** Initial values of theirstdoffset and theirdstoffset.
846			*/
847			theirstdoffset = 0;
848			for (i = 0; i < sp->timecnt; ++i) {
849				j = sp->types[i];
850				if (!sp->ttis[j].tt_isdst) {
851					theirstdoffset =
852						-sp->ttis[j].tt_gmtoff;
853					break;
854				}
855			}
856			theirdstoffset = 0;
857			for (i = 0; i < sp->timecnt; ++i) {
858				j = sp->types[i];
859				if (sp->ttis[j].tt_isdst) {
860					theirdstoffset =
861						-sp->ttis[j].tt_gmtoff;
862					break;
863				}
864			}
865			/*
866			** Initially we're assumed to be in standard time.
867			*/
868			isdst = FALSE;
869			theiroffset = theirstdoffset;
870			/*
871			** Now juggle transition times and types
872			** tracking offsets as you do.
873			*/
874			for (i = 0; i < sp->timecnt; ++i) {
875				j = sp->types[i];
876				sp->types[i] = sp->ttis[j].tt_isdst;
877				if (sp->ttis[j].tt_ttisgmt) {
878					/* No adjustment to transition time */
879				} else {
880					/*
881					** If summer time is in effect, and the
882					** transition time was not specified as
883					** standard time, add the summer time
884					** offset to the transition time;
885					** otherwise, add the standard time
886					** offset to the transition time.
887					*/
888					/*
889					** Transitions from DST to DDST
890					** will effectively disappear since
891					** POSIX provides for only one DST
892					** offset.
893					*/
894					if (isdst && !sp->ttis[j].tt_ttisstd) {
895						sp->ats[i] += dstoffset -
896							theirdstoffset;
897					} else {
898						sp->ats[i] += stdoffset -
899							theirstdoffset;
900					}
901				}
902				theiroffset = -sp->ttis[j].tt_gmtoff;
903				if (sp->ttis[j].tt_isdst)
904					theirdstoffset = theiroffset;
905				else	theirstdoffset = theiroffset;
906			}
907			/*
908			** Finally, fill in ttis.
909			** ttisstd and ttisgmt need not be handled.
910			*/
911			sp->ttis[0].tt_gmtoff = -stdoffset;
912			sp->ttis[0].tt_isdst = FALSE;
913			sp->ttis[0].tt_abbrind = 0;
914			sp->ttis[1].tt_gmtoff = -dstoffset;
915			sp->ttis[1].tt_isdst = TRUE;
916			sp->ttis[1].tt_abbrind = stdlen + 1;
917			sp->typecnt = 2;
918		}
919	} else {
920		dstlen = 0;
921		sp->typecnt = 1;		/* only standard time */
922		sp->timecnt = 0;
923		sp->ttis[0].tt_gmtoff = -stdoffset;
924		sp->ttis[0].tt_isdst = 0;
925		sp->ttis[0].tt_abbrind = 0;
926	}
927	sp->charcnt = stdlen + 1;
928	if (dstlen != 0)
929		sp->charcnt += dstlen + 1;
930	if ((size_t) sp->charcnt > sizeof sp->chars)
931		return -1;
932	cp = sp->chars;
933	(void) strncpy(cp, stdname, stdlen);
934	cp += stdlen;
935	*cp++ = '\0';
936	if (dstlen != 0) {
937		(void) strncpy(cp, dstname, dstlen);
938		*(cp + dstlen) = '\0';
939	}
940	return 0;
941}
942
943static void
944gmtload(sp)
945struct state * const	sp;
946{
947	if (tzload(gmt, sp) != 0)
948		(void) tzparse(gmt, sp, TRUE);
949}
950
951static void
952tzsetwall_basic(void)
953{
954	if (lcl_is_set < 0)
955		return;
956	lcl_is_set = -1;
957
958#ifdef ALL_STATE
959	if (lclptr == NULL) {
960		lclptr = (struct state *) malloc(sizeof *lclptr);
961		if (lclptr == NULL) {
962			settzname();	/* all we can do */
963			return;
964		}
965	}
966#endif /* defined ALL_STATE */
967	if (tzload((char *) NULL, lclptr) != 0)
968		gmtload(lclptr);
969	settzname();
970}
971
972void
973tzsetwall(void)
974{
975	_MUTEX_LOCK(&lcl_mutex);
976	tzsetwall_basic();
977	_MUTEX_UNLOCK(&lcl_mutex);
978}
979
980static void
981tzset_basic(void)
982{
983	const char *	name;
984
985	name = getenv("TZ");
986	if (name == NULL) {
987		tzsetwall_basic();
988		return;
989	}
990
991	if (lcl_is_set > 0 && strcmp(lcl_TZname, name) == 0)
992		return;
993	lcl_is_set = strlen(name) < sizeof lcl_TZname;
994	if (lcl_is_set)
995		(void) strcpy(lcl_TZname, name);
996
997#ifdef ALL_STATE
998	if (lclptr == NULL) {
999		lclptr = (struct state *) malloc(sizeof *lclptr);
1000		if (lclptr == NULL) {
1001			settzname();	/* all we can do */
1002			return;
1003		}
1004	}
1005#endif /* defined ALL_STATE */
1006	if (*name == '\0') {
1007		/*
1008		** User wants it fast rather than right.
1009		*/
1010		lclptr->leapcnt = 0;		/* so, we're off a little */
1011		lclptr->timecnt = 0;
1012		lclptr->typecnt = 0;
1013		lclptr->ttis[0].tt_isdst = 0;
1014		lclptr->ttis[0].tt_gmtoff = 0;
1015		lclptr->ttis[0].tt_abbrind = 0;
1016		(void) strcpy(lclptr->chars, gmt);
1017	} else if (tzload(name, lclptr) != 0)
1018		if (name[0] == ':' || tzparse(name, lclptr, FALSE) != 0)
1019			(void) gmtload(lclptr);
1020	settzname();
1021}
1022
1023void
1024tzset(void)
1025{
1026	_MUTEX_LOCK(&lcl_mutex);
1027	tzset_basic();
1028	_MUTEX_UNLOCK(&lcl_mutex);
1029}
1030
1031/*
1032** The easy way to behave "as if no library function calls" localtime
1033** is to not call it--so we drop its guts into "localsub", which can be
1034** freely called.  (And no, the PANS doesn't require the above behavior--
1035** but it *is* desirable.)
1036**
1037** The unused offset argument is for the benefit of mktime variants.
1038*/
1039
1040/*ARGSUSED*/
1041static void
1042localsub(timep, offset, tmp)
1043const time_t * const	timep;
1044const long		offset;
1045struct tm * const	tmp;
1046{
1047	struct state *		sp;
1048	const struct ttinfo *	ttisp;
1049	int			i;
1050	const time_t			t = *timep;
1051
1052	sp = lclptr;
1053#ifdef ALL_STATE
1054	if (sp == NULL) {
1055		gmtsub(timep, offset, tmp);
1056		return;
1057	}
1058#endif /* defined ALL_STATE */
1059	if (sp->timecnt == 0 || t < sp->ats[0]) {
1060		i = 0;
1061		while (sp->ttis[i].tt_isdst)
1062			if (++i >= sp->typecnt) {
1063				i = 0;
1064				break;
1065			}
1066	} else {
1067		for (i = 1; i < sp->timecnt; ++i)
1068			if (t < sp->ats[i])
1069				break;
1070		i = sp->types[i - 1];
1071	}
1072	ttisp = &sp->ttis[i];
1073	/*
1074	** To get (wrong) behavior that's compatible with System V Release 2.0
1075	** you'd replace the statement below with
1076	**	t += ttisp->tt_gmtoff;
1077	**	timesub(&t, 0L, sp, tmp);
1078	*/
1079	timesub(&t, ttisp->tt_gmtoff, sp, tmp);
1080	tmp->tm_isdst = ttisp->tt_isdst;
1081	tzname[tmp->tm_isdst] = &sp->chars[ttisp->tt_abbrind];
1082#ifdef TM_ZONE
1083	tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
1084#endif /* defined TM_ZONE */
1085}
1086
1087struct tm *
1088localtime(timep)
1089const time_t * const	timep;
1090{
1091	static pthread_mutex_t localtime_mutex = PTHREAD_MUTEX_INITIALIZER;
1092	static pthread_key_t localtime_key = -1;
1093	struct tm *p_tm;
1094
1095	if (__isthreaded != 0) {
1096		_pthread_mutex_lock(&localtime_mutex);
1097		if (localtime_key < 0) {
1098			if (_pthread_key_create(&localtime_key, free) < 0) {
1099				_pthread_mutex_unlock(&localtime_mutex);
1100				return(NULL);
1101			}
1102		}
1103		_pthread_mutex_unlock(&localtime_mutex);
1104		p_tm = _pthread_getspecific(localtime_key);
1105		if (p_tm == NULL) {
1106			if ((p_tm = (struct tm *)malloc(sizeof(struct tm)))
1107			    == NULL)
1108				return(NULL);
1109			_pthread_setspecific(localtime_key, p_tm);
1110		}
1111		_pthread_mutex_lock(&lcl_mutex);
1112		tzset_basic();
1113		localsub(timep, 0L, p_tm);
1114		_pthread_mutex_unlock(&lcl_mutex);
1115		return(p_tm);
1116	} else {
1117		tzset_basic();
1118		localsub(timep, 0L, &tm);
1119		return(&tm);
1120	}
1121}
1122
1123/*
1124** Re-entrant version of localtime.
1125*/
1126
1127struct tm *
1128localtime_r(timep, tm)
1129const time_t * const	timep;
1130struct tm *		tm;
1131{
1132	_MUTEX_LOCK(&lcl_mutex);
1133	tzset_basic();
1134	localsub(timep, 0L, tm);
1135	_MUTEX_UNLOCK(&lcl_mutex);
1136	return tm;
1137}
1138
1139/*
1140** gmtsub is to gmtime as localsub is to localtime.
1141*/
1142
1143static void
1144gmtsub(timep, offset, tmp)
1145const time_t * const	timep;
1146const long		offset;
1147struct tm * const	tmp;
1148{
1149	_MUTEX_LOCK(&gmt_mutex);
1150	if (!gmt_is_set) {
1151		gmt_is_set = TRUE;
1152#ifdef ALL_STATE
1153		gmtptr = (struct state *) malloc(sizeof *gmtptr);
1154		if (gmtptr != NULL)
1155#endif /* defined ALL_STATE */
1156			gmtload(gmtptr);
1157	}
1158	_MUTEX_UNLOCK(&gmt_mutex);
1159	timesub(timep, offset, gmtptr, tmp);
1160#ifdef TM_ZONE
1161	/*
1162	** Could get fancy here and deliver something such as
1163	** "UTC+xxxx" or "UTC-xxxx" if offset is non-zero,
1164	** but this is no time for a treasure hunt.
1165	*/
1166	if (offset != 0)
1167		tmp->TM_ZONE = wildabbr;
1168	else {
1169#ifdef ALL_STATE
1170		if (gmtptr == NULL)
1171			tmp->TM_ZONE = gmt;
1172		else	tmp->TM_ZONE = gmtptr->chars;
1173#endif /* defined ALL_STATE */
1174#ifndef ALL_STATE
1175		tmp->TM_ZONE = gmtptr->chars;
1176#endif /* State Farm */
1177	}
1178#endif /* defined TM_ZONE */
1179}
1180
1181struct tm *
1182gmtime(timep)
1183const time_t * const	timep;
1184{
1185	static pthread_mutex_t gmtime_mutex = PTHREAD_MUTEX_INITIALIZER;
1186	static pthread_key_t gmtime_key = -1;
1187	struct tm *p_tm;
1188
1189	if (__isthreaded != 0) {
1190		_pthread_mutex_lock(&gmtime_mutex);
1191		if (gmtime_key < 0) {
1192			if (_pthread_key_create(&gmtime_key, free) < 0) {
1193				_pthread_mutex_unlock(&gmtime_mutex);
1194				return(NULL);
1195			}
1196		}
1197		_pthread_mutex_unlock(&gmtime_mutex);
1198		/*
1199		 * Changed to follow POSIX.1 threads standard, which
1200		 * is what BSD currently has.
1201		 */
1202		if ((p_tm = _pthread_getspecific(gmtime_key)) == NULL) {
1203			if ((p_tm = (struct tm *)malloc(sizeof(struct tm)))
1204			    == NULL) {
1205				return(NULL);
1206			}
1207			_pthread_setspecific(gmtime_key, p_tm);
1208		}
1209		gmtsub(timep, 0L, p_tm);
1210		return(p_tm);
1211	}
1212	else {
1213		gmtsub(timep, 0L, &tm);
1214		return(&tm);
1215	}
1216}
1217
1218/*
1219* Re-entrant version of gmtime.
1220*/
1221
1222struct tm *
1223gmtime_r(timep, tm)
1224const time_t * const	timep;
1225struct tm *		tm;
1226{
1227	gmtsub(timep, 0L, tm);
1228	return tm;
1229}
1230
1231#ifdef STD_INSPIRED
1232
1233struct tm *
1234offtime(timep, offset)
1235const time_t * const	timep;
1236const long		offset;
1237{
1238	gmtsub(timep, offset, &tm);
1239	return &tm;
1240}
1241
1242#endif /* defined STD_INSPIRED */
1243
1244static void
1245timesub(timep, offset, sp, tmp)
1246const time_t * const			timep;
1247const long				offset;
1248const struct state * const	sp;
1249struct tm * const		tmp;
1250{
1251	const struct lsinfo *	lp;
1252	long			days;
1253	long			rem;
1254	long			y;
1255	int			yleap;
1256	const int *		ip;
1257	long			corr;
1258	int			hit;
1259	int			i;
1260
1261	corr = 0;
1262	hit = 0;
1263#ifdef ALL_STATE
1264	i = (sp == NULL) ? 0 : sp->leapcnt;
1265#endif /* defined ALL_STATE */
1266#ifndef ALL_STATE
1267	i = sp->leapcnt;
1268#endif /* State Farm */
1269	while (--i >= 0) {
1270		lp = &sp->lsis[i];
1271		if (*timep >= lp->ls_trans) {
1272			if (*timep == lp->ls_trans) {
1273				hit = ((i == 0 && lp->ls_corr > 0) ||
1274					lp->ls_corr > sp->lsis[i - 1].ls_corr);
1275				if (hit)
1276					while (i > 0 &&
1277						sp->lsis[i].ls_trans ==
1278						sp->lsis[i - 1].ls_trans + 1 &&
1279						sp->lsis[i].ls_corr ==
1280						sp->lsis[i - 1].ls_corr + 1) {
1281							++hit;
1282							--i;
1283					}
1284			}
1285			corr = lp->ls_corr;
1286			break;
1287		}
1288	}
1289	days = *timep / SECSPERDAY;
1290	rem = *timep % SECSPERDAY;
1291#ifdef mc68k
1292	if (*timep == 0x80000000) {
1293		/*
1294		** A 3B1 muffs the division on the most negative number.
1295		*/
1296		days = -24855;
1297		rem = -11648;
1298	}
1299#endif /* defined mc68k */
1300	rem += (offset - corr);
1301	while (rem < 0) {
1302		rem += SECSPERDAY;
1303		--days;
1304	}
1305	while (rem >= SECSPERDAY) {
1306		rem -= SECSPERDAY;
1307		++days;
1308	}
1309	tmp->tm_hour = (int) (rem / SECSPERHOUR);
1310	rem = rem % SECSPERHOUR;
1311	tmp->tm_min = (int) (rem / SECSPERMIN);
1312	/*
1313	** A positive leap second requires a special
1314	** representation.  This uses "... ??:59:60" et seq.
1315	*/
1316	tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
1317	tmp->tm_wday = (int) ((EPOCH_WDAY + days) % DAYSPERWEEK);
1318	if (tmp->tm_wday < 0)
1319		tmp->tm_wday += DAYSPERWEEK;
1320	y = EPOCH_YEAR;
1321#define LEAPS_THRU_END_OF(y)	((y) / 4 - (y) / 100 + (y) / 400)
1322	while (days < 0 || days >= (long) year_lengths[yleap = isleap(y)]) {
1323		long	newy;
1324
1325		newy = y + days / DAYSPERNYEAR;
1326		if (days < 0)
1327			--newy;
1328		days -= (newy - y) * DAYSPERNYEAR +
1329			LEAPS_THRU_END_OF(newy - 1) -
1330			LEAPS_THRU_END_OF(y - 1);
1331		y = newy;
1332	}
1333	tmp->tm_year = y - TM_YEAR_BASE;
1334	tmp->tm_yday = (int) days;
1335	ip = mon_lengths[yleap];
1336	for (tmp->tm_mon = 0; days >= (long) ip[tmp->tm_mon]; ++(tmp->tm_mon))
1337		days = days - (long) ip[tmp->tm_mon];
1338	tmp->tm_mday = (int) (days + 1);
1339	tmp->tm_isdst = 0;
1340#ifdef TM_GMTOFF
1341	tmp->TM_GMTOFF = offset;
1342#endif /* defined TM_GMTOFF */
1343}
1344
1345char *
1346ctime(timep)
1347const time_t * const	timep;
1348{
1349/*
1350** Section 4.12.3.2 of X3.159-1989 requires that
1351**	The ctime function converts the calendar time pointed to by timer
1352**	to local time in the form of a string.  It is equivalent to
1353**		asctime(localtime(timer))
1354*/
1355	return asctime(localtime(timep));
1356}
1357
1358char *
1359ctime_r(timep, buf)
1360const time_t * const	timep;
1361char *			buf;
1362{
1363	struct tm	tm;
1364
1365	return asctime_r(localtime_r(timep, &tm), buf);
1366}
1367
1368/*
1369** Adapted from code provided by Robert Elz, who writes:
1370**	The "best" way to do mktime I think is based on an idea of Bob
1371**	Kridle's (so its said...) from a long time ago.
1372**	[kridle@xinet.com as of 1996-01-16.]
1373**	It does a binary search of the time_t space.  Since time_t's are
1374**	just 32 bits, its a max of 32 iterations (even at 64 bits it
1375**	would still be very reasonable).
1376*/
1377
1378#ifndef WRONG
1379#define WRONG	(-1)
1380#endif /* !defined WRONG */
1381
1382/*
1383** Simplified normalize logic courtesy Paul Eggert (eggert@twinsun.com).
1384*/
1385
1386static int
1387increment_overflow(number, delta)
1388int *	number;
1389int	delta;
1390{
1391	int	number0;
1392
1393	number0 = *number;
1394	*number += delta;
1395	return (*number < number0) != (delta < 0);
1396}
1397
1398static int
1399normalize_overflow(tensptr, unitsptr, base)
1400int * const	tensptr;
1401int * const	unitsptr;
1402const int	base;
1403{
1404	int	tensdelta;
1405
1406	tensdelta = (*unitsptr >= 0) ?
1407		(*unitsptr / base) :
1408		(-1 - (-1 - *unitsptr) / base);
1409	*unitsptr -= tensdelta * base;
1410	return increment_overflow(tensptr, tensdelta);
1411}
1412
1413static int
1414tmcomp(atmp, btmp)
1415const struct tm * const atmp;
1416const struct tm * const btmp;
1417{
1418	int	result;
1419
1420	if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
1421		(result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
1422		(result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
1423		(result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
1424		(result = (atmp->tm_min - btmp->tm_min)) == 0)
1425			result = atmp->tm_sec - btmp->tm_sec;
1426	return result;
1427}
1428
1429static time_t
1430time2sub(tmp, funcp, offset, okayp, do_norm_secs)
1431struct tm * const	tmp;
1432void (* const		funcp)(const time_t*, long, struct tm*);
1433const long		offset;
1434int * const		okayp;
1435const int		do_norm_secs;
1436{
1437	const struct state *	sp;
1438	int			dir;
1439	int			bits;
1440	int			i, j ;
1441	int			saved_seconds;
1442	time_t				newt;
1443	time_t				t;
1444	struct tm			yourtm, mytm;
1445
1446	*okayp = FALSE;
1447	yourtm = *tmp;
1448	if (do_norm_secs) {
1449		if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
1450			SECSPERMIN))
1451				return WRONG;
1452	}
1453	if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
1454		return WRONG;
1455	if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
1456		return WRONG;
1457	if (normalize_overflow(&yourtm.tm_year, &yourtm.tm_mon, MONSPERYEAR))
1458		return WRONG;
1459	/*
1460	** Turn yourtm.tm_year into an actual year number for now.
1461	** It is converted back to an offset from TM_YEAR_BASE later.
1462	*/
1463	if (increment_overflow(&yourtm.tm_year, TM_YEAR_BASE))
1464		return WRONG;
1465	while (yourtm.tm_mday <= 0) {
1466		if (increment_overflow(&yourtm.tm_year, -1))
1467			return WRONG;
1468		i = yourtm.tm_year + (1 < yourtm.tm_mon);
1469		yourtm.tm_mday += year_lengths[isleap(i)];
1470	}
1471	while (yourtm.tm_mday > DAYSPERLYEAR) {
1472		i = yourtm.tm_year + (1 < yourtm.tm_mon);
1473		yourtm.tm_mday -= year_lengths[isleap(i)];
1474		if (increment_overflow(&yourtm.tm_year, 1))
1475			return WRONG;
1476	}
1477	for ( ; ; ) {
1478		i = mon_lengths[isleap(yourtm.tm_year)][yourtm.tm_mon];
1479		if (yourtm.tm_mday <= i)
1480			break;
1481		yourtm.tm_mday -= i;
1482		if (++yourtm.tm_mon >= MONSPERYEAR) {
1483			yourtm.tm_mon = 0;
1484			if (increment_overflow(&yourtm.tm_year, 1))
1485				return WRONG;
1486		}
1487	}
1488	if (increment_overflow(&yourtm.tm_year, -TM_YEAR_BASE))
1489		return WRONG;
1490	if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
1491		saved_seconds = 0;
1492	else if (yourtm.tm_year + TM_YEAR_BASE < EPOCH_YEAR) {
1493		/*
1494		** We can't set tm_sec to 0, because that might push the
1495		** time below the minimum representable time.
1496		** Set tm_sec to 59 instead.
1497		** This assumes that the minimum representable time is
1498		** not in the same minute that a leap second was deleted from,
1499		** which is a safer assumption than using 58 would be.
1500		*/
1501		if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
1502			return WRONG;
1503		saved_seconds = yourtm.tm_sec;
1504		yourtm.tm_sec = SECSPERMIN - 1;
1505	} else {
1506		saved_seconds = yourtm.tm_sec;
1507		yourtm.tm_sec = 0;
1508	}
1509	/*
1510	** Divide the search space in half
1511	** (this works whether time_t is signed or unsigned).
1512	*/
1513	bits = TYPE_BIT(time_t) - 1;
1514	/*
1515	** If we have more than this, we will overflow tm_year for tmcomp().
1516	** We should really return an error if we cannot represent it.
1517	*/
1518	if (bits > 56)
1519		bits = 56;
1520	/*
1521	** If time_t is signed, then 0 is just above the median,
1522	** assuming two's complement arithmetic.
1523	** If time_t is unsigned, then (1 << bits) is just above the median.
1524	*/
1525	t = TYPE_SIGNED(time_t) ? 0 : (((time_t) 1) << bits);
1526	for ( ; ; ) {
1527		(*funcp)(&t, offset, &mytm);
1528		dir = tmcomp(&mytm, &yourtm);
1529		if (dir != 0) {
1530			if (bits-- < 0)
1531				return WRONG;
1532			if (bits < 0)
1533				--t; /* may be needed if new t is minimal */
1534			else if (dir > 0)
1535				t -= ((time_t) 1) << bits;
1536			else	t += ((time_t) 1) << bits;
1537			continue;
1538		}
1539		if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
1540			break;
1541		/*
1542		** Right time, wrong type.
1543		** Hunt for right time, right type.
1544		** It's okay to guess wrong since the guess
1545		** gets checked.
1546		*/
1547		sp = (funcp == localsub) ? lclptr : gmtptr;
1548#ifdef ALL_STATE
1549		if (sp == NULL)
1550			return WRONG;
1551#endif /* defined ALL_STATE */
1552		for (i = sp->typecnt - 1; i >= 0; --i) {
1553			if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
1554				continue;
1555			for (j = sp->typecnt - 1; j >= 0; --j) {
1556				if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
1557					continue;
1558				newt = t + sp->ttis[j].tt_gmtoff -
1559					sp->ttis[i].tt_gmtoff;
1560				(*funcp)(&newt, offset, &mytm);
1561				if (tmcomp(&mytm, &yourtm) != 0)
1562					continue;
1563				if (mytm.tm_isdst != yourtm.tm_isdst)
1564					continue;
1565				/*
1566				** We have a match.
1567				*/
1568				t = newt;
1569				goto label;
1570			}
1571		}
1572		return WRONG;
1573	}
1574label:
1575	newt = t + saved_seconds;
1576	if ((newt < t) != (saved_seconds < 0))
1577		return WRONG;
1578	t = newt;
1579	(*funcp)(&t, offset, tmp);
1580	*okayp = TRUE;
1581	return t;
1582}
1583
1584static time_t
1585time2(tmp, funcp, offset, okayp)
1586struct tm * const	tmp;
1587void (* const		funcp)(const time_t*, long, struct tm*);
1588const long		offset;
1589int * const		okayp;
1590{
1591	time_t	t;
1592
1593	/*
1594	** First try without normalization of seconds
1595	** (in case tm_sec contains a value associated with a leap second).
1596	** If that fails, try with normalization of seconds.
1597	*/
1598	t = time2sub(tmp, funcp, offset, okayp, FALSE);
1599	return *okayp ? t : time2sub(tmp, funcp, offset, okayp, TRUE);
1600}
1601
1602static time_t
1603time1(tmp, funcp, offset)
1604struct tm * const	tmp;
1605void (* const		funcp)(const time_t *, long, struct tm *);
1606const long		offset;
1607{
1608	time_t			t;
1609	const struct state *	sp;
1610	int			samei, otheri;
1611	int			sameind, otherind;
1612	int			i;
1613	int			nseen;
1614	int				seen[TZ_MAX_TYPES];
1615	int				types[TZ_MAX_TYPES];
1616	int				okay;
1617
1618	if (tmp->tm_isdst > 1)
1619		tmp->tm_isdst = 1;
1620	t = time2(tmp, funcp, offset, &okay);
1621#ifdef PCTS
1622	/*
1623	** PCTS code courtesy Grant Sullivan (grant@osf.org).
1624	*/
1625	if (okay)
1626		return t;
1627	if (tmp->tm_isdst < 0)
1628		tmp->tm_isdst = 0;	/* reset to std and try again */
1629#endif /* defined PCTS */
1630#ifndef PCTS
1631	if (okay || tmp->tm_isdst < 0)
1632		return t;
1633#endif /* !defined PCTS */
1634	/*
1635	** We're supposed to assume that somebody took a time of one type
1636	** and did some math on it that yielded a "struct tm" that's bad.
1637	** We try to divine the type they started from and adjust to the
1638	** type they need.
1639	*/
1640	sp = (funcp == localsub) ? lclptr : gmtptr;
1641#ifdef ALL_STATE
1642	if (sp == NULL)
1643		return WRONG;
1644#endif /* defined ALL_STATE */
1645	for (i = 0; i < sp->typecnt; ++i)
1646		seen[i] = FALSE;
1647	nseen = 0;
1648	for (i = sp->timecnt - 1; i >= 0; --i)
1649		if (!seen[sp->types[i]]) {
1650			seen[sp->types[i]] = TRUE;
1651			types[nseen++] = sp->types[i];
1652		}
1653	for (sameind = 0; sameind < nseen; ++sameind) {
1654		samei = types[sameind];
1655		if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
1656			continue;
1657		for (otherind = 0; otherind < nseen; ++otherind) {
1658			otheri = types[otherind];
1659			if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
1660				continue;
1661			tmp->tm_sec += sp->ttis[otheri].tt_gmtoff -
1662					sp->ttis[samei].tt_gmtoff;
1663			tmp->tm_isdst = !tmp->tm_isdst;
1664			t = time2(tmp, funcp, offset, &okay);
1665			if (okay)
1666				return t;
1667			tmp->tm_sec -= sp->ttis[otheri].tt_gmtoff -
1668					sp->ttis[samei].tt_gmtoff;
1669			tmp->tm_isdst = !tmp->tm_isdst;
1670		}
1671	}
1672	return WRONG;
1673}
1674
1675time_t
1676mktime(tmp)
1677struct tm * const	tmp;
1678{
1679	time_t mktime_return_value;
1680	_MUTEX_LOCK(&lcl_mutex);
1681	tzset_basic();
1682	mktime_return_value = time1(tmp, localsub, 0L);
1683	_MUTEX_UNLOCK(&lcl_mutex);
1684	return(mktime_return_value);
1685}
1686
1687#ifdef STD_INSPIRED
1688
1689time_t
1690timelocal(tmp)
1691struct tm * const	tmp;
1692{
1693	tmp->tm_isdst = -1;	/* in case it wasn't initialized */
1694	return mktime(tmp);
1695}
1696
1697time_t
1698timegm(tmp)
1699struct tm * const	tmp;
1700{
1701	tmp->tm_isdst = 0;
1702	return time1(tmp, gmtsub, 0L);
1703}
1704
1705time_t
1706timeoff(tmp, offset)
1707struct tm * const	tmp;
1708const long		offset;
1709{
1710	tmp->tm_isdst = 0;
1711	return time1(tmp, gmtsub, offset);
1712}
1713
1714#endif /* defined STD_INSPIRED */
1715
1716#ifdef CMUCS
1717
1718/*
1719** The following is supplied for compatibility with
1720** previous versions of the CMUCS runtime library.
1721*/
1722
1723long
1724gtime(tmp)
1725struct tm * const	tmp;
1726{
1727	const time_t	t = mktime(tmp);
1728
1729	if (t == WRONG)
1730		return -1;
1731	return t;
1732}
1733
1734#endif /* defined CMUCS */
1735
1736/*
1737** XXX--is the below the right way to conditionalize??
1738*/
1739
1740#ifdef STD_INSPIRED
1741
1742/*
1743** IEEE Std 1003.1-1988 (POSIX) legislates that 536457599
1744** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
1745** is not the case if we are accounting for leap seconds.
1746** So, we provide the following conversion routines for use
1747** when exchanging timestamps with POSIX conforming systems.
1748*/
1749
1750static long
1751leapcorr(timep)
1752time_t *	timep;
1753{
1754	struct state *		sp;
1755	struct lsinfo *	lp;
1756	int			i;
1757
1758	sp = lclptr;
1759	i = sp->leapcnt;
1760	while (--i >= 0) {
1761		lp = &sp->lsis[i];
1762		if (*timep >= lp->ls_trans)
1763			return lp->ls_corr;
1764	}
1765	return 0;
1766}
1767
1768time_t
1769time2posix(t)
1770time_t	t;
1771{
1772	tzset();
1773	return t - leapcorr(&t);
1774}
1775
1776time_t
1777posix2time(t)
1778time_t	t;
1779{
1780	time_t	x;
1781	time_t	y;
1782
1783	tzset();
1784	/*
1785	** For a positive leap second hit, the result
1786	** is not unique.  For a negative leap second
1787	** hit, the corresponding time doesn't exist,
1788	** so we return an adjacent second.
1789	*/
1790	x = t + leapcorr(&t);
1791	y = x - leapcorr(&x);
1792	if (y < t) {
1793		do {
1794			x++;
1795			y = x - leapcorr(&x);
1796		} while (y < t);
1797		if (t != y)
1798			return x - 1;
1799	} else if (y > t) {
1800		do {
1801			--x;
1802			y = x - leapcorr(&x);
1803		} while (y > t);
1804		if (t != y)
1805			return x + 1;
1806	}
1807	return x;
1808}
1809
1810#endif /* defined STD_INSPIRED */
1811