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