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