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