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