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