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