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