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