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