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