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