Home | History | Annotate | Line # | Download | only in time
localtime.c revision 1.81
      1 /*	$NetBSD: localtime.c,v 1.81 2013/12/26 18:34:28 christos Exp $	*/
      2 
      3 /*
      4 ** This file is in the public domain, so clarified as of
      5 ** 1996-06-05 by Arthur David Olson.
      6 */
      7 
      8 #include <sys/cdefs.h>
      9 #if defined(LIBC_SCCS) && !defined(lint)
     10 #if 0
     11 static char	elsieid[] = "@(#)localtime.c	8.17";
     12 #else
     13 __RCSID("$NetBSD: localtime.c,v 1.81 2013/12/26 18:34:28 christos Exp $");
     14 #endif
     15 #endif /* LIBC_SCCS and not lint */
     16 
     17 /*
     18 ** Leap second handling from Bradley White.
     19 ** POSIX-style TZ environment variable handling from Guy Harris.
     20 */
     21 
     22 /*LINTLIBRARY*/
     23 
     24 #include "namespace.h"
     25 #include <assert.h>
     26 #include "private.h"
     27 #include "tzfile.h"
     28 #include "fcntl.h"
     29 #include "reentrant.h"
     30 
     31 #if defined(__weak_alias)
     32 __weak_alias(daylight,_daylight)
     33 __weak_alias(tzname,_tzname)
     34 #endif
     35 
     36 #ifndef TZ_ABBR_MAX_LEN
     37 #define TZ_ABBR_MAX_LEN	16
     38 #endif /* !defined TZ_ABBR_MAX_LEN */
     39 
     40 #ifndef TZ_ABBR_CHAR_SET
     41 #define TZ_ABBR_CHAR_SET \
     42 	"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._"
     43 #endif /* !defined TZ_ABBR_CHAR_SET */
     44 
     45 #ifndef TZ_ABBR_ERR_CHAR
     46 #define TZ_ABBR_ERR_CHAR	'_'
     47 #endif /* !defined TZ_ABBR_ERR_CHAR */
     48 
     49 /* The minimum and maximum finite time values.  */
     50 static time_t const time_t_min =
     51   (TYPE_SIGNED(time_t)
     52    ? (time_t) -1 << (int)(CHAR_BIT * sizeof (time_t) - 1)
     53    : 0);
     54 static time_t const time_t_max =
     55   (TYPE_SIGNED(time_t)
     56    ? - (~ 0 < 0) - ((time_t) -1 << (int)(CHAR_BIT * sizeof (time_t) - 1))
     57    : -1);
     58 
     59 /*
     60 ** SunOS 4.1.1 headers lack O_BINARY.
     61 */
     62 
     63 #ifdef O_BINARY
     64 #define OPEN_MODE	(O_RDONLY | O_BINARY)
     65 #endif /* defined O_BINARY */
     66 #ifndef O_BINARY
     67 #define OPEN_MODE	O_RDONLY
     68 #endif /* !defined O_BINARY */
     69 
     70 #ifndef WILDABBR
     71 /*
     72 ** Someone might make incorrect use of a time zone abbreviation:
     73 **	1.	They might reference tzname[0] before calling tzset (explicitly
     74 **		or implicitly).
     75 **	2.	They might reference tzname[1] before calling tzset (explicitly
     76 **		or implicitly).
     77 **	3.	They might reference tzname[1] after setting to a time zone
     78 **		in which Daylight Saving Time is never observed.
     79 **	4.	They might reference tzname[0] after setting to a time zone
     80 **		in which Standard Time is never observed.
     81 **	5.	They might reference tm.TM_ZONE after calling offtime.
     82 ** What's best to do in the above cases is open to debate;
     83 ** for now, we just set things up so that in any of the five cases
     84 ** WILDABBR is used. Another possibility: initialize tzname[0] to the
     85 ** string "tzname[0] used before set", and similarly for the other cases.
     86 ** And another: initialize tzname[0] to "ERA", with an explanation in the
     87 ** manual page of what this "time zone abbreviation" means (doing this so
     88 ** that tzname[0] has the "normal" length of three characters).
     89 */
     90 #define WILDABBR	"   "
     91 #endif /* !defined WILDABBR */
     92 
     93 static const char	wildabbr[] = WILDABBR;
     94 
     95 static const char	gmt[] = "GMT";
     96 
     97 /*
     98 ** The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
     99 ** We default to US rules as of 1999-08-17.
    100 ** POSIX 1003.1 section 8.1.1 says that the default DST rules are
    101 ** implementation dependent; for historical reasons, US rules are a
    102 ** common default.
    103 */
    104 #ifndef TZDEFRULESTRING
    105 #define TZDEFRULESTRING ",M4.1.0,M10.5.0"
    106 #endif /* !defined TZDEFDST */
    107 
    108 struct ttinfo {				/* time type information */
    109 	int_fast32_t	tt_gmtoff;	/* UT offset in seconds */
    110 	int		tt_isdst;	/* used to set tm_isdst */
    111 	int		tt_abbrind;	/* abbreviation list index */
    112 	int		tt_ttisstd;	/* TRUE if transition is std time */
    113 	int		tt_ttisgmt;	/* TRUE if transition is UT */
    114 };
    115 
    116 struct lsinfo {				/* leap second information */
    117 	time_t		ls_trans;	/* transition time */
    118 	int_fast64_t	ls_corr;	/* correction to apply */
    119 };
    120 
    121 #define BIGGEST(a, b)	(((a) > (b)) ? (a) : (b))
    122 
    123 #ifdef TZNAME_MAX
    124 #define MY_TZNAME_MAX	TZNAME_MAX
    125 #endif /* defined TZNAME_MAX */
    126 #ifndef TZNAME_MAX
    127 #define MY_TZNAME_MAX	255
    128 #endif /* !defined TZNAME_MAX */
    129 
    130 struct __state {
    131 	int		leapcnt;
    132 	int		timecnt;
    133 	int		typecnt;
    134 	int		charcnt;
    135 	int		goback;
    136 	int		goahead;
    137 	time_t		ats[TZ_MAX_TIMES];
    138 	unsigned char	types[TZ_MAX_TIMES];
    139 	struct ttinfo	ttis[TZ_MAX_TYPES];
    140 	char		chars[/*CONSTCOND*/BIGGEST(BIGGEST(TZ_MAX_CHARS + 1,
    141 				sizeof gmt), (2 * (MY_TZNAME_MAX + 1)))];
    142 	struct lsinfo	lsis[TZ_MAX_LEAPS];
    143 	int		defaulttype; /* for early times or if no transitions */
    144 };
    145 
    146 struct rule {
    147 	int		r_type;		/* type of rule--see below */
    148 	int		r_day;		/* day number of rule */
    149 	int		r_week;		/* week number of rule */
    150 	int		r_mon;		/* month number of rule */
    151 	int_fast32_t	r_time;		/* transition time of rule */
    152 };
    153 
    154 #define JULIAN_DAY		0	/* Jn - Julian day */
    155 #define DAY_OF_YEAR		1	/* n - day of year */
    156 #define MONTH_NTH_DAY_OF_WEEK	2	/* Mm.n.d - month, week, day of week */
    157 
    158 typedef struct tm *(*subfun_t)(const timezone_t sp, const time_t *timep,
    159 			       const int_fast32_t offset, struct tm *tmp);
    160 
    161 /*
    162 ** Prototypes for static functions.
    163 */
    164 
    165 static int_fast32_t	detzcode(const char * codep);
    166 static int_fast64_t	detzcode64(const char * codep);
    167 static int		differ_by_repeat(time_t t1, time_t t0);
    168 static const char *	getzname(const char * strp) ATTRIBUTE_PURE;
    169 static const char *	getqzname(const char * strp, const int delim) ATTRIBUTE_PURE;
    170 static const char *	getnum(const char * strp, int * nump, int min,
    171 				int max);
    172 static const char *	getsecs(const char * strp, int_fast32_t * secsp);
    173 static const char *	getoffset(const char * strp, int_fast32_t * offsetp);
    174 static const char *	getrule(const char * strp, struct rule * rulep);
    175 static void		gmtload(timezone_t sp);
    176 static struct tm *	gmtsub(const timezone_t sp, const time_t *timep,
    177 				const int_fast32_t offset, struct tm * tmp);
    178 static struct tm *	localsub(const timezone_t sp, const time_t *timep,
    179 				const int_fast32_t offset, struct tm *tmp);
    180 static int		increment_overflow(int * number, int delta);
    181 static int		increment_overflow32(int_fast32_t * number, int delta);
    182 static int		increment_overflow_time(time_t *t, int_fast32_t delta);
    183 static int		leaps_thru_end_of(int y) ATTRIBUTE_PURE;
    184 static int		normalize_overflow(int * tensptr, int * unitsptr,
    185 				int base);
    186 static int		normalize_overflow32(int_fast32_t * tensptr,
    187 				int * unitsptr, int base);
    188 static void		settzname(void);
    189 static time_t		time1(const timezone_t sp, struct tm * const tmp,
    190 				subfun_t funcp, const int_fast32_t offset);
    191 static time_t		time2(const timezone_t sp, struct tm * const tmp,
    192 				subfun_t funcp,
    193 				const int_fast32_t offset, int *const okayp);
    194 static time_t		time2sub(const timezone_t sp, struct tm * const tmp,
    195 				subfun_t funcp, const int_fast32_t offset,
    196 				int *const okayp, const int do_norm_secs);
    197 static struct tm *	timesub(const timezone_t sp, const time_t * timep,
    198 				const int_fast32_t offset, struct tm * tmp);
    199 static int		tmcomp(const struct tm * atmp,
    200 				const struct tm * btmp);
    201 static int_fast32_t	transtime(int year, const struct rule * rulep,
    202 				  int_fast32_t offset)
    203   ATTRIBUTE_PURE;
    204 static int		typesequiv(const timezone_t sp, int a, int b);
    205 static int		tzload(timezone_t sp, const char * name,
    206 				int doextend);
    207 static int		tzparse(timezone_t sp, const char * name,
    208 				int lastditch);
    209 static void		tzset_unlocked(void);
    210 static void		tzsetwall_unlocked(void);
    211 static int_fast64_t	leapcorr(const timezone_t sp, time_t * timep);
    212 
    213 static timezone_t lclptr;
    214 static timezone_t gmtptr;
    215 
    216 #ifndef TZ_STRLEN_MAX
    217 #define TZ_STRLEN_MAX 255
    218 #endif /* !defined TZ_STRLEN_MAX */
    219 
    220 static char		lcl_TZname[TZ_STRLEN_MAX + 1];
    221 static int		lcl_is_set;
    222 static int		gmt_is_set;
    223 
    224 #if !defined(__LIBC12_SOURCE__)
    225 
    226 __aconst char *		tzname[2] = {
    227 	(__aconst char *)__UNCONST(wildabbr),
    228 	(__aconst char *)__UNCONST(wildabbr)
    229 };
    230 
    231 #else
    232 
    233 extern __aconst char *	tzname[2];
    234 
    235 #endif
    236 
    237 #ifdef _REENTRANT
    238 static rwlock_t lcl_lock = RWLOCK_INITIALIZER;
    239 #endif
    240 
    241 /*
    242 ** Section 4.12.3 of X3.159-1989 requires that
    243 **	Except for the strftime function, these functions [asctime,
    244 **	ctime, gmtime, localtime] return values in one of two static
    245 **	objects: a broken-down time structure and an array of char.
    246 ** Thanks to Paul Eggert for noting this.
    247 */
    248 
    249 static struct tm	tm;
    250 
    251 #ifdef USG_COMPAT
    252 #if !defined(__LIBC12_SOURCE__)
    253 long 			timezone = 0;
    254 int			daylight = 0;
    255 #else
    256 extern int		daylight;
    257 extern long		timezone __RENAME(__timezone13);
    258 #endif
    259 #endif /* defined USG_COMPAT */
    260 
    261 #ifdef ALTZONE
    262 long			altzone = 0;
    263 #endif /* defined ALTZONE */
    264 
    265 static int_fast32_t
    266 detzcode(const char *const codep)
    267 {
    268 	int_fast32_t	result;
    269 	int	i;
    270 
    271 	result = (codep[0] & 0x80) ? -1 : 0;
    272 	for (i = 0; i < 4; ++i)
    273 		result = (result << 8) | (codep[i] & 0xff);
    274 	return result;
    275 }
    276 
    277 static int_fast64_t
    278 detzcode64(const char *const codep)
    279 {
    280 	int_fast64_t	result;
    281 	int	i;
    282 
    283 	result = (codep[0] & 0x80) ? -1 : 0;
    284 	for (i = 0; i < 8; ++i)
    285 		result = (result << 8) | (codep[i] & 0xff);
    286 	return result;
    287 }
    288 
    289 const char *
    290 tzgetname(const timezone_t sp, int isdst)
    291 {
    292 	int i;
    293 	for (i = 0; i < sp->timecnt; ++i) {
    294 		const struct ttinfo *const ttisp = &sp->ttis[sp->types[i]];
    295 
    296 		if (ttisp->tt_isdst == isdst)
    297 			return &sp->chars[ttisp->tt_abbrind];
    298 	}
    299 	return NULL;
    300 }
    301 
    302 static void
    303 settzname_z(timezone_t sp)
    304 {
    305 	int			i;
    306 
    307 	/*
    308 	** Scrub the abbreviations.
    309 	** First, replace bogus characters.
    310 	*/
    311 	for (i = 0; i < sp->charcnt; ++i)
    312 		if (strchr(TZ_ABBR_CHAR_SET, sp->chars[i]) == NULL)
    313 			sp->chars[i] = TZ_ABBR_ERR_CHAR;
    314 	/*
    315 	** Second, truncate long abbreviations.
    316 	*/
    317 	for (i = 0; i < sp->typecnt; ++i) {
    318 		const struct ttinfo * const	ttisp = &sp->ttis[i];
    319 		char *				cp = &sp->chars[ttisp->tt_abbrind];
    320 
    321 		if (strlen(cp) > TZ_ABBR_MAX_LEN &&
    322 			strcmp(cp, GRANDPARENTED) != 0)
    323 				*(cp + TZ_ABBR_MAX_LEN) = '\0';
    324 	}
    325 }
    326 
    327 static void
    328 settzname(void)
    329 {
    330 	timezone_t const	sp = lclptr;
    331 	int			i;
    332 
    333 	tzname[0] = (__aconst char *)__UNCONST(wildabbr);
    334 	tzname[1] = (__aconst char *)__UNCONST(wildabbr);
    335 #ifdef USG_COMPAT
    336 	daylight = 0;
    337 	timezone = 0;
    338 #endif /* defined USG_COMPAT */
    339 #ifdef ALTZONE
    340 	altzone = 0;
    341 #endif /* defined ALTZONE */
    342 	if (sp == NULL) {
    343 		tzname[0] = tzname[1] = (__aconst char *)__UNCONST(gmt);
    344 		return;
    345 	}
    346 	/*
    347 	** And to get the latest zone names into tzname. . .
    348 	*/
    349 	for (i = 0; i < sp->typecnt; ++i) {
    350 		const struct ttinfo * const	ttisp = &sp->ttis[i];
    351 
    352 		tzname[ttisp->tt_isdst] = &sp->chars[ttisp->tt_abbrind];
    353 #ifdef USG_COMPAT
    354 		if (ttisp->tt_isdst)
    355 			daylight = 1;
    356 		if (!ttisp->tt_isdst)
    357 			timezone = -(ttisp->tt_gmtoff);
    358 #endif /* defined USG_COMPAT */
    359 #ifdef ALTZONE
    360 		if (ttisp->tt_isdst)
    361 			altzone = -(ttisp->tt_gmtoff);
    362 #endif /* defined ALTZONE */
    363 	}
    364 	settzname_z(sp);
    365 }
    366 
    367 static int
    368 differ_by_repeat(const time_t t1, const time_t t0)
    369 {
    370 	if (TYPE_BIT(time_t) - TYPE_SIGNED(time_t) < SECSPERREPEAT_BITS)
    371 		return 0;
    372 	return (int_fast64_t)t1 - (int_fast64_t)t0 == SECSPERREPEAT;
    373 }
    374 
    375 static int
    376 tzload(timezone_t sp, const char *name, const int doextend)
    377 {
    378 	const char *		p;
    379 	int			i;
    380 	int			fid;
    381 	int			stored;
    382 	ssize_t			nread;
    383 	typedef union {
    384 		struct tzhead	tzhead;
    385 		char		buf[2 * sizeof(struct tzhead) +
    386 					2 * sizeof *sp +
    387 					4 * TZ_MAX_TIMES];
    388 	} u_t;
    389 	u_t *			up;
    390 
    391 	up = calloc(1, sizeof *up);
    392 	if (up == NULL)
    393 		return -1;
    394 
    395 	sp->goback = sp->goahead = FALSE;
    396 	if (name == NULL && (name = TZDEFAULT) == NULL)
    397 		goto oops;
    398 	{
    399 		int	doaccess;
    400 		/*
    401 		** Section 4.9.1 of the C standard says that
    402 		** "FILENAME_MAX expands to an integral constant expression
    403 		** that is the size needed for an array of char large enough
    404 		** to hold the longest file name string that the implementation
    405 		** guarantees can be opened."
    406 		*/
    407 		char		fullname[FILENAME_MAX + 1];
    408 
    409 		if (name[0] == ':')
    410 			++name;
    411 		doaccess = name[0] == '/';
    412 		if (!doaccess) {
    413 			if ((p = TZDIR) == NULL)
    414 				goto oops;
    415 			if ((strlen(p) + strlen(name) + 1) >= sizeof fullname)
    416 				goto oops;
    417 			(void) strcpy(fullname, p);	/* XXX strcpy is safe */
    418 			(void) strcat(fullname, "/");	/* XXX strcat is safe */
    419 			(void) strcat(fullname, name);	/* XXX strcat is safe */
    420 			/*
    421 			** Set doaccess if '.' (as in "../") shows up in name.
    422 			*/
    423 			if (strchr(name, '.') != NULL)
    424 				doaccess = TRUE;
    425 			name = fullname;
    426 		}
    427 		if (doaccess && access(name, R_OK) != 0)
    428 			goto oops;
    429 		/*
    430 		 * XXX potential security problem here if user of a set-id
    431 		 * program has set TZ (which is passed in as name) here,
    432 		 * and uses a race condition trick to defeat the access(2)
    433 		 * above.
    434 		 */
    435 		if ((fid = open(name, OPEN_MODE)) == -1)
    436 			goto oops;
    437 	}
    438 	nread = read(fid, up->buf, sizeof up->buf);
    439 	if (close(fid) < 0 || nread <= 0)
    440 		goto oops;
    441 	for (stored = 4; stored <= 8; stored *= 2) {
    442 		int		ttisstdcnt;
    443 		int		ttisgmtcnt;
    444 		int		timecnt;
    445 
    446 		ttisstdcnt = (int) detzcode(up->tzhead.tzh_ttisstdcnt);
    447 		ttisgmtcnt = (int) detzcode(up->tzhead.tzh_ttisgmtcnt);
    448 		sp->leapcnt = (int) detzcode(up->tzhead.tzh_leapcnt);
    449 		sp->timecnt = (int) detzcode(up->tzhead.tzh_timecnt);
    450 		sp->typecnt = (int) detzcode(up->tzhead.tzh_typecnt);
    451 		sp->charcnt = (int) detzcode(up->tzhead.tzh_charcnt);
    452 		p = up->tzhead.tzh_charcnt + sizeof up->tzhead.tzh_charcnt;
    453 		if (sp->leapcnt < 0 || sp->leapcnt > TZ_MAX_LEAPS ||
    454 			sp->typecnt <= 0 || sp->typecnt > TZ_MAX_TYPES ||
    455 			sp->timecnt < 0 || sp->timecnt > TZ_MAX_TIMES ||
    456 			sp->charcnt < 0 || sp->charcnt > TZ_MAX_CHARS ||
    457 			(ttisstdcnt != sp->typecnt && ttisstdcnt != 0) ||
    458 			(ttisgmtcnt != sp->typecnt && ttisgmtcnt != 0))
    459 				goto oops;
    460 		if (nread - (p - up->buf) <
    461 			sp->timecnt * stored +		/* ats */
    462 			sp->timecnt +			/* types */
    463 			sp->typecnt * 6 +		/* ttinfos */
    464 			sp->charcnt +			/* chars */
    465 			sp->leapcnt * (stored + 4) +	/* lsinfos */
    466 			ttisstdcnt +			/* ttisstds */
    467 			ttisgmtcnt)			/* ttisgmts */
    468 				goto oops;
    469 		timecnt = 0;
    470 		for (i = 0; i < sp->timecnt; ++i) {
    471 			int_fast64_t at
    472 			  = stored == 4 ? detzcode(p) : detzcode64(p);
    473 			sp->types[i] = ((TYPE_SIGNED(time_t)
    474 					 ? time_t_min <= at
    475 					 : 0 <= at)
    476 					&& at <= time_t_max);
    477 			if (sp->types[i]) {
    478 				if (i && !timecnt && at != time_t_min) {
    479 					/*
    480 					** Keep the earlier record, but tweak
    481 					** it so that it starts with the
    482 					** minimum time_t value.
    483 					*/
    484 					sp->types[i - 1] = 1;
    485 					sp->ats[timecnt++] = time_t_min;
    486 				}
    487 				_DIAGASSERT(__type_fit(time_t, at));
    488 				sp->ats[timecnt++] = (time_t)at;
    489 			}
    490 			p += stored;
    491 		}
    492 		timecnt = 0;
    493 		for (i = 0; i < sp->timecnt; ++i) {
    494 			unsigned char typ = *p++;
    495 			if (sp->typecnt <= typ)
    496 				goto oops;
    497 			if (sp->types[i])
    498 				sp->types[timecnt++] = typ;
    499 		}
    500 		for (i = 0; i < sp->typecnt; ++i) {
    501 			struct ttinfo *	ttisp;
    502 
    503 			ttisp = &sp->ttis[i];
    504 			ttisp->tt_gmtoff = detzcode(p);
    505 			p += 4;
    506 			ttisp->tt_isdst = (unsigned char) *p++;
    507 			if (ttisp->tt_isdst != 0 && ttisp->tt_isdst != 1)
    508 				goto oops;
    509 			ttisp->tt_abbrind = (unsigned char) *p++;
    510 			if (ttisp->tt_abbrind < 0 ||
    511 				ttisp->tt_abbrind > sp->charcnt)
    512 					goto oops;
    513 		}
    514 		for (i = 0; i < sp->charcnt; ++i)
    515 			sp->chars[i] = *p++;
    516 		sp->chars[i] = '\0';	/* ensure '\0' at end */
    517 		for (i = 0; i < sp->leapcnt; ++i) {
    518 			struct lsinfo *	lsisp;
    519 
    520 			lsisp = &sp->lsis[i];
    521 			lsisp->ls_trans = (time_t)((stored == 4) ?
    522 			    detzcode(p) : detzcode64(p));
    523 			p += stored;
    524 			lsisp->ls_corr = detzcode(p);
    525 			p += 4;
    526 		}
    527 		for (i = 0; i < sp->typecnt; ++i) {
    528 			struct ttinfo *	ttisp;
    529 
    530 			ttisp = &sp->ttis[i];
    531 			if (ttisstdcnt == 0)
    532 				ttisp->tt_ttisstd = FALSE;
    533 			else {
    534 				ttisp->tt_ttisstd = *p++;
    535 				if (ttisp->tt_ttisstd != TRUE &&
    536 					ttisp->tt_ttisstd != FALSE)
    537 						goto oops;
    538 			}
    539 		}
    540 		for (i = 0; i < sp->typecnt; ++i) {
    541 			struct ttinfo *	ttisp;
    542 
    543 			ttisp = &sp->ttis[i];
    544 			if (ttisgmtcnt == 0)
    545 				ttisp->tt_ttisgmt = FALSE;
    546 			else {
    547 				ttisp->tt_ttisgmt = *p++;
    548 				if (ttisp->tt_ttisgmt != TRUE &&
    549 					ttisp->tt_ttisgmt != FALSE)
    550 						goto oops;
    551 			}
    552 		}
    553 		/*
    554 		** If this is an old file, we're done.
    555 		*/
    556 		if (up->tzhead.tzh_version[0] == '\0')
    557 			break;
    558 		nread -= p - up->buf;
    559 		for (i = 0; i < nread; ++i)
    560 			up->buf[i] = p[i];
    561 		/*
    562 		** If this is a signed narrow time_t system, we're done.
    563 		*/
    564 		if (TYPE_SIGNED(time_t) && stored >= (int) sizeof(time_t))
    565 			break;
    566 	}
    567 	if (doextend && nread > 2 &&
    568 		up->buf[0] == '\n' && up->buf[nread - 1] == '\n' &&
    569 		sp->typecnt + 2 <= TZ_MAX_TYPES) {
    570 			struct __state ts;
    571 			int	result;
    572 
    573 			up->buf[nread - 1] = '\0';
    574 			result = tzparse(&ts, &up->buf[1], FALSE);
    575 			if (result == 0 && ts.typecnt == 2 &&
    576 				sp->charcnt + ts.charcnt <= TZ_MAX_CHARS) {
    577 					for (i = 0; i < 2; ++i)
    578 						ts.ttis[i].tt_abbrind +=
    579 							sp->charcnt;
    580 					for (i = 0; i < ts.charcnt; ++i)
    581 						sp->chars[sp->charcnt++] =
    582 							ts.chars[i];
    583 					i = 0;
    584 					while (i < ts.timecnt &&
    585 						ts.ats[i] <=
    586 						sp->ats[sp->timecnt - 1])
    587 							++i;
    588 					while (i < ts.timecnt &&
    589 					    sp->timecnt < TZ_MAX_TIMES) {
    590 						sp->ats[sp->timecnt] =
    591 							ts.ats[i];
    592 						sp->types[sp->timecnt] =
    593 							sp->typecnt +
    594 							ts.types[i];
    595 						++sp->timecnt;
    596 						++i;
    597 					}
    598 					sp->ttis[sp->typecnt++] = ts.ttis[0];
    599 					sp->ttis[sp->typecnt++] = ts.ttis[1];
    600 			}
    601 	}
    602 	if (sp->timecnt > 1) {
    603 		for (i = 1; i < sp->timecnt; ++i)
    604 			if (typesequiv(sp, sp->types[i], sp->types[0]) &&
    605 				differ_by_repeat(sp->ats[i], sp->ats[0])) {
    606 					sp->goback = TRUE;
    607 					break;
    608 				}
    609 		for (i = sp->timecnt - 2; i >= 0; --i)
    610 			if (typesequiv(sp, sp->types[sp->timecnt - 1],
    611 				sp->types[i]) &&
    612 				differ_by_repeat(sp->ats[sp->timecnt - 1],
    613 				sp->ats[i])) {
    614 					sp->goahead = TRUE;
    615 					break;
    616 		}
    617 	}
    618 	/*
    619 	** If type 0 is is unused in transitions,
    620 	** it's the type to use for early times.
    621 	*/
    622 	for (i = 0; i < sp->typecnt; ++i)
    623 		if (sp->types[i] == 0)
    624 			break;
    625 	i = (i >= sp->typecnt) ? 0 : -1;
    626 	/*
    627 	** Absent the above,
    628 	** if there are transition times
    629 	** and the first transition is to a daylight time
    630 	** find the standard type less than and closest to
    631 	** the type of the first transition.
    632 	*/
    633 	if (i < 0 && sp->timecnt > 0 && sp->ttis[sp->types[0]].tt_isdst) {
    634 		i = sp->types[0];
    635 		while (--i >= 0)
    636 			if (!sp->ttis[i].tt_isdst)
    637 				break;
    638 	}
    639 	/*
    640 	** If no result yet, find the first standard type.
    641 	** If there is none, punt to type zero.
    642 	*/
    643 	if (i < 0) {
    644 		i = 0;
    645 		while (sp->ttis[i].tt_isdst)
    646 			if (++i >= sp->typecnt) {
    647 				i = 0;
    648 				break;
    649 			}
    650 	}
    651 	sp->defaulttype = i;
    652 	free(up);
    653 	return 0;
    654 oops:
    655 	free(up);
    656 	return -1;
    657 }
    658 
    659 static int
    660 typesequiv(const timezone_t sp, const int a, const int b)
    661 {
    662 	int	result;
    663 
    664 	if (sp == NULL ||
    665 		a < 0 || a >= sp->typecnt ||
    666 		b < 0 || b >= sp->typecnt)
    667 			result = FALSE;
    668 	else {
    669 		const struct ttinfo *	ap = &sp->ttis[a];
    670 		const struct ttinfo *	bp = &sp->ttis[b];
    671 		result = ap->tt_gmtoff == bp->tt_gmtoff &&
    672 			ap->tt_isdst == bp->tt_isdst &&
    673 			ap->tt_ttisstd == bp->tt_ttisstd &&
    674 			ap->tt_ttisgmt == bp->tt_ttisgmt &&
    675 			strcmp(&sp->chars[ap->tt_abbrind],
    676 			&sp->chars[bp->tt_abbrind]) == 0;
    677 	}
    678 	return result;
    679 }
    680 
    681 static const int	mon_lengths[2][MONSPERYEAR] = {
    682 	{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
    683 	{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
    684 };
    685 
    686 static const int	year_lengths[2] = {
    687 	DAYSPERNYEAR, DAYSPERLYEAR
    688 };
    689 
    690 /*
    691 ** Given a pointer into a time zone string, scan until a character that is not
    692 ** a valid character in a zone name is found. Return a pointer to that
    693 ** character.
    694 */
    695 
    696 static const char *
    697 getzname(const char *strp)
    698 {
    699 	char	c;
    700 
    701 	while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
    702 		c != '+')
    703 			++strp;
    704 	return strp;
    705 }
    706 
    707 /*
    708 ** Given a pointer into an extended time zone string, scan until the ending
    709 ** delimiter of the zone name is located. Return a pointer to the delimiter.
    710 **
    711 ** As with getzname above, the legal character set is actually quite
    712 ** restricted, with other characters producing undefined results.
    713 ** We don't do any checking here; checking is done later in common-case code.
    714 */
    715 
    716 static const char *
    717 getqzname(const char *strp, const int delim)
    718 {
    719 	int	c;
    720 
    721 	while ((c = *strp) != '\0' && c != delim)
    722 		++strp;
    723 	return strp;
    724 }
    725 
    726 /*
    727 ** Given a pointer into a time zone string, extract a number from that string.
    728 ** Check that the number is within a specified range; if it is not, return
    729 ** NULL.
    730 ** Otherwise, return a pointer to the first character not part of the number.
    731 */
    732 
    733 static const char *
    734 getnum(const char *strp, int *const nump, const int min, const int max)
    735 {
    736 	char	c;
    737 	int	num;
    738 
    739 	if (strp == NULL || !is_digit(c = *strp)) {
    740 		errno = EINVAL;
    741 		return NULL;
    742 	}
    743 	num = 0;
    744 	do {
    745 		num = num * 10 + (c - '0');
    746 		if (num > max) {
    747 			errno = EOVERFLOW;
    748 			return NULL;	/* illegal value */
    749 		}
    750 		c = *++strp;
    751 	} while (is_digit(c));
    752 	if (num < min) {
    753 		errno = EINVAL;
    754 		return NULL;		/* illegal value */
    755 	}
    756 	*nump = num;
    757 	return strp;
    758 }
    759 
    760 /*
    761 ** Given a pointer into a time zone string, extract a number of seconds,
    762 ** in hh[:mm[:ss]] form, from the string.
    763 ** If any error occurs, return NULL.
    764 ** Otherwise, return a pointer to the first character not part of the number
    765 ** of seconds.
    766 */
    767 
    768 static const char *
    769 getsecs(const char *strp, int_fast32_t *const secsp)
    770 {
    771 	int	num;
    772 
    773 	/*
    774 	** `HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
    775 	** "M10.4.6/26", which does not conform to Posix,
    776 	** but which specifies the equivalent of
    777 	** ``02:00 on the first Sunday on or after 23 Oct''.
    778 	*/
    779 	strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
    780 	if (strp == NULL)
    781 		return NULL;
    782 	*secsp = num * (int_fast32_t) SECSPERHOUR;
    783 	if (*strp == ':') {
    784 		++strp;
    785 		strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
    786 		if (strp == NULL)
    787 			return NULL;
    788 		*secsp += num * SECSPERMIN;
    789 		if (*strp == ':') {
    790 			++strp;
    791 			/* `SECSPERMIN' allows for leap seconds. */
    792 			strp = getnum(strp, &num, 0, SECSPERMIN);
    793 			if (strp == NULL)
    794 				return NULL;
    795 			*secsp += num;
    796 		}
    797 	}
    798 	return strp;
    799 }
    800 
    801 /*
    802 ** Given a pointer into a time zone string, extract an offset, in
    803 ** [+-]hh[:mm[:ss]] form, from the string.
    804 ** If any error occurs, return NULL.
    805 ** Otherwise, return a pointer to the first character not part of the time.
    806 */
    807 
    808 static const char *
    809 getoffset(const char *strp, int_fast32_t *const offsetp)
    810 {
    811 	int	neg = 0;
    812 
    813 	if (*strp == '-') {
    814 		neg = 1;
    815 		++strp;
    816 	} else if (*strp == '+')
    817 		++strp;
    818 	strp = getsecs(strp, offsetp);
    819 	if (strp == NULL)
    820 		return NULL;		/* illegal time */
    821 	if (neg)
    822 		*offsetp = -*offsetp;
    823 	return strp;
    824 }
    825 
    826 /*
    827 ** Given a pointer into a time zone string, extract a rule in the form
    828 ** date[/time]. See POSIX section 8 for the format of "date" and "time".
    829 ** If a valid rule is not found, return NULL.
    830 ** Otherwise, return a pointer to the first character not part of the rule.
    831 */
    832 
    833 static const char *
    834 getrule(const char *strp, struct rule *const rulep)
    835 {
    836 	if (*strp == 'J') {
    837 		/*
    838 		** Julian day.
    839 		*/
    840 		rulep->r_type = JULIAN_DAY;
    841 		++strp;
    842 		strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
    843 	} else if (*strp == 'M') {
    844 		/*
    845 		** Month, week, day.
    846 		*/
    847 		rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
    848 		++strp;
    849 		strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
    850 		if (strp == NULL)
    851 			return NULL;
    852 		if (*strp++ != '.')
    853 			return NULL;
    854 		strp = getnum(strp, &rulep->r_week, 1, 5);
    855 		if (strp == NULL)
    856 			return NULL;
    857 		if (*strp++ != '.')
    858 			return NULL;
    859 		strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
    860 	} else if (is_digit(*strp)) {
    861 		/*
    862 		** Day of year.
    863 		*/
    864 		rulep->r_type = DAY_OF_YEAR;
    865 		strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
    866 	} else	return NULL;		/* invalid format */
    867 	if (strp == NULL)
    868 		return NULL;
    869 	if (*strp == '/') {
    870 		/*
    871 		** Time specified.
    872 		*/
    873 		++strp;
    874 		strp = getoffset(strp, &rulep->r_time);
    875 	} else	rulep->r_time = 2 * SECSPERHOUR;	/* default = 2:00:00 */
    876 	return strp;
    877 }
    878 
    879 /*
    880 ** Given a year, a rule, and the offset from UT at the time that rule takes
    881 ** effect, calculate the year-relative time that rule takes effect.
    882 */
    883 
    884 static int_fast32_t
    885 transtime(const int year, const struct rule *const rulep,
    886 	  const int_fast32_t offset)
    887 {
    888 	int	leapyear;
    889 	int_fast32_t	value;
    890 	int	i;
    891 	int		d, m1, yy0, yy1, yy2, dow;
    892 
    893 	INITIALIZE(value);
    894 	leapyear = isleap(year);
    895 	switch (rulep->r_type) {
    896 
    897 	case JULIAN_DAY:
    898 		/*
    899 		** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
    900 		** years.
    901 		** In non-leap years, or if the day number is 59 or less, just
    902 		** add SECSPERDAY times the day number-1 to the time of
    903 		** January 1, midnight, to get the day.
    904 		*/
    905 		value = (rulep->r_day - 1) * SECSPERDAY;
    906 		if (leapyear && rulep->r_day >= 60)
    907 			value += SECSPERDAY;
    908 		break;
    909 
    910 	case DAY_OF_YEAR:
    911 		/*
    912 		** n - day of year.
    913 		** Just add SECSPERDAY times the day number to the time of
    914 		** January 1, midnight, to get the day.
    915 		*/
    916 		value = rulep->r_day * SECSPERDAY;
    917 		break;
    918 
    919 	case MONTH_NTH_DAY_OF_WEEK:
    920 		/*
    921 		** Mm.n.d - nth "dth day" of month m.
    922 		*/
    923 
    924 		/*
    925 		** Use Zeller's Congruence to get day-of-week of first day of
    926 		** month.
    927 		*/
    928 		m1 = (rulep->r_mon + 9) % 12 + 1;
    929 		yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
    930 		yy1 = yy0 / 100;
    931 		yy2 = yy0 % 100;
    932 		dow = ((26 * m1 - 2) / 10 +
    933 			1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
    934 		if (dow < 0)
    935 			dow += DAYSPERWEEK;
    936 
    937 		/*
    938 		** "dow" is the day-of-week of the first day of the month. Get
    939 		** the day-of-month (zero-origin) of the first "dow" day of the
    940 		** month.
    941 		*/
    942 		d = rulep->r_day - dow;
    943 		if (d < 0)
    944 			d += DAYSPERWEEK;
    945 		for (i = 1; i < rulep->r_week; ++i) {
    946 			if (d + DAYSPERWEEK >=
    947 				mon_lengths[leapyear][rulep->r_mon - 1])
    948 					break;
    949 			d += DAYSPERWEEK;
    950 		}
    951 
    952 		/*
    953 		** "d" is the day-of-month (zero-origin) of the day we want.
    954 		*/
    955 		value = d * SECSPERDAY;
    956 		for (i = 0; i < rulep->r_mon - 1; ++i)
    957 			value += mon_lengths[leapyear][i] * SECSPERDAY;
    958 		break;
    959 	}
    960 
    961 	/*
    962 	** "value" is the year-relative time of 00:00:00 UT on the day in
    963 	** question. To get the year-relative time of the specified local
    964 	** time on that day, add the transition time and the current offset
    965 	** from UT.
    966 	*/
    967 	return value + rulep->r_time + offset;
    968 }
    969 
    970 /*
    971 ** Given a POSIX section 8-style TZ string, fill in the rule tables as
    972 ** appropriate.
    973 */
    974 
    975 static int
    976 tzparse(timezone_t sp, const char *name, const int lastditch)
    977 {
    978 	const char *		stdname;
    979 	const char *		dstname;
    980 	size_t			stdlen;
    981 	size_t			dstlen;
    982 	int_fast32_t		stdoffset;
    983 	int_fast32_t		dstoffset;
    984 	char *			cp;
    985 	int			load_result;
    986 
    987 	INITIALIZE(dstname);
    988 	stdname = name;
    989 	if (lastditch) {
    990 		stdlen = strlen(name);	/* length of standard zone name */
    991 		name += stdlen;
    992 		if (stdlen >= sizeof sp->chars)
    993 			stdlen = (sizeof sp->chars) - 1;
    994 		stdoffset = 0;
    995 	} else {
    996 		if (*name == '<') {
    997 			name++;
    998 			stdname = name;
    999 			name = getqzname(name, '>');
   1000 			if (*name != '>')
   1001 				return (-1);
   1002 			stdlen = name - stdname;
   1003 			name++;
   1004 		} else {
   1005 			name = getzname(name);
   1006 			stdlen = name - stdname;
   1007 		}
   1008 		if (*name == '\0')
   1009 			return -1;
   1010 		name = getoffset(name, &stdoffset);
   1011 		if (name == NULL)
   1012 			return -1;
   1013 	}
   1014 	load_result = tzload(sp, TZDEFRULES, FALSE);
   1015 	if (load_result != 0)
   1016 		sp->leapcnt = 0;		/* so, we're off a little */
   1017 	if (*name != '\0') {
   1018 		if (*name == '<') {
   1019 			dstname = ++name;
   1020 			name = getqzname(name, '>');
   1021 			if (*name != '>')
   1022 				return -1;
   1023 			dstlen = name - dstname;
   1024 			name++;
   1025 		} else {
   1026 			dstname = name;
   1027 			name = getzname(name);
   1028 			dstlen = name - dstname; /* length of DST zone name */
   1029 		}
   1030 		if (*name != '\0' && *name != ',' && *name != ';') {
   1031 			name = getoffset(name, &dstoffset);
   1032 			if (name == NULL)
   1033 				return -1;
   1034 		} else	dstoffset = stdoffset - SECSPERHOUR;
   1035 		if (*name == '\0' && load_result != 0)
   1036 			name = TZDEFRULESTRING;
   1037 		if (*name == ',' || *name == ';') {
   1038 			struct rule	start;
   1039 			struct rule	end;
   1040 			int		year;
   1041 			int		yearlim;
   1042 			int		timecnt;
   1043 			time_t		janfirst;
   1044 
   1045 			++name;
   1046 			if ((name = getrule(name, &start)) == NULL)
   1047 				return -1;
   1048 			if (*name++ != ',')
   1049 				return -1;
   1050 			if ((name = getrule(name, &end)) == NULL)
   1051 				return -1;
   1052 			if (*name != '\0')
   1053 				return -1;
   1054 			sp->typecnt = 2;	/* standard time and DST */
   1055 			/*
   1056 			** Two transitions per year, from EPOCH_YEAR forward.
   1057 			*/
   1058 			memset(sp->ttis, 0, sizeof(sp->ttis));
   1059 			sp->ttis[0].tt_gmtoff = -dstoffset;
   1060 			sp->ttis[0].tt_isdst = 1;
   1061 			sp->ttis[0].tt_abbrind = (int)(stdlen + 1);
   1062 			sp->ttis[1].tt_gmtoff = -stdoffset;
   1063 			sp->ttis[1].tt_isdst = 0;
   1064 			sp->ttis[1].tt_abbrind = 0;
   1065 			timecnt = 0;
   1066 			janfirst = 0;
   1067 			sp->timecnt = 0;
   1068 			yearlim = EPOCH_YEAR + YEARSPERREPEAT;
   1069 			for (year = EPOCH_YEAR; year < yearlim; year++) {
   1070 				int_fast32_t
   1071 				  starttime = transtime(year, &start, stdoffset),
   1072 				  endtime = transtime(year, &end, dstoffset);
   1073 				int_fast32_t
   1074 				  yearsecs = (year_lengths[isleap(year)]
   1075 					      * SECSPERDAY);
   1076 				int reversed = endtime < starttime;
   1077 				if (reversed) {
   1078 					int_fast32_t swap = starttime;
   1079 					starttime = endtime;
   1080 					endtime = swap;
   1081 				}
   1082 				if (reversed
   1083 				    || (starttime < endtime
   1084 					&& (endtime - starttime
   1085 					    < (yearsecs
   1086 					       + (stdoffset - dstoffset))))) {
   1087 					if (TZ_MAX_TIMES - 2 < timecnt)
   1088 						break;
   1089 					yearlim = year + YEARSPERREPEAT + 1;
   1090 					sp->ats[timecnt] = janfirst;
   1091 					if (increment_overflow_time
   1092 					    (&sp->ats[timecnt], starttime))
   1093 						break;
   1094 					sp->types[timecnt++] = reversed;
   1095 					sp->ats[timecnt] = janfirst;
   1096 					if (increment_overflow_time
   1097 					    (&sp->ats[timecnt], endtime))
   1098 						break;
   1099 					sp->types[timecnt++] = !reversed;
   1100 				}
   1101 				if (increment_overflow_time(&janfirst, yearsecs))
   1102 					break;
   1103 			}
   1104 			sp->timecnt = timecnt;
   1105 			if (!timecnt)
   1106 				sp->typecnt = 1;	/* Perpetual DST.  */
   1107 		} else {
   1108 			int_fast32_t	theirstdoffset;
   1109 			int_fast32_t	theirdstoffset;
   1110 			int_fast32_t	theiroffset;
   1111 			int		isdst;
   1112 			int		i;
   1113 			int		j;
   1114 
   1115 			if (*name != '\0')
   1116 				return -1;
   1117 			/*
   1118 			** Initial values of theirstdoffset and theirdstoffset.
   1119 			*/
   1120 			theirstdoffset = 0;
   1121 			for (i = 0; i < sp->timecnt; ++i) {
   1122 				j = sp->types[i];
   1123 				if (!sp->ttis[j].tt_isdst) {
   1124 					theirstdoffset =
   1125 						-sp->ttis[j].tt_gmtoff;
   1126 					break;
   1127 				}
   1128 			}
   1129 			theirdstoffset = 0;
   1130 			for (i = 0; i < sp->timecnt; ++i) {
   1131 				j = sp->types[i];
   1132 				if (sp->ttis[j].tt_isdst) {
   1133 					theirdstoffset =
   1134 						-sp->ttis[j].tt_gmtoff;
   1135 					break;
   1136 				}
   1137 			}
   1138 			/*
   1139 			** Initially we're assumed to be in standard time.
   1140 			*/
   1141 			isdst = FALSE;
   1142 			theiroffset = theirstdoffset;
   1143 			/*
   1144 			** Now juggle transition times and types
   1145 			** tracking offsets as you do.
   1146 			*/
   1147 			for (i = 0; i < sp->timecnt; ++i) {
   1148 				j = sp->types[i];
   1149 				sp->types[i] = sp->ttis[j].tt_isdst;
   1150 				if (sp->ttis[j].tt_ttisgmt) {
   1151 					/* No adjustment to transition time */
   1152 				} else {
   1153 					/*
   1154 					** If summer time is in effect, and the
   1155 					** transition time was not specified as
   1156 					** standard time, add the summer time
   1157 					** offset to the transition time;
   1158 					** otherwise, add the standard time
   1159 					** offset to the transition time.
   1160 					*/
   1161 					/*
   1162 					** Transitions from DST to DDST
   1163 					** will effectively disappear since
   1164 					** POSIX provides for only one DST
   1165 					** offset.
   1166 					*/
   1167 					if (isdst && !sp->ttis[j].tt_ttisstd) {
   1168 						sp->ats[i] += (time_t)
   1169 						    (dstoffset - theirdstoffset);
   1170 					} else {
   1171 						sp->ats[i] += (time_t)
   1172 						    (stdoffset - theirstdoffset);
   1173 					}
   1174 				}
   1175 				theiroffset = -sp->ttis[j].tt_gmtoff;
   1176 				if (!sp->ttis[j].tt_isdst)
   1177 					theirstdoffset = theiroffset;
   1178 				else	theirdstoffset = theiroffset;
   1179 			}
   1180 			/*
   1181 			** Finally, fill in ttis.
   1182 			** ttisstd and ttisgmt need not be handled
   1183 			*/
   1184 			memset(sp->ttis, 0, sizeof(sp->ttis));
   1185 			sp->ttis[0].tt_gmtoff = -stdoffset;
   1186 			sp->ttis[0].tt_isdst = FALSE;
   1187 			sp->ttis[0].tt_abbrind = 0;
   1188 			sp->ttis[1].tt_gmtoff = -dstoffset;
   1189 			sp->ttis[1].tt_isdst = TRUE;
   1190 			sp->ttis[1].tt_abbrind = (int)(stdlen + 1);
   1191 			sp->typecnt = 2;
   1192 		}
   1193 	} else {
   1194 		dstlen = 0;
   1195 		sp->typecnt = 1;		/* only standard time */
   1196 		sp->timecnt = 0;
   1197 		memset(sp->ttis, 0, sizeof(sp->ttis));
   1198 		sp->ttis[0].tt_gmtoff = -stdoffset;
   1199 		sp->ttis[0].tt_isdst = 0;
   1200 		sp->ttis[0].tt_abbrind = 0;
   1201 	}
   1202 	sp->charcnt = (int)(stdlen + 1);
   1203 	if (dstlen != 0)
   1204 		sp->charcnt += (int)(dstlen + 1);
   1205 	if ((size_t) sp->charcnt > sizeof sp->chars)
   1206 		return -1;
   1207 	cp = sp->chars;
   1208 	(void) strncpy(cp, stdname, stdlen);
   1209 	cp += stdlen;
   1210 	*cp++ = '\0';
   1211 	if (dstlen != 0) {
   1212 		(void) strncpy(cp, dstname, dstlen);
   1213 		*(cp + dstlen) = '\0';
   1214 	}
   1215 	return 0;
   1216 }
   1217 
   1218 static void
   1219 gmtload(timezone_t sp)
   1220 {
   1221 	if (tzload(sp, gmt, TRUE) != 0)
   1222 		(void) tzparse(sp, gmt, TRUE);
   1223 }
   1224 
   1225 timezone_t
   1226 tzalloc(const char *name)
   1227 {
   1228 	timezone_t sp = calloc(1, sizeof *sp);
   1229 	if (sp == NULL)
   1230 		return NULL;
   1231 	if (tzload(sp, name, TRUE) != 0) {
   1232 		free(sp);
   1233 		return NULL;
   1234 	}
   1235 	settzname_z(sp);
   1236 	return sp;
   1237 }
   1238 
   1239 void
   1240 tzfree(const timezone_t sp)
   1241 {
   1242 	free(sp);
   1243 }
   1244 
   1245 static void
   1246 tzsetwall_unlocked(void)
   1247 {
   1248 	if (lcl_is_set < 0)
   1249 		return;
   1250 	lcl_is_set = -1;
   1251 
   1252 	if (lclptr == NULL) {
   1253 		int saveerrno = errno;
   1254 		lclptr = calloc(1, sizeof *lclptr);
   1255 		errno = saveerrno;
   1256 		if (lclptr == NULL) {
   1257 			settzname();	/* all we can do */
   1258 			return;
   1259 		}
   1260 	}
   1261 	if (tzload(lclptr, NULL, TRUE) != 0)
   1262 		gmtload(lclptr);
   1263 	settzname();
   1264 }
   1265 
   1266 #ifndef STD_INSPIRED
   1267 /*
   1268 ** A non-static declaration of tzsetwall in a system header file
   1269 ** may cause a warning about this upcoming static declaration...
   1270 */
   1271 static
   1272 #endif /* !defined STD_INSPIRED */
   1273 void
   1274 tzsetwall(void)
   1275 {
   1276 	rwlock_wrlock(&lcl_lock);
   1277 	tzsetwall_unlocked();
   1278 	rwlock_unlock(&lcl_lock);
   1279 }
   1280 
   1281 #ifndef STD_INSPIRED
   1282 /*
   1283 ** A non-static declaration of tzsetwall in a system header file
   1284 ** may cause a warning about this upcoming static declaration...
   1285 */
   1286 static
   1287 #endif /* !defined STD_INSPIRED */
   1288 void
   1289 tzset_unlocked(void)
   1290 {
   1291 	const char *	name;
   1292 
   1293 	name = getenv("TZ");
   1294 	if (name == NULL) {
   1295 		tzsetwall_unlocked();
   1296 		return;
   1297 	}
   1298 
   1299 	if (lcl_is_set > 0 && strcmp(lcl_TZname, name) == 0)
   1300 		return;
   1301 	lcl_is_set = strlen(name) < sizeof lcl_TZname;
   1302 	if (lcl_is_set)
   1303 		(void)strlcpy(lcl_TZname, name, sizeof(lcl_TZname));
   1304 
   1305 	if (lclptr == NULL) {
   1306 		int saveerrno = errno;
   1307 		lclptr = calloc(1, sizeof *lclptr);
   1308 		errno = saveerrno;
   1309 		if (lclptr == NULL) {
   1310 			settzname();	/* all we can do */
   1311 			return;
   1312 		}
   1313 	}
   1314 	if (*name == '\0') {
   1315 		/*
   1316 		** User wants it fast rather than right.
   1317 		*/
   1318 		lclptr->leapcnt = 0;		/* so, we're off a little */
   1319 		lclptr->timecnt = 0;
   1320 		lclptr->typecnt = 0;
   1321 		lclptr->ttis[0].tt_isdst = 0;
   1322 		lclptr->ttis[0].tt_gmtoff = 0;
   1323 		lclptr->ttis[0].tt_abbrind = 0;
   1324 		(void) strlcpy(lclptr->chars, gmt, sizeof(lclptr->chars));
   1325 	} else if (tzload(lclptr, name, TRUE) != 0)
   1326 		if (name[0] == ':' || tzparse(lclptr, name, FALSE) != 0)
   1327 			(void) gmtload(lclptr);
   1328 	settzname();
   1329 }
   1330 
   1331 void
   1332 tzset(void)
   1333 {
   1334 	rwlock_wrlock(&lcl_lock);
   1335 	tzset_unlocked();
   1336 	rwlock_unlock(&lcl_lock);
   1337 }
   1338 
   1339 /*
   1340 ** The easy way to behave "as if no library function calls" localtime
   1341 ** is to not call it--so we drop its guts into "localsub", which can be
   1342 ** freely called. (And no, the PANS doesn't require the above behavior--
   1343 ** but it *is* desirable.)
   1344 **
   1345 ** The unused offset argument is for the benefit of mktime variants.
   1346 */
   1347 
   1348 /*ARGSUSED*/
   1349 static struct tm *
   1350 localsub(const timezone_t sp, const time_t * const timep, const int_fast32_t offset,
   1351     struct tm *const tmp)
   1352 {
   1353 	const struct ttinfo *	ttisp;
   1354 	int			i;
   1355 	struct tm *		result;
   1356 	const time_t			t = *timep;
   1357 
   1358 	if ((sp->goback && t < sp->ats[0]) ||
   1359 		(sp->goahead && t > sp->ats[sp->timecnt - 1])) {
   1360 			time_t			newt = t;
   1361 			time_t		seconds;
   1362 			time_t		years;
   1363 
   1364 			if (t < sp->ats[0])
   1365 				seconds = sp->ats[0] - t;
   1366 			else	seconds = t - sp->ats[sp->timecnt - 1];
   1367 			--seconds;
   1368 			years = (time_t)((seconds / SECSPERREPEAT + 1) * YEARSPERREPEAT);
   1369 			seconds = (time_t)(years * AVGSECSPERYEAR);
   1370 			if (t < sp->ats[0])
   1371 				newt += seconds;
   1372 			else	newt -= seconds;
   1373 			if (newt < sp->ats[0] ||
   1374 				newt > sp->ats[sp->timecnt - 1])
   1375 					return NULL;	/* "cannot happen" */
   1376 			result = localsub(sp, &newt, offset, tmp);
   1377 			if (result == tmp) {
   1378 				time_t	newy;
   1379 
   1380 				newy = tmp->tm_year;
   1381 				if (t < sp->ats[0])
   1382 					newy -= years;
   1383 				else	newy += years;
   1384 				tmp->tm_year = (int)newy;
   1385 				if (tmp->tm_year != newy)
   1386 					return NULL;
   1387 			}
   1388 			return result;
   1389 	}
   1390 	if (sp->timecnt == 0 || t < sp->ats[0]) {
   1391 		i = sp->defaulttype;
   1392 	} else {
   1393 		int	lo = 1;
   1394 		int	hi = sp->timecnt;
   1395 
   1396 		while (lo < hi) {
   1397 			int	mid = (lo + hi) / 2;
   1398 
   1399 			if (t < sp->ats[mid])
   1400 				hi = mid;
   1401 			else	lo = mid + 1;
   1402 		}
   1403 		i = (int) sp->types[lo - 1];
   1404 	}
   1405 	ttisp = &sp->ttis[i];
   1406 	/*
   1407 	** To get (wrong) behavior that's compatible with System V Release 2.0
   1408 	** you'd replace the statement below with
   1409 	**	t += ttisp->tt_gmtoff;
   1410 	**	timesub(&t, 0L, sp, tmp);
   1411 	*/
   1412 	result = timesub(sp, &t, ttisp->tt_gmtoff, tmp);
   1413 	tmp->tm_isdst = ttisp->tt_isdst;
   1414 	if (sp == lclptr)
   1415 		tzname[tmp->tm_isdst] = &sp->chars[ttisp->tt_abbrind];
   1416 #ifdef TM_ZONE
   1417 	tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
   1418 #endif /* defined TM_ZONE */
   1419 	return result;
   1420 }
   1421 
   1422 /*
   1423 ** Re-entrant version of localtime.
   1424 */
   1425 
   1426 struct tm *
   1427 localtime_r(const time_t * __restrict timep, struct tm *tmp)
   1428 {
   1429 	rwlock_rdlock(&lcl_lock);
   1430 	tzset_unlocked();
   1431 	tmp = localtime_rz(lclptr, timep, tmp);
   1432 	rwlock_unlock(&lcl_lock);
   1433 	return tmp;
   1434 }
   1435 
   1436 struct tm *
   1437 localtime(const time_t *const timep)
   1438 {
   1439 	return localtime_r(timep, &tm);
   1440 }
   1441 
   1442 struct tm *
   1443 localtime_rz(const timezone_t sp, const time_t * __restrict timep, struct tm *tmp)
   1444 {
   1445 	if (sp == NULL)
   1446 		tmp = gmtsub(NULL, timep, 0, tmp);
   1447 	else
   1448 		tmp = localsub(sp, timep, 0, tmp);
   1449 	if (tmp == NULL)
   1450 		errno = EOVERFLOW;
   1451 	return tmp;
   1452 }
   1453 
   1454 /*
   1455 ** gmtsub is to gmtime as localsub is to localtime.
   1456 */
   1457 
   1458 static struct tm *
   1459 gmtsub(const timezone_t sp, const time_t *const timep,
   1460     const int_fast32_t offset, struct tm *const tmp)
   1461 {
   1462 	struct tm *	result;
   1463 #ifdef _REENTRANT
   1464 	static mutex_t gmt_mutex = MUTEX_INITIALIZER;
   1465 #endif
   1466 
   1467 	mutex_lock(&gmt_mutex);
   1468 	if (!gmt_is_set) {
   1469 		int saveerrno;
   1470 		gmt_is_set = TRUE;
   1471 		saveerrno = errno;
   1472 		gmtptr = calloc(1, sizeof *gmtptr);
   1473 		errno = saveerrno;
   1474 		if (gmtptr != NULL)
   1475 			gmtload(gmtptr);
   1476 	}
   1477 	mutex_unlock(&gmt_mutex);
   1478 	result = timesub(gmtptr, timep, offset, tmp);
   1479 #ifdef TM_ZONE
   1480 	/*
   1481 	** Could get fancy here and deliver something such as
   1482 	** "UT+xxxx" or "UT-xxxx" if offset is non-zero,
   1483 	** but this is no time for a treasure hunt.
   1484 	*/
   1485 	if (offset != 0)
   1486 		tmp->TM_ZONE = (__aconst char *)__UNCONST(wildabbr);
   1487 	else {
   1488 		if (gmtptr == NULL)
   1489 			tmp->TM_ZONE = (__aconst char *)__UNCONST(gmt);
   1490 		else	tmp->TM_ZONE = gmtptr->chars;
   1491 	}
   1492 #endif /* defined TM_ZONE */
   1493 	return result;
   1494 }
   1495 
   1496 struct tm *
   1497 gmtime(const time_t *const timep)
   1498 {
   1499 	struct tm *tmp = gmtsub(NULL, timep, 0, &tm);
   1500 
   1501 	if (tmp == NULL)
   1502 		errno = EOVERFLOW;
   1503 
   1504 	return tmp;
   1505 }
   1506 
   1507 /*
   1508 ** Re-entrant version of gmtime.
   1509 */
   1510 
   1511 struct tm *
   1512 gmtime_r(const time_t * const timep, struct tm *tmp)
   1513 {
   1514 	tmp = gmtsub(NULL, timep, 0, tmp);
   1515 
   1516 	if (tmp == NULL)
   1517 		errno = EOVERFLOW;
   1518 
   1519 	return tmp;
   1520 }
   1521 
   1522 #ifdef STD_INSPIRED
   1523 
   1524 struct tm *
   1525 offtime(const time_t *const timep, long offset)
   1526 {
   1527 	struct tm *tmp;
   1528 
   1529 	if ((offset > 0 && offset > INT_FAST32_MAX) ||
   1530 	    (offset < 0 && offset < INT_FAST32_MIN)) {
   1531 		errno = EOVERFLOW;
   1532 		return NULL;
   1533 	}
   1534 	tmp = gmtsub(NULL, timep, (int_fast32_t)offset, &tm);
   1535 
   1536 	if (tmp == NULL)
   1537 		errno = EOVERFLOW;
   1538 
   1539 	return tmp;
   1540 }
   1541 
   1542 struct tm *
   1543 offtime_r(const time_t *timep, long offset, struct tm *tmp)
   1544 {
   1545 	if ((offset > 0 && offset > INT_FAST32_MAX) ||
   1546 	    (offset < 0 && offset < INT_FAST32_MIN)) {
   1547 		errno = EOVERFLOW;
   1548 		return NULL;
   1549 	}
   1550 	tmp = gmtsub(NULL, timep, (int_fast32_t)offset, tmp);
   1551 
   1552 	if (tmp == NULL)
   1553 		errno = EOVERFLOW;
   1554 
   1555 	return tmp;
   1556 }
   1557 
   1558 #endif /* defined STD_INSPIRED */
   1559 
   1560 /*
   1561 ** Return the number of leap years through the end of the given year
   1562 ** where, to make the math easy, the answer for year zero is defined as zero.
   1563 */
   1564 
   1565 static int
   1566 leaps_thru_end_of(const int y)
   1567 {
   1568 	return (y >= 0) ? (y / 4 - y / 100 + y / 400) :
   1569 		-(leaps_thru_end_of(-(y + 1)) + 1);
   1570 }
   1571 
   1572 static struct tm *
   1573 timesub(const timezone_t sp, const time_t *const timep,
   1574     const int_fast32_t offset, struct tm *const tmp)
   1575 {
   1576 	const struct lsinfo *	lp;
   1577 	time_t			tdays;
   1578 	int			idays;	/* unsigned would be so 2003 */
   1579 	int_fast64_t		rem;
   1580 	int			y;
   1581 	const int *		ip;
   1582 	int_fast64_t		corr;
   1583 	int			hit;
   1584 	int			i;
   1585 
   1586 	corr = 0;
   1587 	hit = 0;
   1588 	i = (sp == NULL) ? 0 : sp->leapcnt;
   1589 	while (--i >= 0) {
   1590 		lp = &sp->lsis[i];
   1591 		if (*timep >= lp->ls_trans) {
   1592 			if (*timep == lp->ls_trans) {
   1593 				hit = ((i == 0 && lp->ls_corr > 0) ||
   1594 					lp->ls_corr > sp->lsis[i - 1].ls_corr);
   1595 				if (hit)
   1596 					while (i > 0 &&
   1597 						sp->lsis[i].ls_trans ==
   1598 						sp->lsis[i - 1].ls_trans + 1 &&
   1599 						sp->lsis[i].ls_corr ==
   1600 						sp->lsis[i - 1].ls_corr + 1) {
   1601 							++hit;
   1602 							--i;
   1603 					}
   1604 			}
   1605 			corr = lp->ls_corr;
   1606 			break;
   1607 		}
   1608 	}
   1609 	y = EPOCH_YEAR;
   1610 	tdays = (time_t)(*timep / SECSPERDAY);
   1611 	rem = (int_fast64_t) (*timep - tdays * SECSPERDAY);
   1612 	while (tdays < 0 || tdays >= year_lengths[isleap(y)]) {
   1613 		int		newy;
   1614 		time_t	tdelta;
   1615 		int	idelta;
   1616 		int	leapdays;
   1617 
   1618 		tdelta = tdays / DAYSPERLYEAR;
   1619 		if (! ((! TYPE_SIGNED(time_t) || INT_MIN <= tdelta)
   1620 		       && tdelta <= INT_MAX))
   1621 			return NULL;
   1622 		_DIAGASSERT(__type_fit(int, tdelta));
   1623 		idelta = (int)tdelta;
   1624 		if (idelta == 0)
   1625 			idelta = (tdays < 0) ? -1 : 1;
   1626 		newy = y;
   1627 		if (increment_overflow(&newy, idelta))
   1628 			return NULL;
   1629 		leapdays = leaps_thru_end_of(newy - 1) -
   1630 			leaps_thru_end_of(y - 1);
   1631 		tdays -= ((time_t) newy - y) * DAYSPERNYEAR;
   1632 		tdays -= leapdays;
   1633 		y = newy;
   1634 	}
   1635 	{
   1636 		int_fast32_t seconds;
   1637 
   1638 		seconds = (int_fast32_t)(tdays * SECSPERDAY);
   1639 		tdays = (time_t)(seconds / SECSPERDAY);
   1640 		rem += (int_fast64_t)(seconds - tdays * SECSPERDAY);
   1641 	}
   1642 	/*
   1643 	** Given the range, we can now fearlessly cast...
   1644 	*/
   1645 	idays = (int) tdays;
   1646 	rem += offset - corr;
   1647 	while (rem < 0) {
   1648 		rem += SECSPERDAY;
   1649 		--idays;
   1650 	}
   1651 	while (rem >= SECSPERDAY) {
   1652 		rem -= SECSPERDAY;
   1653 		++idays;
   1654 	}
   1655 	while (idays < 0) {
   1656 		if (increment_overflow(&y, -1))
   1657 			return NULL;
   1658 		idays += year_lengths[isleap(y)];
   1659 	}
   1660 	while (idays >= year_lengths[isleap(y)]) {
   1661 		idays -= year_lengths[isleap(y)];
   1662 		if (increment_overflow(&y, 1))
   1663 			return NULL;
   1664 	}
   1665 	tmp->tm_year = y;
   1666 	if (increment_overflow(&tmp->tm_year, -TM_YEAR_BASE))
   1667 		return NULL;
   1668 	tmp->tm_yday = idays;
   1669 	/*
   1670 	** The "extra" mods below avoid overflow problems.
   1671 	*/
   1672 	tmp->tm_wday = EPOCH_WDAY +
   1673 		((y - EPOCH_YEAR) % DAYSPERWEEK) *
   1674 		(DAYSPERNYEAR % DAYSPERWEEK) +
   1675 		leaps_thru_end_of(y - 1) -
   1676 		leaps_thru_end_of(EPOCH_YEAR - 1) +
   1677 		idays;
   1678 	tmp->tm_wday %= DAYSPERWEEK;
   1679 	if (tmp->tm_wday < 0)
   1680 		tmp->tm_wday += DAYSPERWEEK;
   1681 	tmp->tm_hour = (int) (rem / SECSPERHOUR);
   1682 	rem %= SECSPERHOUR;
   1683 	tmp->tm_min = (int) (rem / SECSPERMIN);
   1684 	/*
   1685 	** A positive leap second requires a special
   1686 	** representation. This uses "... ??:59:60" et seq.
   1687 	*/
   1688 	tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
   1689 	ip = mon_lengths[isleap(y)];
   1690 	for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
   1691 		idays -= ip[tmp->tm_mon];
   1692 	tmp->tm_mday = (int) (idays + 1);
   1693 	tmp->tm_isdst = 0;
   1694 #ifdef TM_GMTOFF
   1695 	tmp->TM_GMTOFF = offset;
   1696 #endif /* defined TM_GMTOFF */
   1697 	return tmp;
   1698 }
   1699 
   1700 char *
   1701 ctime(const time_t *const timep)
   1702 {
   1703 /*
   1704 ** Section 4.12.3.2 of X3.159-1989 requires that
   1705 **	The ctime function converts the calendar time pointed to by timer
   1706 **	to local time in the form of a string. It is equivalent to
   1707 **		asctime(localtime(timer))
   1708 */
   1709 	struct tm *rtm = localtime(timep);
   1710 	if (rtm == NULL)
   1711 		return NULL;
   1712 	return asctime(rtm);
   1713 }
   1714 
   1715 char *
   1716 ctime_r(const time_t *const timep, char *buf)
   1717 {
   1718 	struct tm	mytm, *rtm;
   1719 
   1720 	rtm = localtime_r(timep, &mytm);
   1721 	if (rtm == NULL)
   1722 		return NULL;
   1723 	return asctime_r(rtm, buf);
   1724 }
   1725 
   1726 char *
   1727 ctime_rz(const timezone_t sp, const time_t * timep, char *buf)
   1728 {
   1729 	struct tm	mytm, *rtm;
   1730 
   1731 	rtm = localtime_rz(sp, timep, &mytm);
   1732 	if (rtm == NULL)
   1733 		return NULL;
   1734 	return asctime_r(rtm, buf);
   1735 }
   1736 
   1737 /*
   1738 ** Adapted from code provided by Robert Elz, who writes:
   1739 **	The "best" way to do mktime I think is based on an idea of Bob
   1740 **	Kridle's (so its said...) from a long time ago.
   1741 **	It does a binary search of the time_t space. Since time_t's are
   1742 **	just 32 bits, its a max of 32 iterations (even at 64 bits it
   1743 **	would still be very reasonable).
   1744 */
   1745 
   1746 #ifndef WRONG
   1747 #define WRONG	((time_t)-1)
   1748 #endif /* !defined WRONG */
   1749 
   1750 /*
   1751 ** Simplified normalize logic courtesy Paul Eggert.
   1752 */
   1753 
   1754 static int
   1755 increment_overflow(int *const ip, int j)
   1756 {
   1757 	int	i = *ip;
   1758 
   1759 	/*
   1760 	** If i >= 0 there can only be overflow if i + j > INT_MAX
   1761 	** or if j > INT_MAX - i; given i >= 0, INT_MAX - i cannot overflow.
   1762 	** If i < 0 there can only be overflow if i + j < INT_MIN
   1763 	** or if j < INT_MIN - i; given i < 0, INT_MIN - i cannot overflow.
   1764 	*/
   1765 	if ((i >= 0) ? (j > INT_MAX - i) : (j < INT_MIN - i))
   1766 		return TRUE;
   1767 	*ip += j;
   1768 	return FALSE;
   1769 }
   1770 
   1771 static int
   1772 increment_overflow32(int_fast32_t *const lp, int const m)
   1773 {
   1774 	int_fast32_t l = *lp;
   1775 
   1776 	if ((l >= 0) ? (m > INT_FAST32_MAX - l) : (m < INT_FAST32_MIN - l))
   1777 		return TRUE;
   1778 	*lp += m;
   1779 	return FALSE;
   1780 }
   1781 
   1782 static int
   1783 increment_overflow_time(time_t *tp, int_fast32_t j)
   1784 {
   1785 	/*
   1786 	** This is like
   1787 	** 'if (! (time_t_min <= *tp + j && *tp + j <= time_t_max)) ...',
   1788 	** except that it does the right thing even if *tp + j would overflow.
   1789 	*/
   1790 	if (! (j < 0
   1791 	       ? (TYPE_SIGNED(time_t) ? time_t_min - j <= *tp : -1 - j < *tp)
   1792 	       : *tp <= time_t_max - j))
   1793 		return TRUE;
   1794 	*tp += j;
   1795 	return FALSE;
   1796 }
   1797 
   1798 static int
   1799 normalize_overflow(int *const tensptr, int *const unitsptr, const int base)
   1800 {
   1801 	int	tensdelta;
   1802 
   1803 	tensdelta = (*unitsptr >= 0) ?
   1804 		(*unitsptr / base) :
   1805 		(-1 - (-1 - *unitsptr) / base);
   1806 	*unitsptr -= tensdelta * base;
   1807 	return increment_overflow(tensptr, tensdelta);
   1808 }
   1809 
   1810 static int
   1811 normalize_overflow32(int_fast32_t *const tensptr, int *const unitsptr,
   1812     const int base)
   1813 {
   1814 	int	tensdelta;
   1815 
   1816 	tensdelta = (*unitsptr >= 0) ?
   1817 		(*unitsptr / base) :
   1818 		(-1 - (-1 - *unitsptr) / base);
   1819 	*unitsptr -= tensdelta * base;
   1820 	return increment_overflow32(tensptr, tensdelta);
   1821 }
   1822 
   1823 static int
   1824 tmcomp(const struct tm *const atmp, const struct tm *const btmp)
   1825 {
   1826 	int	result;
   1827 
   1828 	if (atmp->tm_year != btmp->tm_year)
   1829 		return atmp->tm_year < btmp->tm_year ? -1 : 1;
   1830 	if ((result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
   1831 		(result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
   1832 		(result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
   1833 		(result = (atmp->tm_min - btmp->tm_min)) == 0)
   1834 			result = atmp->tm_sec - btmp->tm_sec;
   1835 	return result;
   1836 }
   1837 
   1838 static time_t
   1839 time2sub(const timezone_t sp, struct tm *const tmp, subfun_t funcp,
   1840     const int_fast32_t offset, int *const okayp, const int do_norm_secs)
   1841 {
   1842 	int			dir;
   1843 	int			i, j;
   1844 	int			saved_seconds;
   1845 	int_fast32_t		li;
   1846 	time_t			lo;
   1847 	time_t			hi;
   1848 #ifdef NO_ERROR_IN_DST_GAP
   1849 	time_t			ilo;
   1850 #endif
   1851 	int_fast32_t		y;
   1852 	time_t			newt;
   1853 	time_t			t;
   1854 	struct tm		yourtm, mytm;
   1855 
   1856 	*okayp = FALSE;
   1857 	yourtm = *tmp;
   1858 #ifdef NO_ERROR_IN_DST_GAP
   1859 again:
   1860 #endif
   1861 	if (do_norm_secs) {
   1862 		if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
   1863 		    SECSPERMIN))
   1864 			goto overflow;
   1865 	}
   1866 	if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
   1867 		goto overflow;
   1868 	if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
   1869 		goto overflow;
   1870 	y = yourtm.tm_year;
   1871 	if (normalize_overflow32(&y, &yourtm.tm_mon, MONSPERYEAR))
   1872 		goto overflow;
   1873 	/*
   1874 	** Turn y into an actual year number for now.
   1875 	** It is converted back to an offset from TM_YEAR_BASE later.
   1876 	*/
   1877 	if (increment_overflow32(&y, TM_YEAR_BASE))
   1878 		goto overflow;
   1879 	while (yourtm.tm_mday <= 0) {
   1880 		if (increment_overflow32(&y, -1))
   1881 			goto overflow;
   1882 		li = y + (1 < yourtm.tm_mon);
   1883 		yourtm.tm_mday += year_lengths[isleap(li)];
   1884 	}
   1885 	while (yourtm.tm_mday > DAYSPERLYEAR) {
   1886 		li = y + (1 < yourtm.tm_mon);
   1887 		yourtm.tm_mday -= year_lengths[isleap(li)];
   1888 		if (increment_overflow32(&y, 1))
   1889 			goto overflow;
   1890 	}
   1891 	for ( ; ; ) {
   1892 		i = mon_lengths[isleap(y)][yourtm.tm_mon];
   1893 		if (yourtm.tm_mday <= i)
   1894 			break;
   1895 		yourtm.tm_mday -= i;
   1896 		if (++yourtm.tm_mon >= MONSPERYEAR) {
   1897 			yourtm.tm_mon = 0;
   1898 			if (increment_overflow32(&y, 1))
   1899 				goto overflow;
   1900 		}
   1901 	}
   1902 	if (increment_overflow32(&y, -TM_YEAR_BASE))
   1903 		goto overflow;
   1904 	yourtm.tm_year = (int)y;
   1905 	if (yourtm.tm_year != y)
   1906 		goto overflow;
   1907 	if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
   1908 		saved_seconds = 0;
   1909 	else if (y + TM_YEAR_BASE < EPOCH_YEAR) {
   1910 		/*
   1911 		** We can't set tm_sec to 0, because that might push the
   1912 		** time below the minimum representable time.
   1913 		** Set tm_sec to 59 instead.
   1914 		** This assumes that the minimum representable time is
   1915 		** not in the same minute that a leap second was deleted from,
   1916 		** which is a safer assumption than using 58 would be.
   1917 		*/
   1918 		if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
   1919 			goto overflow;
   1920 		saved_seconds = yourtm.tm_sec;
   1921 		yourtm.tm_sec = SECSPERMIN - 1;
   1922 	} else {
   1923 		saved_seconds = yourtm.tm_sec;
   1924 		yourtm.tm_sec = 0;
   1925 	}
   1926 	/*
   1927 	** Do a binary search (this works whatever time_t's type is).
   1928 	*/
   1929 	/* LINTED const not */
   1930 	if (!TYPE_SIGNED(time_t)) {
   1931 		lo = 0;
   1932 		hi = lo - 1;
   1933 	} else {
   1934 		lo = 1;
   1935 		for (i = 0; i < (int) TYPE_BIT(time_t) - 1; ++i)
   1936 			lo *= 2;
   1937 		hi = -(lo + 1);
   1938 	}
   1939 #ifdef NO_ERROR_IN_DST_GAP
   1940 	ilo = lo;
   1941 #endif
   1942 	for ( ; ; ) {
   1943 		t = lo / 2 + hi / 2;
   1944 		if (t < lo)
   1945 			t = lo;
   1946 		else if (t > hi)
   1947 			t = hi;
   1948 		if ((*funcp)(sp, &t, offset, &mytm) == NULL) {
   1949 			/*
   1950 			** Assume that t is too extreme to be represented in
   1951 			** a struct tm; arrange things so that it is less
   1952 			** extreme on the next pass.
   1953 			*/
   1954 			dir = (t > 0) ? 1 : -1;
   1955 		} else	dir = tmcomp(&mytm, &yourtm);
   1956 		if (dir != 0) {
   1957 			if (t == lo) {
   1958 				if (t == time_t_max)
   1959 					goto overflow;
   1960 				++t;
   1961 				++lo;
   1962 			} else if (t == hi) {
   1963 				if (t == time_t_min)
   1964 					goto overflow;
   1965 				--t;
   1966 				--hi;
   1967 			}
   1968 #ifdef NO_ERROR_IN_DST_GAP
   1969 			if (ilo != lo && lo - 1 == hi && yourtm.tm_isdst < 0 &&
   1970 			    do_norm_secs) {
   1971 				for (i = sp->typecnt - 1; i >= 0; --i) {
   1972 					for (j = sp->typecnt - 1; j >= 0; --j) {
   1973 						time_t off;
   1974 						if (sp->ttis[j].tt_isdst ==
   1975 						    sp->ttis[i].tt_isdst)
   1976 							continue;
   1977 						off = sp->ttis[j].tt_gmtoff -
   1978 						    sp->ttis[i].tt_gmtoff;
   1979 						yourtm.tm_sec += off < 0 ?
   1980 						    -off : off;
   1981 						goto again;
   1982 					}
   1983 				}
   1984 			}
   1985 #endif
   1986 			if (lo > hi)
   1987 				goto invalid;
   1988 			if (dir > 0)
   1989 				hi = t;
   1990 			else	lo = t;
   1991 			continue;
   1992 		}
   1993 		if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
   1994 			break;
   1995 		/*
   1996 		** Right time, wrong type.
   1997 		** Hunt for right time, right type.
   1998 		** It's okay to guess wrong since the guess
   1999 		** gets checked.
   2000 		*/
   2001 		if (sp == NULL)
   2002 			goto invalid;
   2003 		for (i = sp->typecnt - 1; i >= 0; --i) {
   2004 			if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
   2005 				continue;
   2006 			for (j = sp->typecnt - 1; j >= 0; --j) {
   2007 				if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
   2008 					continue;
   2009 				newt = (time_t)(t + sp->ttis[j].tt_gmtoff -
   2010 				    sp->ttis[i].tt_gmtoff);
   2011 				if ((*funcp)(sp, &newt, offset, &mytm) == NULL)
   2012 					continue;
   2013 				if (tmcomp(&mytm, &yourtm) != 0)
   2014 					continue;
   2015 				if (mytm.tm_isdst != yourtm.tm_isdst)
   2016 					continue;
   2017 				/*
   2018 				** We have a match.
   2019 				*/
   2020 				t = newt;
   2021 				goto label;
   2022 			}
   2023 		}
   2024 		goto invalid;
   2025 	}
   2026 label:
   2027 	newt = t + saved_seconds;
   2028 	if ((newt < t) != (saved_seconds < 0))
   2029 		goto overflow;
   2030 	t = newt;
   2031 	if ((*funcp)(sp, &t, offset, tmp)) {
   2032 		*okayp = TRUE;
   2033 		return t;
   2034 	}
   2035 overflow:
   2036 	errno = EOVERFLOW;
   2037 	return WRONG;
   2038 invalid:
   2039 	errno = EINVAL;
   2040 	return WRONG;
   2041 }
   2042 
   2043 static time_t
   2044 time2(const timezone_t sp, struct tm *const tmp, subfun_t funcp,
   2045     const int_fast32_t offset, int *const okayp)
   2046 {
   2047 	time_t	t;
   2048 
   2049 	/*
   2050 	** First try without normalization of seconds
   2051 	** (in case tm_sec contains a value associated with a leap second).
   2052 	** If that fails, try with normalization of seconds.
   2053 	*/
   2054 	t = time2sub(sp, tmp, funcp, offset, okayp, FALSE);
   2055 	return *okayp ? t : time2sub(sp, tmp, funcp, offset, okayp, TRUE);
   2056 }
   2057 
   2058 static time_t
   2059 time1(const timezone_t sp, struct tm *const tmp, subfun_t funcp,
   2060     const int_fast32_t offset)
   2061 {
   2062 	time_t			t;
   2063 	int			samei, otheri;
   2064 	int			sameind, otherind;
   2065 	int			i;
   2066 	int			nseen;
   2067 	int				seen[TZ_MAX_TYPES];
   2068 	int				types[TZ_MAX_TYPES];
   2069 	int				okay;
   2070 
   2071 	if (tmp == NULL) {
   2072 		errno = EINVAL;
   2073 		return WRONG;
   2074 	}
   2075 	if (tmp->tm_isdst > 1)
   2076 		tmp->tm_isdst = 1;
   2077 	t = time2(sp, tmp, funcp, offset, &okay);
   2078 #ifdef PCTS
   2079 	/*
   2080 	** PCTS code courtesy Grant Sullivan.
   2081 	*/
   2082 	if (okay)
   2083 		return t;
   2084 	if (tmp->tm_isdst < 0)
   2085 		tmp->tm_isdst = 0;	/* reset to std and try again */
   2086 #endif /* defined PCTS */
   2087 #ifndef PCTS
   2088 	if (okay || tmp->tm_isdst < 0)
   2089 		return t;
   2090 #endif /* !defined PCTS */
   2091 	/*
   2092 	** We're supposed to assume that somebody took a time of one type
   2093 	** and did some math on it that yielded a "struct tm" that's bad.
   2094 	** We try to divine the type they started from and adjust to the
   2095 	** type they need.
   2096 	*/
   2097 	if (sp == NULL) {
   2098 		errno = EINVAL;
   2099 		return WRONG;
   2100 	}
   2101 	for (i = 0; i < sp->typecnt; ++i)
   2102 		seen[i] = FALSE;
   2103 	nseen = 0;
   2104 	for (i = sp->timecnt - 1; i >= 0; --i)
   2105 		if (!seen[sp->types[i]]) {
   2106 			seen[sp->types[i]] = TRUE;
   2107 			types[nseen++] = sp->types[i];
   2108 		}
   2109 	for (sameind = 0; sameind < nseen; ++sameind) {
   2110 		samei = types[sameind];
   2111 		if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
   2112 			continue;
   2113 		for (otherind = 0; otherind < nseen; ++otherind) {
   2114 			otheri = types[otherind];
   2115 			if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
   2116 				continue;
   2117 			tmp->tm_sec += (int)(sp->ttis[otheri].tt_gmtoff -
   2118 					sp->ttis[samei].tt_gmtoff);
   2119 			tmp->tm_isdst = !tmp->tm_isdst;
   2120 			t = time2(sp, tmp, funcp, offset, &okay);
   2121 			if (okay)
   2122 				return t;
   2123 			tmp->tm_sec -= (int)(sp->ttis[otheri].tt_gmtoff -
   2124 					sp->ttis[samei].tt_gmtoff);
   2125 			tmp->tm_isdst = !tmp->tm_isdst;
   2126 		}
   2127 	}
   2128 	errno = EOVERFLOW;
   2129 	return WRONG;
   2130 }
   2131 
   2132 time_t
   2133 mktime_z(const timezone_t sp, struct tm *const tmp)
   2134 {
   2135 	time_t t;
   2136 	if (sp == NULL)
   2137 		t = time1(NULL, tmp, gmtsub, 0);
   2138 	else
   2139 		t = time1(sp, tmp, localsub, 0);
   2140 	return t;
   2141 }
   2142 
   2143 time_t
   2144 mktime(struct tm *const tmp)
   2145 {
   2146 	time_t result;
   2147 
   2148 	rwlock_wrlock(&lcl_lock);
   2149 	tzset_unlocked();
   2150 	result = mktime_z(lclptr, tmp);
   2151 	rwlock_unlock(&lcl_lock);
   2152 	return result;
   2153 }
   2154 
   2155 #ifdef STD_INSPIRED
   2156 
   2157 time_t
   2158 timelocal_z(const timezone_t sp, struct tm *const tmp)
   2159 {
   2160 	if (tmp != NULL)
   2161 		tmp->tm_isdst = -1;	/* in case it wasn't initialized */
   2162 	return mktime_z(sp, tmp);
   2163 }
   2164 
   2165 time_t
   2166 timelocal(struct tm *const tmp)
   2167 {
   2168 	if (tmp != NULL)
   2169 		tmp->tm_isdst = -1;	/* in case it wasn't initialized */
   2170 	return mktime(tmp);
   2171 }
   2172 
   2173 time_t
   2174 timegm(struct tm *const tmp)
   2175 {
   2176 	time_t t;
   2177 
   2178 	if (tmp != NULL)
   2179 		tmp->tm_isdst = 0;
   2180 	t = time1(gmtptr, tmp, gmtsub, 0);
   2181 	return t;
   2182 }
   2183 
   2184 time_t
   2185 timeoff(struct tm *const tmp, long offset)
   2186 {
   2187 	time_t t;
   2188 
   2189 	if ((offset > 0 && offset > INT_FAST32_MAX) ||
   2190 	    (offset < 0 && offset < INT_FAST32_MIN)) {
   2191 		errno = EOVERFLOW;
   2192 		return -1;
   2193 	}
   2194 	if (tmp != NULL)
   2195 		tmp->tm_isdst = 0;
   2196 	t = time1(gmtptr, tmp, gmtsub, (int_fast32_t)offset);
   2197 	return t;
   2198 }
   2199 
   2200 #endif /* defined STD_INSPIRED */
   2201 
   2202 #ifdef CMUCS
   2203 
   2204 /*
   2205 ** The following is supplied for compatibility with
   2206 ** previous versions of the CMUCS runtime library.
   2207 */
   2208 
   2209 long
   2210 gtime(struct tm *const tmp)
   2211 {
   2212 	const time_t t = mktime(tmp);
   2213 
   2214 	if (t == WRONG)
   2215 		return -1;
   2216 	return t;
   2217 }
   2218 
   2219 #endif /* defined CMUCS */
   2220 
   2221 /*
   2222 ** XXX--is the below the right way to conditionalize??
   2223 */
   2224 
   2225 #ifdef STD_INSPIRED
   2226 
   2227 /*
   2228 ** IEEE Std 1003.1-1988 (POSIX) legislates that 536457599
   2229 ** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
   2230 ** is not the case if we are accounting for leap seconds.
   2231 ** So, we provide the following conversion routines for use
   2232 ** when exchanging timestamps with POSIX conforming systems.
   2233 */
   2234 
   2235 static int_fast64_t
   2236 leapcorr(const timezone_t sp, time_t *timep)
   2237 {
   2238 	struct lsinfo * lp;
   2239 	int		i;
   2240 
   2241 	i = sp->leapcnt;
   2242 	while (--i >= 0) {
   2243 		lp = &sp->lsis[i];
   2244 		if (*timep >= lp->ls_trans)
   2245 			return lp->ls_corr;
   2246 	}
   2247 	return 0;
   2248 }
   2249 
   2250 time_t
   2251 time2posix_z(const timezone_t sp, time_t t)
   2252 {
   2253 	return (time_t)(t - leapcorr(sp, &t));
   2254 }
   2255 
   2256 time_t
   2257 time2posix(time_t t)
   2258 {
   2259 	time_t result;
   2260 	rwlock_wrlock(&lcl_lock);
   2261 	tzset_unlocked();
   2262 	result = (time_t)(t - leapcorr(lclptr, &t));
   2263 	rwlock_unlock(&lcl_lock);
   2264 	return (result);
   2265 }
   2266 
   2267 time_t
   2268 posix2time_z(const timezone_t sp, time_t t)
   2269 {
   2270 	time_t	x;
   2271 	time_t	y;
   2272 
   2273 	/*
   2274 	** For a positive leap second hit, the result
   2275 	** is not unique. For a negative leap second
   2276 	** hit, the corresponding time doesn't exist,
   2277 	** so we return an adjacent second.
   2278 	*/
   2279 	x = (time_t)(t + leapcorr(sp, &t));
   2280 	y = (time_t)(x - leapcorr(sp, &x));
   2281 	if (y < t) {
   2282 		do {
   2283 			x++;
   2284 			y = (time_t)(x - leapcorr(sp, &x));
   2285 		} while (y < t);
   2286 		if (t != y) {
   2287 			return x - 1;
   2288 		}
   2289 	} else if (y > t) {
   2290 		do {
   2291 			--x;
   2292 			y = (time_t)(x - leapcorr(sp, &x));
   2293 		} while (y > t);
   2294 		if (t != y) {
   2295 			return x + 1;
   2296 		}
   2297 	}
   2298 	return x;
   2299 }
   2300 
   2301 
   2302 
   2303 time_t
   2304 posix2time(time_t t)
   2305 {
   2306 	time_t result;
   2307 
   2308 	rwlock_wrlock(&lcl_lock);
   2309 	tzset_unlocked();
   2310 	result = posix2time_z(lclptr, t);
   2311 	rwlock_unlock(&lcl_lock);
   2312 	return result;
   2313 }
   2314 
   2315 #endif /* defined STD_INSPIRED */
   2316