xref: /netbsd-src/lib/libc/time/localtime.c (revision 1ca5c1b28139779176bd5c13ad7c5f25c0bcd5f8)
1 /*	$NetBSD: localtime.c,v 1.28 2001/11/04 13:57:31 lukem 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@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.28 2001/11/04 13:57:31 lukem Exp $");
14 #endif
15 #endif /* LIBC_SCCS and not lint */
16 
17 /*
18 ** Leap second handling from Bradley White (bww@k.gp.cs.cmu.edu).
19 ** POSIX-style TZ environment variable handling from Guy Harris
20 ** (guy@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@twinsun.com) for noting this.
227 */
228 
229 static struct tm	tm;
230 
231 #ifdef USG_COMPAT
232 long int		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->typecnt = 0;
1044 		lclptr->ttis[0].tt_isdst = 0;
1045 		lclptr->ttis[0].tt_gmtoff = 0;
1046 		lclptr->ttis[0].tt_abbrind = 0;
1047 		(void)strncpy(lclptr->chars, gmt, sizeof(lclptr->chars) - 1);
1048 	} else if (tzload(name, lclptr) != 0)
1049 		if (name[0] == ':' || tzparse(name, lclptr, FALSE) != 0)
1050 			(void) gmtload(lclptr);
1051 	settzname();
1052 }
1053 
1054 void
1055 tzset P((void))
1056 {
1057 	rwlock_wrlock(&lcl_lock);
1058 	tzset_unlocked();
1059 	rwlock_unlock(&lcl_lock);
1060 }
1061 
1062 /*
1063 ** The easy way to behave "as if no library function calls" localtime
1064 ** is to not call it--so we drop its guts into "localsub", which can be
1065 ** freely called.  (And no, the PANS doesn't require the above behavior--
1066 ** but it *is* desirable.)
1067 **
1068 ** The unused offset argument is for the benefit of mktime variants.
1069 */
1070 
1071 /*ARGSUSED*/
1072 static void
1073 localsub(timep, offset, tmp)
1074 const time_t * const	timep;
1075 const long		offset;
1076 struct tm * const	tmp;
1077 {
1078 	register struct state *		sp;
1079 	register const struct ttinfo *	ttisp;
1080 	register int			i;
1081 	const time_t			t = *timep;
1082 
1083 	sp = lclptr;
1084 #ifdef ALL_STATE
1085 	if (sp == NULL) {
1086 		gmtsub(timep, offset, tmp);
1087 		return;
1088 	}
1089 #endif /* defined ALL_STATE */
1090 	if (sp->timecnt == 0 || t < sp->ats[0]) {
1091 		i = 0;
1092 		while (sp->ttis[i].tt_isdst)
1093 			if (++i >= sp->typecnt) {
1094 				i = 0;
1095 				break;
1096 			}
1097 	} else {
1098 		for (i = 1; i < sp->timecnt; ++i)
1099 			if (t < sp->ats[i])
1100 				break;
1101 		i = sp->types[i - 1];
1102 	}
1103 	ttisp = &sp->ttis[i];
1104 	/*
1105 	** To get (wrong) behavior that's compatible with System V Release 2.0
1106 	** you'd replace the statement below with
1107 	**	t += ttisp->tt_gmtoff;
1108 	**	timesub(&t, 0L, sp, tmp);
1109 	*/
1110 	timesub(&t, ttisp->tt_gmtoff, sp, tmp);
1111 	tmp->tm_isdst = ttisp->tt_isdst;
1112 	tzname[tmp->tm_isdst] = &sp->chars[ttisp->tt_abbrind];
1113 #ifdef TM_ZONE
1114 	tmp->TM_ZONE = &sp->chars[ttisp->tt_abbrind];
1115 #endif /* defined TM_ZONE */
1116 }
1117 
1118 struct tm *
1119 localtime(timep)
1120 const time_t * const	timep;
1121 {
1122 	rwlock_wrlock(&lcl_lock);
1123 	tzset_unlocked();
1124 	localsub(timep, 0L, &tm);
1125 	rwlock_unlock(&lcl_lock);
1126 	return &tm;
1127 }
1128 
1129 /*
1130  * Re-entrant version of localtime
1131  */
1132 struct tm *
1133 localtime_r(timep, tmp)
1134 const time_t * const	timep;
1135 struct tm *		tmp;
1136 {
1137 	rwlock_rdlock(&lcl_lock);
1138 	localsub(timep, 0L, tmp);
1139 	rwlock_unlock(&lcl_lock);
1140 	return tmp;
1141 }
1142 
1143 /*
1144 ** gmtsub is to gmtime as localsub is to localtime.
1145 */
1146 
1147 static void
1148 gmtsub(timep, offset, tmp)
1149 const time_t * const	timep;
1150 const long		offset;
1151 struct tm * const	tmp;
1152 {
1153 #ifdef _REENT
1154 	static mutex_t gmt_mutex = MUTEX_INITIALIZER;
1155 #endif
1156 
1157 	mutex_lock(&gmt_mutex);
1158 	if (!gmt_is_set) {
1159 		gmt_is_set = TRUE;
1160 #ifdef ALL_STATE
1161 		gmtptr = (struct state *) malloc(sizeof *gmtptr);
1162 		if (gmtptr != NULL)
1163 #endif /* defined ALL_STATE */
1164 			gmtload(gmtptr);
1165 	}
1166 	mutex_unlock(&gmt_mutex);
1167 	timesub(timep, offset, gmtptr, tmp);
1168 #ifdef TM_ZONE
1169 	/*
1170 	** Could get fancy here and deliver something such as
1171 	** "UTC+xxxx" or "UTC-xxxx" if offset is non-zero,
1172 	** but this is no time for a treasure hunt.
1173 	*/
1174 	if (offset != 0)
1175 		/* LINTED const castaway */
1176 		tmp->TM_ZONE = (__aconst char *)wildabbr;
1177 	else {
1178 #ifdef ALL_STATE
1179 		if (gmtptr == NULL)
1180 			tmp->TM_ZONE = (__aconst char *)gmt;
1181 		else	tmp->TM_ZONE = gmtptr->chars;
1182 #endif /* defined ALL_STATE */
1183 #ifndef ALL_STATE
1184 		tmp->TM_ZONE = gmtptr->chars;
1185 #endif /* State Farm */
1186 	}
1187 #endif /* defined TM_ZONE */
1188 }
1189 
1190 struct tm *
1191 gmtime(timep)
1192 const time_t * const	timep;
1193 {
1194 	gmtsub(timep, 0L, &tm);
1195 	return &tm;
1196 }
1197 
1198 /*
1199  * Re-entrant version of gmtime
1200  */
1201 struct tm *
1202 gmtime_r(timep, tmp)
1203 const time_t * const	timep;
1204 struct tm *		tmp;
1205 {
1206 	gmtsub(timep, 0L, tmp);
1207 	return tmp;
1208 }
1209 
1210 #ifdef STD_INSPIRED
1211 
1212 struct tm *
1213 offtime(timep, offset)
1214 const time_t * const	timep;
1215 const long		offset;
1216 {
1217 	gmtsub(timep, offset, &tm);
1218 	return &tm;
1219 }
1220 
1221 #endif /* defined STD_INSPIRED */
1222 
1223 static void
1224 timesub(timep, offset, sp, tmp)
1225 const time_t * const			timep;
1226 const long				offset;
1227 register const struct state * const	sp;
1228 register struct tm * const		tmp;
1229 {
1230 	register const struct lsinfo *	lp;
1231 	register long			days;
1232 	register long			rem;
1233 	register int			y;
1234 	register int			yleap;
1235 	register const int *		ip;
1236 	register long			corr;
1237 	register int			hit;
1238 	register int			i;
1239 
1240 	corr = 0;
1241 	hit = 0;
1242 #ifdef ALL_STATE
1243 	i = (sp == NULL) ? 0 : sp->leapcnt;
1244 #endif /* defined ALL_STATE */
1245 #ifndef ALL_STATE
1246 	i = sp->leapcnt;
1247 #endif /* State Farm */
1248 	while (--i >= 0) {
1249 		lp = &sp->lsis[i];
1250 		if (*timep >= lp->ls_trans) {
1251 			if (*timep == lp->ls_trans) {
1252 				hit = ((i == 0 && lp->ls_corr > 0) ||
1253 					lp->ls_corr > sp->lsis[i - 1].ls_corr);
1254 				if (hit)
1255 					while (i > 0 &&
1256 						sp->lsis[i].ls_trans ==
1257 						sp->lsis[i - 1].ls_trans + 1 &&
1258 						sp->lsis[i].ls_corr ==
1259 						sp->lsis[i - 1].ls_corr + 1) {
1260 							++hit;
1261 							--i;
1262 					}
1263 			}
1264 			corr = lp->ls_corr;
1265 			break;
1266 		}
1267 	}
1268 	days = *timep / SECSPERDAY;
1269 	rem = *timep % SECSPERDAY;
1270 #ifdef mc68k
1271 	if (*timep == 0x80000000) {
1272 		/*
1273 		** A 3B1 muffs the division on the most negative number.
1274 		*/
1275 		days = -24855;
1276 		rem = -11648;
1277 	}
1278 #endif /* defined mc68k */
1279 	rem += (offset - corr);
1280 	while (rem < 0) {
1281 		rem += SECSPERDAY;
1282 		--days;
1283 	}
1284 	while (rem >= SECSPERDAY) {
1285 		rem -= SECSPERDAY;
1286 		++days;
1287 	}
1288 	tmp->tm_hour = (int) (rem / SECSPERHOUR);
1289 	rem = rem % SECSPERHOUR;
1290 	tmp->tm_min = (int) (rem / SECSPERMIN);
1291 	/*
1292 	** A positive leap second requires a special
1293 	** representation.  This uses "... ??:59:60" et seq.
1294 	*/
1295 	tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
1296 	tmp->tm_wday = (int) ((EPOCH_WDAY + days) % DAYSPERWEEK);
1297 	if (tmp->tm_wday < 0)
1298 		tmp->tm_wday += DAYSPERWEEK;
1299 	y = EPOCH_YEAR;
1300 #define LEAPS_THRU_END_OF(y)	((y) / 4 - (y) / 100 + (y) / 400)
1301 	while (days < 0 || days >= (long) year_lengths[yleap = isleap(y)]) {
1302 		register int	newy;
1303 
1304 		newy = (int)(y + days / DAYSPERNYEAR);
1305 		if (days < 0)
1306 			--newy;
1307 		days -= (newy - y) * DAYSPERNYEAR +
1308 			LEAPS_THRU_END_OF(newy - 1) -
1309 			LEAPS_THRU_END_OF(y - 1);
1310 		y = newy;
1311 	}
1312 	tmp->tm_year = y - TM_YEAR_BASE;
1313 	tmp->tm_yday = (int) days;
1314 	ip = mon_lengths[yleap];
1315 	for (tmp->tm_mon = 0; days >= (long) ip[tmp->tm_mon]; ++(tmp->tm_mon))
1316 		days = days - (long) ip[tmp->tm_mon];
1317 	tmp->tm_mday = (int) (days + 1);
1318 	tmp->tm_isdst = 0;
1319 #ifdef TM_GMTOFF
1320 	tmp->TM_GMTOFF = offset;
1321 #endif /* defined TM_GMTOFF */
1322 }
1323 
1324 char *
1325 ctime(timep)
1326 const time_t * const	timep;
1327 {
1328 /*
1329 ** Section 4.12.3.2 of X3.159-1989 requires that
1330 **	The ctime function converts the calendar time pointed to by timer
1331 **	to local time in the form of a string.  It is equivalent to
1332 **		asctime(localtime(timer))
1333 */
1334 	return asctime(localtime(timep));
1335 }
1336 
1337 char *
1338 ctime_r(timep, buf)
1339 const time_t * const	timep;
1340 char *			buf;
1341 {
1342 	struct tm	tmp;
1343 
1344 	return asctime_r(localtime_r(timep, &tmp), buf);
1345 }
1346 
1347 /*
1348 ** Adapted from code provided by Robert Elz, who writes:
1349 **	The "best" way to do mktime I think is based on an idea of Bob
1350 **	Kridle's (so its said...) from a long time ago.
1351 **	[kridle@xinet.com as of 1996-01-16.]
1352 **	It does a binary search of the time_t space.  Since time_t's are
1353 **	just 32 bits, its a max of 32 iterations (even at 64 bits it
1354 **	would still be very reasonable).
1355 */
1356 
1357 #ifndef WRONG
1358 #define WRONG	(-1)
1359 #endif /* !defined WRONG */
1360 
1361 /*
1362 ** Simplified normalize logic courtesy Paul Eggert (eggert@twinsun.com).
1363 */
1364 
1365 static int
1366 increment_overflow(number, delta)
1367 int *	number;
1368 int	delta;
1369 {
1370 	int	number0;
1371 
1372 	number0 = *number;
1373 	*number += delta;
1374 	return (*number < number0) != (delta < 0);
1375 }
1376 
1377 static int
1378 normalize_overflow(tensptr, unitsptr, base)
1379 int * const	tensptr;
1380 int * const	unitsptr;
1381 const int	base;
1382 {
1383 	register int	tensdelta;
1384 
1385 	tensdelta = (*unitsptr >= 0) ?
1386 		(*unitsptr / base) :
1387 		(-1 - (-1 - *unitsptr) / base);
1388 	*unitsptr -= tensdelta * base;
1389 	return increment_overflow(tensptr, tensdelta);
1390 }
1391 
1392 static int
1393 tmcomp(atmp, btmp)
1394 register const struct tm * const atmp;
1395 register const struct tm * const btmp;
1396 {
1397 	register int	result;
1398 
1399 	if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
1400 		(result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
1401 		(result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
1402 		(result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
1403 		(result = (atmp->tm_min - btmp->tm_min)) == 0)
1404 			result = atmp->tm_sec - btmp->tm_sec;
1405 	return result;
1406 }
1407 
1408 static time_t
1409 time2sub(tmp, funcp, offset, okayp, do_norm_secs)
1410 struct tm * const	tmp;
1411 void (* const		funcp) P((const time_t*, long, struct tm*));
1412 const long		offset;
1413 int * const		okayp;
1414 const int		do_norm_secs;
1415 {
1416 	register const struct state *	sp;
1417 	register int			dir;
1418 	register int			bits;
1419 	register int			i, j ;
1420 	register int			saved_seconds;
1421 	time_t				newt;
1422 	time_t				t;
1423 	struct tm			yourtm, mytm;
1424 
1425 	*okayp = FALSE;
1426 	yourtm = *tmp;
1427 	if (do_norm_secs) {
1428 		if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
1429 			SECSPERMIN))
1430 				return WRONG;
1431 	}
1432 	if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
1433 		return WRONG;
1434 	if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
1435 		return WRONG;
1436 	if (normalize_overflow(&yourtm.tm_year, &yourtm.tm_mon, MONSPERYEAR))
1437 		return WRONG;
1438 	/*
1439 	** Turn yourtm.tm_year into an actual year number for now.
1440 	** It is converted back to an offset from TM_YEAR_BASE later.
1441 	*/
1442 	if (increment_overflow(&yourtm.tm_year, TM_YEAR_BASE))
1443 		return WRONG;
1444 	while (yourtm.tm_mday <= 0) {
1445 		if (increment_overflow(&yourtm.tm_year, -1))
1446 			return WRONG;
1447 		i = yourtm.tm_year + (1 < yourtm.tm_mon);
1448 		yourtm.tm_mday += year_lengths[isleap(i)];
1449 	}
1450 	while (yourtm.tm_mday > DAYSPERLYEAR) {
1451 		i = yourtm.tm_year + (1 < yourtm.tm_mon);
1452 		yourtm.tm_mday -= year_lengths[isleap(i)];
1453 		if (increment_overflow(&yourtm.tm_year, 1))
1454 			return WRONG;
1455 	}
1456 	for ( ; ; ) {
1457 		i = mon_lengths[isleap(yourtm.tm_year)][yourtm.tm_mon];
1458 		if (yourtm.tm_mday <= i)
1459 			break;
1460 		yourtm.tm_mday -= i;
1461 		if (++yourtm.tm_mon >= MONSPERYEAR) {
1462 			yourtm.tm_mon = 0;
1463 			if (increment_overflow(&yourtm.tm_year, 1))
1464 				return WRONG;
1465 		}
1466 	}
1467 	if (increment_overflow(&yourtm.tm_year, -TM_YEAR_BASE))
1468 		return WRONG;
1469 	if (yourtm.tm_year + TM_YEAR_BASE < EPOCH_YEAR) {
1470 		/*
1471 		** We can't set tm_sec to 0, because that might push the
1472 		** time below the minimum representable time.
1473 		** Set tm_sec to 59 instead.
1474 		** This assumes that the minimum representable time is
1475 		** not in the same minute that a leap second was deleted from,
1476 		** which is a safer assumption than using 58 would be.
1477 		*/
1478 		if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
1479 			return WRONG;
1480 		saved_seconds = yourtm.tm_sec;
1481 		yourtm.tm_sec = SECSPERMIN - 1;
1482 	} else {
1483 		saved_seconds = yourtm.tm_sec;
1484 		yourtm.tm_sec = 0;
1485 	}
1486 	/*
1487 	** Divide the search space in half
1488 	** (this works whether time_t is signed or unsigned).
1489 	*/
1490 	bits = TYPE_BIT(time_t) - 1;
1491 	/*
1492 	** If time_t is signed, then 0 is just above the median,
1493 	** assuming two's complement arithmetic.
1494 	** If time_t is unsigned, then (1 << bits) is just above the median.
1495 	*/
1496 	/* LINTED constant in conditional context */
1497 	t = TYPE_SIGNED(time_t) ? 0 : (((time_t) 1) << bits);
1498 	for ( ; ; ) {
1499 		(*funcp)(&t, offset, &mytm);
1500 		dir = tmcomp(&mytm, &yourtm);
1501 		if (dir != 0) {
1502 			if (bits-- < 0)
1503 				return WRONG;
1504 			if (bits < 0)
1505 				--t; /* may be needed if new t is minimal */
1506 			else if (dir > 0)
1507 				t -= ((time_t) 1) << bits;
1508 			else	t += ((time_t) 1) << bits;
1509 			continue;
1510 		}
1511 		if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
1512 			break;
1513 		/*
1514 		** Right time, wrong type.
1515 		** Hunt for right time, right type.
1516 		** It's okay to guess wrong since the guess
1517 		** gets checked.
1518 		*/
1519 		/*
1520 		** The (void *) casts are the benefit of SunOS 3.3 on Sun 2's.
1521 		*/
1522 		sp = (const struct state *)
1523 			(((void *) funcp == (void *) localsub) ?
1524 			lclptr : gmtptr);
1525 #ifdef ALL_STATE
1526 		if (sp == NULL)
1527 			return WRONG;
1528 #endif /* defined ALL_STATE */
1529 		for (i = sp->typecnt - 1; i >= 0; --i) {
1530 			if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
1531 				continue;
1532 			for (j = sp->typecnt - 1; j >= 0; --j) {
1533 				if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
1534 					continue;
1535 				newt = t + sp->ttis[j].tt_gmtoff -
1536 					sp->ttis[i].tt_gmtoff;
1537 				(*funcp)(&newt, offset, &mytm);
1538 				if (tmcomp(&mytm, &yourtm) != 0)
1539 					continue;
1540 				if (mytm.tm_isdst != yourtm.tm_isdst)
1541 					continue;
1542 				/*
1543 				** We have a match.
1544 				*/
1545 				t = newt;
1546 				goto label;
1547 			}
1548 		}
1549 		return WRONG;
1550 	}
1551 label:
1552 	newt = t + saved_seconds;
1553 	if ((newt < t) != (saved_seconds < 0))
1554 		return WRONG;
1555 	t = newt;
1556 	(*funcp)(&t, offset, tmp);
1557 	*okayp = TRUE;
1558 	return t;
1559 }
1560 
1561 static time_t
1562 time2(tmp, funcp, offset, okayp)
1563 struct tm * const	tmp;
1564 void (* const		funcp) P((const time_t*, long, struct tm*));
1565 const long		offset;
1566 int * const		okayp;
1567 {
1568 	time_t	t;
1569 
1570 	/*
1571 	** First try without normalization of seconds
1572 	** (in case tm_sec contains a value associated with a leap second).
1573 	** If that fails, try with normalization of seconds.
1574 	*/
1575 	t = time2sub(tmp, funcp, offset, okayp, FALSE);
1576 	return *okayp ? t : time2sub(tmp, funcp, offset, okayp, TRUE);
1577 }
1578 
1579 static time_t
1580 time1(tmp, funcp, offset)
1581 struct tm * const	tmp;
1582 void (* const		funcp) P((const time_t *, long, struct tm *));
1583 const long		offset;
1584 {
1585 	register time_t			t;
1586 	register const struct state *	sp;
1587 	register int			samei, otheri;
1588 	int				okay;
1589 
1590 	if (tmp->tm_isdst > 1)
1591 		tmp->tm_isdst = 1;
1592 	t = time2(tmp, funcp, offset, &okay);
1593 #ifdef PCTS
1594 	/*
1595 	** PCTS code courtesy Grant Sullivan (grant@osf.org).
1596 	*/
1597 	if (okay)
1598 		return t;
1599 	if (tmp->tm_isdst < 0)
1600 		tmp->tm_isdst = 0;	/* reset to std and try again */
1601 #endif /* defined PCTS */
1602 #ifndef PCTS
1603 	if (okay || tmp->tm_isdst < 0)
1604 		return t;
1605 #endif /* !defined PCTS */
1606 	/*
1607 	** We're supposed to assume that somebody took a time of one type
1608 	** and did some math on it that yielded a "struct tm" that's bad.
1609 	** We try to divine the type they started from and adjust to the
1610 	** type they need.
1611 	*/
1612 	/*
1613 	** The (void *) casts are the benefit of SunOS 3.3 on Sun 2's.
1614 	*/
1615 	sp = (const struct state *) (((void *) funcp == (void *) localsub) ?
1616 		lclptr : gmtptr);
1617 #ifdef ALL_STATE
1618 	if (sp == NULL)
1619 		return WRONG;
1620 #endif /* defined ALL_STATE */
1621 	for (samei = sp->typecnt - 1; samei >= 0; --samei) {
1622 		if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
1623 			continue;
1624 		for (otheri = sp->typecnt - 1; otheri >= 0; --otheri) {
1625 			if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
1626 				continue;
1627 			tmp->tm_sec += (int)(sp->ttis[otheri].tt_gmtoff -
1628 					sp->ttis[samei].tt_gmtoff);
1629 			tmp->tm_isdst = !tmp->tm_isdst;
1630 			t = time2(tmp, funcp, offset, &okay);
1631 			if (okay)
1632 				return t;
1633 			tmp->tm_sec -= (int)(sp->ttis[otheri].tt_gmtoff -
1634 					sp->ttis[samei].tt_gmtoff);
1635 			tmp->tm_isdst = !tmp->tm_isdst;
1636 		}
1637 	}
1638 	return WRONG;
1639 }
1640 
1641 time_t
1642 mktime(tmp)
1643 struct tm * const	tmp;
1644 {
1645 	time_t result;
1646 
1647 	rwlock_wrlock(&lcl_lock);
1648 	tzset_unlocked();
1649 	result = time1(tmp, localsub, 0L);
1650 	rwlock_unlock(&lcl_lock);
1651 	return (result);
1652 }
1653 
1654 #ifdef STD_INSPIRED
1655 
1656 time_t
1657 timelocal(tmp)
1658 struct tm * const	tmp;
1659 {
1660 	tmp->tm_isdst = -1;	/* in case it wasn't initialized */
1661 	return mktime(tmp);
1662 }
1663 
1664 time_t
1665 timegm(tmp)
1666 struct tm * const	tmp;
1667 {
1668 	tmp->tm_isdst = 0;
1669 	return time1(tmp, gmtsub, 0L);
1670 }
1671 
1672 time_t
1673 timeoff(tmp, offset)
1674 struct tm * const	tmp;
1675 const long		offset;
1676 {
1677 	tmp->tm_isdst = 0;
1678 	return time1(tmp, gmtsub, offset);
1679 }
1680 
1681 #endif /* defined STD_INSPIRED */
1682 
1683 #ifdef CMUCS
1684 
1685 /*
1686 ** The following is supplied for compatibility with
1687 ** previous versions of the CMUCS runtime library.
1688 */
1689 
1690 long
1691 gtime(tmp)
1692 struct tm * const	tmp;
1693 {
1694 	const time_t	t = mktime(tmp);
1695 
1696 	if (t == WRONG)
1697 		return -1;
1698 	return t;
1699 }
1700 
1701 #endif /* defined CMUCS */
1702 
1703 /*
1704 ** XXX--is the below the right way to conditionalize??
1705 */
1706 
1707 #ifdef STD_INSPIRED
1708 
1709 /*
1710 ** IEEE Std 1003.1-1988 (POSIX) legislates that 536457599
1711 ** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
1712 ** is not the case if we are accounting for leap seconds.
1713 ** So, we provide the following conversion routines for use
1714 ** when exchanging timestamps with POSIX conforming systems.
1715 */
1716 
1717 static long
1718 leapcorr(timep)
1719 time_t *	timep;
1720 {
1721 	register struct state *		sp;
1722 	register struct lsinfo *	lp;
1723 	register int			i;
1724 
1725 	sp = lclptr;
1726 	i = sp->leapcnt;
1727 	while (--i >= 0) {
1728 		lp = &sp->lsis[i];
1729 		if (*timep >= lp->ls_trans)
1730 			return lp->ls_corr;
1731 	}
1732 	return 0;
1733 }
1734 
1735 time_t
1736 time2posix(t)
1737 time_t	t;
1738 {
1739 	time_t result;
1740 
1741 	rwlock_wrlock(&lcl_lock);
1742 	tzset_unlocked();
1743 	result = t - leapcorr(&t);
1744 	rwlock_unlock(&lcl_lock);
1745 	return (result);
1746 }
1747 
1748 time_t
1749 posix2time(t)
1750 time_t	t;
1751 {
1752 	time_t	x;
1753 	time_t	y;
1754 
1755 	rwlock_wrlock(&lcl_lock);
1756 	tzset_unlocked();
1757 	/*
1758 	** For a positive leap second hit, the result
1759 	** is not unique.  For a negative leap second
1760 	** hit, the corresponding time doesn't exist,
1761 	** so we return an adjacent second.
1762 	*/
1763 	x = t + leapcorr(&t);
1764 	y = x - leapcorr(&x);
1765 	if (y < t) {
1766 		do {
1767 			x++;
1768 			y = x - leapcorr(&x);
1769 		} while (y < t);
1770 		if (t != y) {
1771 			rwlock_unlock(&lcl_lock);
1772 			return x - 1;
1773 		}
1774 	} else if (y > t) {
1775 		do {
1776 			--x;
1777 			y = x - leapcorr(&x);
1778 		} while (y > t);
1779 		if (t != y) {
1780 			rwlock_unlock(&lcl_lock);
1781 			return x + 1;
1782 		}
1783 	}
1784 	rwlock_unlock(&lcl_lock);
1785 	return x;
1786 }
1787 
1788 #endif /* defined STD_INSPIRED */
1789