Home | History | Annotate | Line # | Download | only in time
localtime.c revision 1.111.2.1
      1  1.111.2.1  pgoyette /*	$NetBSD: localtime.c,v 1.111.2.1 2018/05/21 04:35:55 pgoyette Exp $	*/
      2        1.7       jtc 
      3        1.7       jtc /*
      4        1.7       jtc ** This file is in the public domain, so clarified as of
      5       1.45   mlelstv ** 1996-06-05 by Arthur David Olson.
      6        1.7       jtc */
      7        1.2       jtc 
      8       1.11  christos #include <sys/cdefs.h>
      9       1.24   msaitoh #if defined(LIBC_SCCS) && !defined(lint)
     10       1.11  christos #if 0
     11       1.58  christos static char	elsieid[] = "@(#)localtime.c	8.17";
     12       1.11  christos #else
     13  1.111.2.1  pgoyette __RCSID("$NetBSD: localtime.c,v 1.111.2.1 2018/05/21 04:35:55 pgoyette Exp $");
     14       1.11  christos #endif
     15       1.24   msaitoh #endif /* LIBC_SCCS and not lint */
     16        1.1       jtc 
     17        1.1       jtc /*
     18       1.45   mlelstv ** Leap second handling from Bradley White.
     19       1.45   mlelstv ** POSIX-style TZ environment variable handling from Guy Harris.
     20        1.1       jtc */
     21        1.1       jtc 
     22        1.1       jtc /*LINTLIBRARY*/
     23        1.1       jtc 
     24       1.12       jtc #include "namespace.h"
     25       1.78  christos #include <assert.h>
     26       1.87  christos #define LOCALTIME_IMPLEMENTATION
     27        1.1       jtc #include "private.h"
     28       1.87  christos 
     29        1.1       jtc #include "tzfile.h"
     30      1.106  christos #include <fcntl.h>
     31       1.19    kleink #include "reentrant.h"
     32       1.12       jtc 
     33       1.87  christos #if NETBSD_INSPIRED
     34       1.87  christos # define NETBSD_INSPIRED_EXTERN
     35       1.87  christos #else
     36       1.87  christos # define NETBSD_INSPIRED_EXTERN static
     37       1.87  christos #endif
     38       1.87  christos 
     39       1.42  christos #if defined(__weak_alias)
     40       1.25    kleink __weak_alias(daylight,_daylight)
     41       1.23   mycroft __weak_alias(tzname,_tzname)
     42       1.12       jtc #endif
     43        1.1       jtc 
     44       1.45   mlelstv #ifndef TZ_ABBR_MAX_LEN
     45       1.45   mlelstv #define TZ_ABBR_MAX_LEN	16
     46       1.45   mlelstv #endif /* !defined TZ_ABBR_MAX_LEN */
     47       1.45   mlelstv 
     48       1.45   mlelstv #ifndef TZ_ABBR_CHAR_SET
     49       1.45   mlelstv #define TZ_ABBR_CHAR_SET \
     50       1.45   mlelstv 	"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 :+-._"
     51       1.45   mlelstv #endif /* !defined TZ_ABBR_CHAR_SET */
     52       1.45   mlelstv 
     53       1.45   mlelstv #ifndef TZ_ABBR_ERR_CHAR
     54       1.45   mlelstv #define TZ_ABBR_ERR_CHAR	'_'
     55       1.45   mlelstv #endif /* !defined TZ_ABBR_ERR_CHAR */
     56       1.45   mlelstv 
     57        1.1       jtc /*
     58        1.1       jtc ** SunOS 4.1.1 headers lack O_BINARY.
     59        1.1       jtc */
     60        1.1       jtc 
     61        1.1       jtc #ifdef O_BINARY
     62       1.86  christos #define OPEN_MODE	(O_RDONLY | O_BINARY | O_CLOEXEC)
     63        1.1       jtc #endif /* defined O_BINARY */
     64        1.1       jtc #ifndef O_BINARY
     65       1.86  christos #define OPEN_MODE	(O_RDONLY | O_CLOEXEC)
     66        1.1       jtc #endif /* !defined O_BINARY */
     67        1.1       jtc 
     68        1.1       jtc #ifndef WILDABBR
     69        1.1       jtc /*
     70        1.1       jtc ** Someone might make incorrect use of a time zone abbreviation:
     71        1.1       jtc **	1.	They might reference tzname[0] before calling tzset (explicitly
     72        1.1       jtc **		or implicitly).
     73        1.1       jtc **	2.	They might reference tzname[1] before calling tzset (explicitly
     74        1.1       jtc **		or implicitly).
     75        1.1       jtc **	3.	They might reference tzname[1] after setting to a time zone
     76        1.1       jtc **		in which Daylight Saving Time is never observed.
     77        1.1       jtc **	4.	They might reference tzname[0] after setting to a time zone
     78        1.1       jtc **		in which Standard Time is never observed.
     79        1.1       jtc **	5.	They might reference tm.TM_ZONE after calling offtime.
     80        1.1       jtc ** What's best to do in the above cases is open to debate;
     81        1.1       jtc ** for now, we just set things up so that in any of the five cases
     82       1.45   mlelstv ** WILDABBR is used. Another possibility: initialize tzname[0] to the
     83        1.1       jtc ** string "tzname[0] used before set", and similarly for the other cases.
     84       1.45   mlelstv ** And another: initialize tzname[0] to "ERA", with an explanation in the
     85        1.1       jtc ** manual page of what this "time zone abbreviation" means (doing this so
     86        1.1       jtc ** that tzname[0] has the "normal" length of three characters).
     87        1.1       jtc */
     88        1.1       jtc #define WILDABBR	"   "
     89        1.1       jtc #endif /* !defined WILDABBR */
     90        1.1       jtc 
     91       1.45   mlelstv static const char	wildabbr[] = WILDABBR;
     92        1.1       jtc 
     93       1.71  christos static const char	gmt[] = "GMT";
     94        1.1       jtc 
     95       1.22    kleink /*
     96       1.22    kleink ** The DST rules to use if TZ has no rules and we can't load TZDEFRULES.
     97      1.109  christos ** Default to US rules as of 2017-05-07.
     98  1.111.2.1  pgoyette ** POSIX does not specify the default DST rules;
     99  1.111.2.1  pgoyette ** for historical reasons, US rules are a common default.
    100       1.22    kleink */
    101       1.22    kleink #ifndef TZDEFRULESTRING
    102      1.109  christos #define TZDEFRULESTRING ",M3.2.0,M11.1.0"
    103      1.109  christos #endif
    104       1.22    kleink 
    105        1.1       jtc struct ttinfo {				/* time type information */
    106       1.78  christos 	int_fast32_t	tt_gmtoff;	/* UT offset in seconds */
    107       1.87  christos 	bool		tt_isdst;	/* used to set tm_isdst */
    108        1.1       jtc 	int		tt_abbrind;	/* abbreviation list index */
    109       1.87  christos 	bool		tt_ttisstd;	/* transition is std time */
    110       1.87  christos 	bool		tt_ttisgmt;	/* transition is UT */
    111        1.1       jtc };
    112        1.1       jtc 
    113        1.1       jtc struct lsinfo {				/* leap second information */
    114        1.1       jtc 	time_t		ls_trans;	/* transition time */
    115       1.74  christos 	int_fast64_t	ls_corr;	/* correction to apply */
    116        1.1       jtc };
    117        1.1       jtc 
    118       1.87  christos #define SMALLEST(a, b)	(((a) < (b)) ? (a) : (b))
    119        1.1       jtc #define BIGGEST(a, b)	(((a) > (b)) ? (a) : (b))
    120        1.1       jtc 
    121        1.1       jtc #ifdef TZNAME_MAX
    122        1.1       jtc #define MY_TZNAME_MAX	TZNAME_MAX
    123        1.1       jtc #endif /* defined TZNAME_MAX */
    124        1.1       jtc #ifndef TZNAME_MAX
    125        1.1       jtc #define MY_TZNAME_MAX	255
    126        1.1       jtc #endif /* !defined TZNAME_MAX */
    127        1.1       jtc 
    128       1.87  christos #define state __state
    129       1.87  christos struct state {
    130        1.1       jtc 	int		leapcnt;
    131        1.1       jtc 	int		timecnt;
    132        1.1       jtc 	int		typecnt;
    133        1.1       jtc 	int		charcnt;
    134       1.87  christos 	bool		goback;
    135       1.87  christos 	bool		goahead;
    136       1.45   mlelstv 	time_t		ats[TZ_MAX_TIMES];
    137        1.1       jtc 	unsigned char	types[TZ_MAX_TIMES];
    138        1.1       jtc 	struct ttinfo	ttis[TZ_MAX_TYPES];
    139       1.69  christos 	char		chars[/*CONSTCOND*/BIGGEST(BIGGEST(TZ_MAX_CHARS + 1,
    140       1.69  christos 				sizeof gmt), (2 * (MY_TZNAME_MAX + 1)))];
    141        1.1       jtc 	struct lsinfo	lsis[TZ_MAX_LEAPS];
    142       1.74  christos 	int		defaulttype; /* for early times or if no transitions */
    143        1.1       jtc };
    144        1.1       jtc 
    145       1.96  christos enum r_type {
    146       1.96  christos   JULIAN_DAY,		/* Jn = Julian day */
    147       1.96  christos   DAY_OF_YEAR,		/* n = day of year */
    148       1.96  christos   MONTH_NTH_DAY_OF_WEEK	/* Mm.n.d = month, week, day of week */
    149       1.96  christos };
    150       1.96  christos 
    151        1.1       jtc struct rule {
    152       1.96  christos 	enum r_type	r_type;		/* type of rule */
    153        1.1       jtc 	int		r_day;		/* day number of rule */
    154        1.1       jtc 	int		r_week;		/* week number of rule */
    155        1.1       jtc 	int		r_mon;		/* month number of rule */
    156       1.74  christos 	int_fast32_t	r_time;		/* transition time of rule */
    157        1.1       jtc };
    158        1.1       jtc 
    159       1.87  christos static struct tm *gmtsub(struct state const *, time_t const *, int_fast32_t,
    160       1.87  christos 			 struct tm *);
    161       1.87  christos static bool increment_overflow(int *, int);
    162       1.87  christos static bool increment_overflow_time(time_t *, int_fast32_t);
    163       1.87  christos static bool normalize_overflow32(int_fast32_t *, int *, int);
    164       1.87  christos static struct tm *timesub(time_t const *, int_fast32_t, struct state const *,
    165       1.87  christos 			  struct tm *);
    166       1.87  christos static bool typesequiv(struct state const *, int, int);
    167       1.87  christos static bool tzparse(char const *, struct state *, bool);
    168        1.1       jtc 
    169       1.49  christos static timezone_t lclptr;
    170       1.49  christos static timezone_t gmtptr;
    171        1.1       jtc 
    172        1.1       jtc #ifndef TZ_STRLEN_MAX
    173        1.1       jtc #define TZ_STRLEN_MAX 255
    174        1.1       jtc #endif /* !defined TZ_STRLEN_MAX */
    175        1.1       jtc 
    176       1.45   mlelstv static char		lcl_TZname[TZ_STRLEN_MAX + 1];
    177       1.45   mlelstv static int		lcl_is_set;
    178       1.42  christos 
    179       1.42  christos 
    180       1.33  christos #ifdef _REENTRANT
    181       1.45   mlelstv static rwlock_t lcl_lock = RWLOCK_INITIALIZER;
    182       1.19    kleink #endif
    183       1.19    kleink 
    184        1.1       jtc /*
    185        1.1       jtc ** Section 4.12.3 of X3.159-1989 requires that
    186        1.1       jtc **	Except for the strftime function, these functions [asctime,
    187        1.1       jtc **	ctime, gmtime, localtime] return values in one of two static
    188        1.1       jtc **	objects: a broken-down time structure and an array of char.
    189       1.45   mlelstv ** Thanks to Paul Eggert for noting this.
    190        1.1       jtc */
    191        1.1       jtc 
    192        1.1       jtc static struct tm	tm;
    193        1.1       jtc 
    194      1.109  christos #if !HAVE_POSIX_DECLS || TZ_TIME_T || defined(__NetBSD__)
    195      1.102  christos # if !defined(__LIBC12_SOURCE__)
    196      1.102  christos 
    197      1.102  christos __aconst char *		tzname[2] = {
    198      1.102  christos 	(__aconst char *)__UNCONST(wildabbr),
    199      1.102  christos 	(__aconst char *)__UNCONST(wildabbr)
    200      1.102  christos };
    201      1.102  christos 
    202      1.102  christos # else
    203      1.102  christos 
    204      1.102  christos extern __aconst char *	tzname[2];
    205      1.102  christos 
    206      1.102  christos # endif /* __LIBC12_SOURCE__ */
    207      1.102  christos 
    208      1.109  christos # if USG_COMPAT
    209      1.102  christos #  if !defined(__LIBC12_SOURCE__)
    210       1.42  christos long 			timezone = 0;
    211        1.1       jtc int			daylight = 0;
    212      1.109  christos #  else
    213       1.42  christos extern int		daylight;
    214       1.42  christos extern long		timezone __RENAME(__timezone13);
    215      1.102  christos #  endif /* __LIBC12_SOURCE__ */
    216      1.102  christos # endif /* defined USG_COMPAT */
    217        1.1       jtc 
    218      1.109  christos # ifdef ALTZONE
    219       1.81  christos long			altzone = 0;
    220      1.109  christos # endif /* defined ALTZONE */
    221      1.109  christos #endif /* !HAVE_POSIX_DECLS */
    222        1.1       jtc 
    223       1.91  christos /* Initialize *S to a value based on GMTOFF, ISDST, and ABBRIND.  */
    224       1.91  christos static void
    225       1.91  christos init_ttinfo(struct ttinfo *s, int_fast32_t gmtoff, bool isdst, int abbrind)
    226       1.91  christos {
    227       1.91  christos 	s->tt_gmtoff = gmtoff;
    228       1.91  christos 	s->tt_isdst = isdst;
    229       1.91  christos 	s->tt_abbrind = abbrind;
    230       1.91  christos 	s->tt_ttisstd = false;
    231       1.91  christos 	s->tt_ttisgmt = false;
    232       1.91  christos }
    233       1.91  christos 
    234       1.74  christos static int_fast32_t
    235       1.49  christos detzcode(const char *const codep)
    236        1.1       jtc {
    237       1.95  christos 	int_fast32_t result;
    238       1.95  christos 	int	i;
    239       1.95  christos 	int_fast32_t one = 1;
    240       1.95  christos 	int_fast32_t halfmaxval = one << (32 - 2);
    241       1.95  christos 	int_fast32_t maxval = halfmaxval - 1 + halfmaxval;
    242       1.95  christos 	int_fast32_t minval = -1 - maxval;
    243       1.45   mlelstv 
    244       1.95  christos 	result = codep[0] & 0x7f;
    245       1.95  christos 	for (i = 1; i < 4; ++i)
    246       1.45   mlelstv 		result = (result << 8) | (codep[i] & 0xff);
    247       1.95  christos 
    248       1.95  christos 	if (codep[0] & 0x80) {
    249       1.95  christos 	  /* Do two's-complement negation even on non-two's-complement machines.
    250       1.95  christos 	     If the result would be minval - 1, return minval.  */
    251       1.95  christos 	    result -= !TWOS_COMPLEMENT(int_fast32_t) && result != 0;
    252       1.95  christos 	    result += minval;
    253       1.95  christos 	}
    254       1.95  christos  	return result;
    255       1.45   mlelstv }
    256       1.45   mlelstv 
    257       1.81  christos static int_fast64_t
    258       1.49  christos detzcode64(const char *const codep)
    259       1.45   mlelstv {
    260       1.87  christos 	int_fast64_t result;
    261       1.49  christos 	int	i;
    262       1.95  christos 	int_fast64_t one = 1;
    263       1.95  christos 	int_fast64_t halfmaxval = one << (64 - 2);
    264       1.95  christos 	int_fast64_t maxval = halfmaxval - 1 + halfmaxval;
    265       1.95  christos 	int_fast64_t minval = -TWOS_COMPLEMENT(int_fast64_t) - maxval;
    266        1.1       jtc 
    267       1.95  christos 	result = codep[0] & 0x7f;
    268       1.95  christos 	for (i = 1; i < 8; ++i)
    269       1.81  christos 		result = (result << 8) | (codep[i] & 0xff);
    270       1.95  christos 
    271       1.95  christos 	if (codep[0] & 0x80) {
    272       1.95  christos 	  /* Do two's-complement negation even on non-two's-complement machines.
    273       1.95  christos 	     If the result would be minval - 1, return minval.  */
    274       1.95  christos 	  result -= !TWOS_COMPLEMENT(int_fast64_t) && result != 0;
    275       1.95  christos 	  result += minval;
    276       1.95  christos 	}
    277       1.95  christos  	return result;
    278        1.1       jtc }
    279        1.1       jtc 
    280       1.49  christos const char *
    281       1.49  christos tzgetname(const timezone_t sp, int isdst)
    282       1.49  christos {
    283       1.49  christos 	int i;
    284      1.103  ginsbach 	for (i = 0; i < sp->typecnt; ++i) {
    285       1.49  christos 		const struct ttinfo *const ttisp = &sp->ttis[sp->types[i]];
    286       1.49  christos 
    287       1.49  christos 		if (ttisp->tt_isdst == isdst)
    288       1.49  christos 			return &sp->chars[ttisp->tt_abbrind];
    289       1.49  christos 	}
    290       1.88  christos 	errno = ESRCH;
    291       1.49  christos 	return NULL;
    292       1.49  christos }
    293       1.49  christos 
    294       1.99  christos long
    295       1.99  christos tzgetgmtoff(const timezone_t sp, int isdst)
    296       1.99  christos {
    297       1.99  christos 	int i;
    298       1.99  christos 	long l = -1;
    299      1.103  ginsbach 	for (i = 0; i < sp->typecnt; ++i) {
    300       1.99  christos 		const struct ttinfo *const ttisp = &sp->ttis[sp->types[i]];
    301       1.99  christos 
    302       1.99  christos 		if (ttisp->tt_isdst == isdst) {
    303       1.99  christos 			l = ttisp->tt_gmtoff;
    304       1.99  christos 			if (sp->types[i] != 0)
    305       1.99  christos 				return l;
    306       1.99  christos 		}
    307       1.99  christos 	}
    308       1.99  christos 	if (l == -1)
    309       1.99  christos 		errno = ESRCH;
    310       1.99  christos 	return l;
    311       1.99  christos }
    312       1.99  christos 
    313       1.49  christos static void
    314       1.93  christos scrub_abbrs(struct state *sp)
    315       1.49  christos {
    316       1.93  christos 	int i;
    317       1.49  christos 
    318       1.49  christos 	/*
    319       1.49  christos 	** First, replace bogus characters.
    320       1.49  christos 	*/
    321       1.49  christos 	for (i = 0; i < sp->charcnt; ++i)
    322       1.49  christos 		if (strchr(TZ_ABBR_CHAR_SET, sp->chars[i]) == NULL)
    323       1.49  christos 			sp->chars[i] = TZ_ABBR_ERR_CHAR;
    324       1.49  christos 	/*
    325       1.49  christos 	** Second, truncate long abbreviations.
    326       1.49  christos 	*/
    327       1.49  christos 	for (i = 0; i < sp->typecnt; ++i) {
    328       1.49  christos 		const struct ttinfo * const	ttisp = &sp->ttis[i];
    329       1.49  christos 		char *				cp = &sp->chars[ttisp->tt_abbrind];
    330       1.49  christos 
    331       1.49  christos 		if (strlen(cp) > TZ_ABBR_MAX_LEN &&
    332       1.49  christos 			strcmp(cp, GRANDPARENTED) != 0)
    333       1.49  christos 				*(cp + TZ_ABBR_MAX_LEN) = '\0';
    334       1.49  christos 	}
    335       1.49  christos }
    336       1.49  christos 
    337       1.93  christos static void
    338       1.93  christos update_tzname_etc(const struct state *sp, const struct ttinfo *ttisp)
    339       1.92  christos {
    340      1.109  christos #if HAVE_TZNAME
    341       1.93  christos 	tzname[ttisp->tt_isdst] = __UNCONST(&sp->chars[ttisp->tt_abbrind]);
    342      1.109  christos #endif
    343      1.109  christos #if USG_COMPAT
    344       1.93  christos 	if (!ttisp->tt_isdst)
    345       1.93  christos 		timezone = - ttisp->tt_gmtoff;
    346       1.93  christos #endif
    347       1.92  christos #ifdef ALTZONE
    348       1.93  christos 	if (ttisp->tt_isdst)
    349       1.93  christos 	    altzone = - ttisp->tt_gmtoff;
    350       1.92  christos #endif /* defined ALTZONE */
    351       1.92  christos }
    352       1.92  christos 
    353       1.45   mlelstv static void
    354       1.45   mlelstv settzname(void)
    355        1.1       jtc {
    356       1.49  christos 	timezone_t const	sp = lclptr;
    357       1.49  christos 	int			i;
    358        1.1       jtc 
    359      1.109  christos #if HAVE_TZNAME
    360      1.109  christos 	tzname[0] = tzname[1] =
    361      1.109  christos 	    (__aconst char *) __UNCONST(sp ? wildabbr : gmt);
    362      1.109  christos #endif
    363      1.109  christos #if USG_COMPAT
    364        1.1       jtc 	daylight = 0;
    365        1.1       jtc 	timezone = 0;
    366      1.109  christos #endif
    367        1.1       jtc #ifdef ALTZONE
    368        1.1       jtc 	altzone = 0;
    369        1.1       jtc #endif /* defined ALTZONE */
    370        1.1       jtc 	if (sp == NULL) {
    371        1.1       jtc 		return;
    372        1.1       jtc 	}
    373       1.58  christos 	/*
    374       1.58  christos 	** And to get the latest zone names into tzname. . .
    375       1.58  christos 	*/
    376       1.92  christos 	for (i = 0; i < sp->typecnt; ++i)
    377       1.93  christos 		update_tzname_etc(sp, &sp->ttis[i]);
    378        1.1       jtc 
    379       1.93  christos 	for (i = 0; i < sp->timecnt; ++i) {
    380       1.93  christos 		const struct ttinfo * const ttisp = &sp->ttis[sp->types[i]];
    381       1.93  christos 		update_tzname_etc(sp, ttisp);
    382      1.109  christos #if USG_COMPAT
    383       1.93  christos 		if (ttisp->tt_isdst)
    384       1.93  christos 			daylight = 1;
    385      1.109  christos #endif
    386       1.93  christos 	}
    387        1.1       jtc }
    388        1.1       jtc 
    389       1.87  christos static bool
    390       1.49  christos differ_by_repeat(const time_t t1, const time_t t0)
    391       1.45   mlelstv {
    392       1.78  christos 	if (TYPE_BIT(time_t) - TYPE_SIGNED(time_t) < SECSPERREPEAT_BITS)
    393       1.78  christos 		return 0;
    394       1.45   mlelstv 	return (int_fast64_t)t1 - (int_fast64_t)t0 == SECSPERREPEAT;
    395       1.45   mlelstv }
    396       1.45   mlelstv 
    397       1.91  christos union input_buffer {
    398       1.91  christos 	/* The first part of the buffer, interpreted as a header.  */
    399       1.91  christos 	struct tzhead tzhead;
    400       1.91  christos 
    401       1.91  christos 	/* The entire buffer.  */
    402       1.91  christos 	char buf[2 * sizeof(struct tzhead) + 2 * sizeof (struct state)
    403       1.91  christos 	  + 4 * TZ_MAX_TIMES];
    404       1.91  christos };
    405       1.91  christos 
    406      1.109  christos /* TZDIR with a trailing '/' rather than a trailing '\0'.  */
    407      1.109  christos static char const tzdirslash[sizeof TZDIR] = TZDIR "/";
    408      1.109  christos 
    409       1.91  christos /* Local storage needed for 'tzloadbody'.  */
    410       1.91  christos union local_storage {
    411       1.91  christos 	/* The results of analyzing the file's contents after it is opened.  */
    412      1.109  christos 	struct file_analysis {
    413       1.91  christos 		/* The input buffer.  */
    414       1.91  christos 		union input_buffer u;
    415       1.91  christos 
    416       1.91  christos 		/* A temporary state used for parsing a TZ string in the file.  */
    417       1.91  christos 		struct state st;
    418       1.91  christos 	} u;
    419      1.109  christos 
    420      1.109  christos 	/* The file name to be opened.  */
    421      1.109  christos 	char fullname[/*CONSTCOND*/BIGGEST(sizeof (struct file_analysis),
    422      1.109  christos 	    sizeof tzdirslash + 1024)];
    423       1.91  christos };
    424       1.91  christos 
    425       1.91  christos /* Load tz data from the file named NAME into *SP.  Read extended
    426       1.91  christos    format if DOEXTEND.  Use *LSP for temporary storage.  Return 0 on
    427       1.91  christos    success, an errno value on failure.  */
    428       1.91  christos static int
    429       1.91  christos tzloadbody(char const *name, struct state *sp, bool doextend,
    430       1.91  christos   union local_storage *lsp)
    431       1.49  christos {
    432       1.49  christos 	int			i;
    433       1.49  christos 	int			fid;
    434       1.49  christos 	int			stored;
    435       1.66  christos 	ssize_t			nread;
    436       1.91  christos 	bool			doaccess;
    437       1.91  christos 	union input_buffer	*up = &lsp->u.u;
    438       1.91  christos 	size_t			tzheadsize = sizeof(struct tzhead);
    439       1.83  christos 
    440       1.87  christos 	sp->goback = sp->goahead = false;
    441       1.83  christos 
    442       1.83  christos 	if (! name) {
    443       1.83  christos 		name = TZDEFAULT;
    444       1.83  christos 		if (! name)
    445       1.91  christos 			return EINVAL;
    446       1.83  christos 	}
    447       1.83  christos 
    448       1.83  christos 	if (name[0] == ':')
    449       1.83  christos 		++name;
    450  1.111.2.1  pgoyette #ifdef SUPPRESS_TZDIR
    451  1.111.2.1  pgoyette 	/* Do not prepend TZDIR.  This is intended for specialized
    452  1.111.2.1  pgoyette 	   applications only, due to its security implications.  */
    453  1.111.2.1  pgoyette 	doaccess = true;
    454  1.111.2.1  pgoyette #else
    455       1.83  christos 	doaccess = name[0] == '/';
    456  1.111.2.1  pgoyette #endif
    457       1.83  christos 	if (!doaccess) {
    458      1.109  christos 		size_t namelen = strlen(name);
    459      1.109  christos 		if (sizeof lsp->fullname - sizeof tzdirslash <= namelen)
    460       1.91  christos 			return ENAMETOOLONG;
    461      1.109  christos 
    462      1.109  christos 		/* Create a string "TZDIR/NAME".  Using sprintf here
    463      1.109  christos 		   would pull in stdio (and would fail if the
    464      1.109  christos 		   resulting string length exceeded INT_MAX!).  */
    465      1.109  christos 		memcpy(lsp->fullname, tzdirslash, sizeof tzdirslash);
    466      1.109  christos 		strcpy(lsp->fullname + sizeof tzdirslash, name);
    467      1.109  christos 
    468       1.83  christos 		/* Set doaccess if '.' (as in "../") shows up in name.  */
    469       1.83  christos 		if (strchr(name, '.'))
    470       1.87  christos 			doaccess = true;
    471      1.110       kre 		name = lsp->fullname;
    472        1.1       jtc 	}
    473       1.83  christos 	if (doaccess && access(name, R_OK) != 0)
    474       1.91  christos 		return errno;
    475       1.83  christos 
    476       1.83  christos 	fid = open(name, OPEN_MODE);
    477       1.83  christos 	if (fid < 0)
    478       1.91  christos 		return errno;
    479       1.58  christos 	nread = read(fid, up->buf, sizeof up->buf);
    480       1.91  christos 	if (nread < (ssize_t)tzheadsize) {
    481       1.91  christos 		int err = nread < 0 ? errno : EINVAL;
    482       1.91  christos 		close(fid);
    483       1.91  christos 		return err;
    484       1.91  christos 	}
    485       1.91  christos 	if (close(fid) < 0)
    486       1.91  christos 		return errno;
    487       1.45   mlelstv 	for (stored = 4; stored <= 8; stored *= 2) {
    488       1.87  christos 		int_fast32_t ttisstdcnt = detzcode(up->tzhead.tzh_ttisstdcnt);
    489       1.87  christos 		int_fast32_t ttisgmtcnt = detzcode(up->tzhead.tzh_ttisgmtcnt);
    490      1.109  christos 		int_fast64_t prevtr = 0;
    491      1.109  christos 		int_fast32_t prevcorr = 0;
    492       1.87  christos 		int_fast32_t leapcnt = detzcode(up->tzhead.tzh_leapcnt);
    493       1.87  christos 		int_fast32_t timecnt = detzcode(up->tzhead.tzh_timecnt);
    494       1.87  christos 		int_fast32_t typecnt = detzcode(up->tzhead.tzh_typecnt);
    495       1.87  christos 		int_fast32_t charcnt = detzcode(up->tzhead.tzh_charcnt);
    496       1.91  christos 		char const *p = up->buf + tzheadsize;
    497       1.87  christos 		if (! (0 <= leapcnt && leapcnt < TZ_MAX_LEAPS
    498       1.87  christos 		       && 0 < typecnt && typecnt < TZ_MAX_TYPES
    499       1.87  christos 		       && 0 <= timecnt && timecnt < TZ_MAX_TIMES
    500       1.87  christos 		       && 0 <= charcnt && charcnt < TZ_MAX_CHARS
    501       1.87  christos 		       && (ttisstdcnt == typecnt || ttisstdcnt == 0)
    502       1.87  christos 		       && (ttisgmtcnt == typecnt || ttisgmtcnt == 0)))
    503       1.91  christos 		  return EINVAL;
    504       1.91  christos 		if ((size_t)nread
    505       1.91  christos 		    < (tzheadsize		/* struct tzhead */
    506       1.91  christos 		       + timecnt * stored	/* ats */
    507       1.87  christos 		       + timecnt		/* types */
    508       1.87  christos 		       + typecnt * 6		/* ttinfos */
    509       1.87  christos 		       + charcnt		/* chars */
    510       1.87  christos 		       + leapcnt * (stored + 4)	/* lsinfos */
    511       1.87  christos 		       + ttisstdcnt		/* ttisstds */
    512       1.87  christos 		       + ttisgmtcnt))		/* ttisgmts */
    513       1.91  christos 		  return EINVAL;
    514       1.87  christos 		sp->leapcnt = leapcnt;
    515       1.87  christos 		sp->timecnt = timecnt;
    516       1.87  christos 		sp->typecnt = typecnt;
    517       1.87  christos 		sp->charcnt = charcnt;
    518       1.87  christos 
    519       1.87  christos 		/* Read transitions, discarding those out of time_t range.
    520      1.109  christos 		   But pretend the last transition before TIME_T_MIN
    521      1.109  christos 		   occurred at TIME_T_MIN.  */
    522       1.81  christos 		timecnt = 0;
    523        1.1       jtc 		for (i = 0; i < sp->timecnt; ++i) {
    524       1.81  christos 			int_fast64_t at
    525       1.81  christos 			  = stored == 4 ? detzcode(p) : detzcode64(p);
    526      1.109  christos 			sp->types[i] = at <= TIME_T_MAX;
    527       1.81  christos 			if (sp->types[i]) {
    528       1.87  christos 				time_t attime
    529       1.87  christos 				    = ((TYPE_SIGNED(time_t) ?
    530      1.109  christos 				    at < TIME_T_MIN : at < 0)
    531      1.109  christos 				    ? TIME_T_MIN : (time_t)at);
    532       1.87  christos 				if (timecnt && attime <= sp->ats[timecnt - 1]) {
    533       1.87  christos 					if (attime < sp->ats[timecnt - 1])
    534       1.91  christos 						return EINVAL;
    535       1.87  christos 					sp->types[i - 1] = 0;
    536       1.87  christos 					timecnt--;
    537       1.81  christos 				}
    538       1.87  christos 				sp->ats[timecnt++] = attime;
    539       1.81  christos 			}
    540       1.45   mlelstv 			p += stored;
    541        1.1       jtc 		}
    542       1.87  christos 
    543       1.81  christos 		timecnt = 0;
    544        1.1       jtc 		for (i = 0; i < sp->timecnt; ++i) {
    545       1.81  christos 			unsigned char typ = *p++;
    546       1.81  christos 			if (sp->typecnt <= typ)
    547       1.91  christos 			  return EINVAL;
    548       1.81  christos 			if (sp->types[i])
    549       1.81  christos 				sp->types[timecnt++] = typ;
    550        1.1       jtc 		}
    551       1.87  christos 		sp->timecnt = timecnt;
    552        1.1       jtc 		for (i = 0; i < sp->typecnt; ++i) {
    553       1.49  christos 			struct ttinfo *	ttisp;
    554       1.87  christos 			unsigned char isdst, abbrind;
    555        1.1       jtc 
    556        1.1       jtc 			ttisp = &sp->ttis[i];
    557        1.1       jtc 			ttisp->tt_gmtoff = detzcode(p);
    558        1.1       jtc 			p += 4;
    559       1.87  christos 			isdst = *p++;
    560       1.87  christos 			if (! (isdst < 2))
    561       1.91  christos 				return EINVAL;
    562       1.87  christos 			ttisp->tt_isdst = isdst;
    563       1.87  christos 			abbrind = *p++;
    564       1.87  christos 			if (! (abbrind < sp->charcnt))
    565       1.91  christos 				return EINVAL;
    566       1.87  christos 			ttisp->tt_abbrind = abbrind;
    567        1.1       jtc 		}
    568        1.1       jtc 		for (i = 0; i < sp->charcnt; ++i)
    569        1.1       jtc 			sp->chars[i] = *p++;
    570        1.1       jtc 		sp->chars[i] = '\0';	/* ensure '\0' at end */
    571       1.87  christos 
    572       1.87  christos 		/* Read leap seconds, discarding those out of time_t range.  */
    573       1.87  christos 		leapcnt = 0;
    574        1.1       jtc 		for (i = 0; i < sp->leapcnt; ++i) {
    575       1.87  christos 			int_fast64_t tr = stored == 4 ? detzcode(p) :
    576       1.87  christos 			    detzcode64(p);
    577       1.87  christos 			int_fast32_t corr = detzcode(p + stored);
    578       1.87  christos 			p += stored + 4;
    579      1.109  christos 			/* Leap seconds cannot occur before the Epoch.  */
    580      1.109  christos 			if (tr < 0)
    581      1.109  christos 				return EINVAL;
    582      1.109  christos 			if (tr <= TIME_T_MAX) {
    583      1.109  christos 		    /* Leap seconds cannot occur more than once per UTC month,
    584      1.109  christos 		       and UTC months are at least 28 days long (minus 1
    585      1.109  christos 		       second for a negative leap second).  Each leap second's
    586      1.109  christos 		       correction must differ from the previous one's by 1
    587      1.109  christos 		       second.  */
    588      1.109  christos 				if (tr - prevtr < 28 * SECSPERDAY - 1
    589      1.109  christos 				    || (corr != prevcorr - 1
    590      1.109  christos 				    && corr != prevcorr + 1))
    591      1.109  christos 					  return EINVAL;
    592      1.109  christos 
    593      1.109  christos 				sp->lsis[leapcnt].ls_trans =
    594      1.109  christos 				    (time_t)(prevtr = tr);
    595      1.109  christos 				sp->lsis[leapcnt].ls_corr = prevcorr = corr;
    596       1.87  christos 				leapcnt++;
    597       1.87  christos 			}
    598       1.87  christos 		}
    599       1.87  christos 		sp->leapcnt = leapcnt;
    600        1.1       jtc 
    601        1.1       jtc 		for (i = 0; i < sp->typecnt; ++i) {
    602       1.49  christos 			struct ttinfo *	ttisp;
    603        1.1       jtc 
    604        1.1       jtc 			ttisp = &sp->ttis[i];
    605        1.1       jtc 			if (ttisstdcnt == 0)
    606       1.87  christos 				ttisp->tt_ttisstd = false;
    607        1.1       jtc 			else {
    608       1.87  christos 				if (*p != true && *p != false)
    609       1.91  christos 				  return EINVAL;
    610        1.1       jtc 				ttisp->tt_ttisstd = *p++;
    611        1.1       jtc 			}
    612        1.1       jtc 		}
    613        1.1       jtc 		for (i = 0; i < sp->typecnt; ++i) {
    614       1.49  christos 			struct ttinfo *	ttisp;
    615        1.1       jtc 
    616        1.1       jtc 			ttisp = &sp->ttis[i];
    617        1.1       jtc 			if (ttisgmtcnt == 0)
    618       1.87  christos 				ttisp->tt_ttisgmt = false;
    619        1.1       jtc 			else {
    620       1.87  christos 				if (*p != true && *p != false)
    621       1.91  christos 						return EINVAL;
    622        1.1       jtc 				ttisp->tt_ttisgmt = *p++;
    623        1.1       jtc 			}
    624        1.1       jtc 		}
    625       1.45   mlelstv 		/*
    626       1.45   mlelstv 		** If this is an old file, we're done.
    627       1.45   mlelstv 		*/
    628       1.58  christos 		if (up->tzhead.tzh_version[0] == '\0')
    629       1.45   mlelstv 			break;
    630       1.58  christos 		nread -= p - up->buf;
    631       1.91  christos 		memmove(up->buf, p, (size_t)nread);
    632       1.45   mlelstv 	}
    633       1.45   mlelstv 	if (doextend && nread > 2 &&
    634       1.58  christos 		up->buf[0] == '\n' && up->buf[nread - 1] == '\n' &&
    635       1.45   mlelstv 		sp->typecnt + 2 <= TZ_MAX_TYPES) {
    636       1.87  christos 			struct state *ts = &lsp->u.st;
    637       1.45   mlelstv 
    638       1.58  christos 			up->buf[nread - 1] = '\0';
    639       1.87  christos 			if (tzparse(&up->buf[1], ts, false)
    640       1.98  christos 			    && ts->typecnt == 2) {
    641       1.98  christos 
    642       1.98  christos 			  /* Attempt to reuse existing abbreviations.
    643      1.106  christos 			     Without this, America/Anchorage would be right on
    644      1.106  christos 			     the edge after 2037 when TZ_MAX_CHARS is 50, as
    645      1.106  christos 			     sp->charcnt equals 40 (for LMT AST AWT APT AHST
    646       1.98  christos 			     AHDT YST AKDT AKST) and ts->charcnt equals 10
    647       1.98  christos 			     (for AKST AKDT).  Reusing means sp->charcnt can
    648      1.106  christos 			     stay 40 in this example.  */
    649       1.98  christos 			  int gotabbr = 0;
    650       1.98  christos 			  int charcnt = sp->charcnt;
    651       1.98  christos 			  for (i = 0; i < 2; i++) {
    652       1.98  christos 			    char *tsabbr = ts->chars + ts->ttis[i].tt_abbrind;
    653       1.98  christos 			    int j;
    654       1.98  christos 			    for (j = 0; j < charcnt; j++)
    655       1.98  christos 			      if (strcmp(sp->chars + j, tsabbr) == 0) {
    656       1.98  christos 				ts->ttis[i].tt_abbrind = j;
    657       1.98  christos 				gotabbr++;
    658       1.98  christos 				break;
    659       1.98  christos 			      }
    660       1.98  christos 			    if (! (j < charcnt)) {
    661       1.99  christos 			      size_t tsabbrlen = strlen(tsabbr);
    662       1.98  christos 			      if (j + tsabbrlen < TZ_MAX_CHARS) {
    663       1.98  christos 				strcpy(sp->chars + j, tsabbr);
    664      1.100  christos 				charcnt = (int_fast32_t)(j + tsabbrlen + 1);
    665       1.98  christos 				ts->ttis[i].tt_abbrind = j;
    666       1.98  christos 				gotabbr++;
    667       1.98  christos 			      }
    668       1.98  christos 			    }
    669       1.98  christos 			  }
    670       1.98  christos 			  if (gotabbr == 2) {
    671       1.98  christos 			    sp->charcnt = charcnt;
    672      1.106  christos 
    673      1.106  christos 			    /* Ignore any trailing, no-op transitions generated
    674      1.106  christos 			       by zic as they don't help here and can run afoul
    675      1.106  christos 			       of bugs in zic 2016j or earlier.  */
    676      1.106  christos 			    while (1 < sp->timecnt
    677      1.106  christos 				   && (sp->types[sp->timecnt - 1]
    678      1.106  christos 				       == sp->types[sp->timecnt - 2]))
    679      1.106  christos 			      sp->timecnt--;
    680      1.106  christos 
    681       1.98  christos 			    for (i = 0; i < ts->timecnt; i++)
    682       1.98  christos 			      if (sp->ats[sp->timecnt - 1] < ts->ats[i])
    683       1.98  christos 				break;
    684       1.98  christos 			    while (i < ts->timecnt
    685       1.98  christos 				   && sp->timecnt < TZ_MAX_TIMES) {
    686       1.98  christos 			      sp->ats[sp->timecnt] = ts->ats[i];
    687       1.98  christos 			      sp->types[sp->timecnt] = (sp->typecnt
    688       1.98  christos 							+ ts->types[i]);
    689       1.98  christos 			      sp->timecnt++;
    690       1.98  christos 			      i++;
    691       1.98  christos 			    }
    692       1.98  christos 			    sp->ttis[sp->typecnt++] = ts->ttis[0];
    693       1.98  christos 			    sp->ttis[sp->typecnt++] = ts->ttis[1];
    694       1.98  christos 			  }
    695       1.45   mlelstv 			}
    696       1.45   mlelstv 	}
    697       1.45   mlelstv 	if (sp->timecnt > 1) {
    698       1.45   mlelstv 		for (i = 1; i < sp->timecnt; ++i)
    699       1.45   mlelstv 			if (typesequiv(sp, sp->types[i], sp->types[0]) &&
    700       1.45   mlelstv 				differ_by_repeat(sp->ats[i], sp->ats[0])) {
    701       1.87  christos 					sp->goback = true;
    702       1.45   mlelstv 					break;
    703       1.45   mlelstv 				}
    704       1.45   mlelstv 		for (i = sp->timecnt - 2; i >= 0; --i)
    705       1.45   mlelstv 			if (typesequiv(sp, sp->types[sp->timecnt - 1],
    706       1.45   mlelstv 				sp->types[i]) &&
    707       1.45   mlelstv 				differ_by_repeat(sp->ats[sp->timecnt - 1],
    708       1.45   mlelstv 				sp->ats[i])) {
    709       1.87  christos 					sp->goahead = true;
    710       1.45   mlelstv 					break;
    711       1.45   mlelstv 		}
    712        1.1       jtc 	}
    713       1.74  christos 	/*
    714      1.109  christos 	** If type 0 is unused in transitions,
    715       1.74  christos 	** it's the type to use for early times.
    716       1.74  christos 	*/
    717       1.87  christos 	for (i = 0; i < sp->timecnt; ++i)
    718       1.74  christos 		if (sp->types[i] == 0)
    719       1.74  christos 			break;
    720       1.87  christos 	i = i < sp->timecnt ? -1 : 0;
    721       1.74  christos 	/*
    722       1.74  christos 	** Absent the above,
    723       1.74  christos 	** if there are transition times
    724       1.74  christos 	** and the first transition is to a daylight time
    725       1.74  christos 	** find the standard type less than and closest to
    726       1.74  christos 	** the type of the first transition.
    727       1.74  christos 	*/
    728       1.74  christos 	if (i < 0 && sp->timecnt > 0 && sp->ttis[sp->types[0]].tt_isdst) {
    729       1.74  christos 		i = sp->types[0];
    730       1.74  christos 		while (--i >= 0)
    731       1.74  christos 			if (!sp->ttis[i].tt_isdst)
    732       1.74  christos 				break;
    733       1.74  christos 	}
    734       1.74  christos 	/*
    735       1.74  christos 	** If no result yet, find the first standard type.
    736       1.74  christos 	** If there is none, punt to type zero.
    737       1.74  christos 	*/
    738       1.74  christos 	if (i < 0) {
    739       1.74  christos 		i = 0;
    740       1.74  christos 		while (sp->ttis[i].tt_isdst)
    741       1.74  christos 			if (++i >= sp->typecnt) {
    742       1.74  christos 				i = 0;
    743       1.74  christos 				break;
    744       1.74  christos 			}
    745       1.74  christos 	}
    746       1.74  christos 	sp->defaulttype = i;
    747       1.91  christos 	return 0;
    748       1.91  christos }
    749       1.91  christos 
    750       1.91  christos /* Load tz data from the file named NAME into *SP.  Read extended
    751       1.91  christos    format if DOEXTEND.  Return 0 on success, an errno value on failure.  */
    752       1.91  christos static int
    753       1.91  christos tzload(char const *name, struct state *sp, bool doextend)
    754       1.91  christos {
    755       1.91  christos 	union local_storage *lsp = malloc(sizeof *lsp);
    756       1.91  christos 	if (!lsp)
    757       1.91  christos 		return errno;
    758       1.91  christos 	else {
    759       1.91  christos 		int err = tzloadbody(name, sp, doextend, lsp);
    760       1.91  christos 		free(lsp);
    761       1.91  christos 		return err;
    762       1.91  christos 	}
    763        1.1       jtc }
    764        1.1       jtc 
    765       1.87  christos static bool
    766       1.96  christos typesequiv(const struct state *sp, int a, int b)
    767       1.45   mlelstv {
    768       1.87  christos 	bool result;
    769       1.45   mlelstv 
    770       1.45   mlelstv 	if (sp == NULL ||
    771       1.45   mlelstv 		a < 0 || a >= sp->typecnt ||
    772       1.45   mlelstv 		b < 0 || b >= sp->typecnt)
    773       1.87  christos 			result = false;
    774       1.45   mlelstv 	else {
    775       1.49  christos 		const struct ttinfo *	ap = &sp->ttis[a];
    776       1.49  christos 		const struct ttinfo *	bp = &sp->ttis[b];
    777       1.45   mlelstv 		result = ap->tt_gmtoff == bp->tt_gmtoff &&
    778       1.45   mlelstv 			ap->tt_isdst == bp->tt_isdst &&
    779       1.45   mlelstv 			ap->tt_ttisstd == bp->tt_ttisstd &&
    780       1.45   mlelstv 			ap->tt_ttisgmt == bp->tt_ttisgmt &&
    781       1.45   mlelstv 			strcmp(&sp->chars[ap->tt_abbrind],
    782       1.45   mlelstv 			&sp->chars[bp->tt_abbrind]) == 0;
    783       1.45   mlelstv 	}
    784       1.45   mlelstv 	return result;
    785       1.45   mlelstv }
    786       1.45   mlelstv 
    787        1.1       jtc static const int	mon_lengths[2][MONSPERYEAR] = {
    788        1.1       jtc 	{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
    789        1.1       jtc 	{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
    790        1.1       jtc };
    791        1.1       jtc 
    792        1.1       jtc static const int	year_lengths[2] = {
    793        1.1       jtc 	DAYSPERNYEAR, DAYSPERLYEAR
    794        1.1       jtc };
    795        1.1       jtc 
    796        1.1       jtc /*
    797        1.1       jtc ** Given a pointer into a time zone string, scan until a character that is not
    798       1.45   mlelstv ** a valid character in a zone name is found. Return a pointer to that
    799        1.1       jtc ** character.
    800        1.1       jtc */
    801        1.1       jtc 
    802      1.109  christos static const char *
    803       1.67      matt getzname(const char *strp)
    804        1.1       jtc {
    805       1.49  christos 	char	c;
    806        1.1       jtc 
    807        1.5       jtc 	while ((c = *strp) != '\0' && !is_digit(c) && c != ',' && c != '-' &&
    808        1.1       jtc 		c != '+')
    809        1.1       jtc 			++strp;
    810        1.1       jtc 	return strp;
    811        1.1       jtc }
    812        1.1       jtc 
    813        1.1       jtc /*
    814       1.45   mlelstv ** Given a pointer into an extended time zone string, scan until the ending
    815       1.45   mlelstv ** delimiter of the zone name is located. Return a pointer to the delimiter.
    816       1.45   mlelstv **
    817       1.45   mlelstv ** As with getzname above, the legal character set is actually quite
    818       1.45   mlelstv ** restricted, with other characters producing undefined results.
    819       1.45   mlelstv ** We don't do any checking here; checking is done later in common-case code.
    820       1.45   mlelstv */
    821       1.45   mlelstv 
    822      1.109  christos static const char *
    823       1.49  christos getqzname(const char *strp, const int delim)
    824       1.45   mlelstv {
    825       1.49  christos 	int	c;
    826       1.45   mlelstv 
    827       1.45   mlelstv 	while ((c = *strp) != '\0' && c != delim)
    828       1.45   mlelstv 		++strp;
    829       1.45   mlelstv 	return strp;
    830       1.45   mlelstv }
    831       1.45   mlelstv 
    832       1.45   mlelstv /*
    833        1.1       jtc ** Given a pointer into a time zone string, extract a number from that string.
    834        1.1       jtc ** Check that the number is within a specified range; if it is not, return
    835        1.1       jtc ** NULL.
    836        1.1       jtc ** Otherwise, return a pointer to the first character not part of the number.
    837        1.1       jtc */
    838        1.1       jtc 
    839        1.1       jtc static const char *
    840       1.68  christos getnum(const char *strp, int *const nump, const int min, const int max)
    841        1.1       jtc {
    842       1.49  christos 	char	c;
    843       1.49  christos 	int	num;
    844        1.1       jtc 
    845       1.46  christos 	if (strp == NULL || !is_digit(c = *strp)) {
    846       1.46  christos 		errno = EINVAL;
    847        1.1       jtc 		return NULL;
    848       1.46  christos 	}
    849        1.1       jtc 	num = 0;
    850        1.5       jtc 	do {
    851        1.1       jtc 		num = num * 10 + (c - '0');
    852       1.46  christos 		if (num > max) {
    853       1.46  christos 			errno = EOVERFLOW;
    854        1.1       jtc 			return NULL;	/* illegal value */
    855       1.46  christos 		}
    856        1.5       jtc 		c = *++strp;
    857        1.5       jtc 	} while (is_digit(c));
    858       1.46  christos 	if (num < min) {
    859       1.46  christos 		errno = EINVAL;
    860        1.1       jtc 		return NULL;		/* illegal value */
    861       1.46  christos 	}
    862        1.1       jtc 	*nump = num;
    863        1.1       jtc 	return strp;
    864        1.1       jtc }
    865        1.1       jtc 
    866        1.1       jtc /*
    867        1.1       jtc ** Given a pointer into a time zone string, extract a number of seconds,
    868        1.1       jtc ** in hh[:mm[:ss]] form, from the string.
    869        1.1       jtc ** If any error occurs, return NULL.
    870        1.1       jtc ** Otherwise, return a pointer to the first character not part of the number
    871        1.1       jtc ** of seconds.
    872        1.1       jtc */
    873        1.1       jtc 
    874        1.1       jtc static const char *
    875       1.74  christos getsecs(const char *strp, int_fast32_t *const secsp)
    876        1.1       jtc {
    877        1.1       jtc 	int	num;
    878        1.1       jtc 
    879        1.1       jtc 	/*
    880       1.83  christos 	** 'HOURSPERDAY * DAYSPERWEEK - 1' allows quasi-Posix rules like
    881        1.1       jtc 	** "M10.4.6/26", which does not conform to Posix,
    882        1.1       jtc 	** but which specifies the equivalent of
    883       1.83  christos 	** "02:00 on the first Sunday on or after 23 Oct".
    884        1.1       jtc 	*/
    885        1.1       jtc 	strp = getnum(strp, &num, 0, HOURSPERDAY * DAYSPERWEEK - 1);
    886        1.1       jtc 	if (strp == NULL)
    887        1.1       jtc 		return NULL;
    888       1.74  christos 	*secsp = num * (int_fast32_t) SECSPERHOUR;
    889        1.1       jtc 	if (*strp == ':') {
    890        1.1       jtc 		++strp;
    891        1.1       jtc 		strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
    892        1.1       jtc 		if (strp == NULL)
    893        1.1       jtc 			return NULL;
    894        1.1       jtc 		*secsp += num * SECSPERMIN;
    895        1.1       jtc 		if (*strp == ':') {
    896        1.1       jtc 			++strp;
    897       1.83  christos 			/* 'SECSPERMIN' allows for leap seconds.  */
    898        1.1       jtc 			strp = getnum(strp, &num, 0, SECSPERMIN);
    899        1.1       jtc 			if (strp == NULL)
    900        1.1       jtc 				return NULL;
    901        1.1       jtc 			*secsp += num;
    902        1.1       jtc 		}
    903        1.1       jtc 	}
    904        1.1       jtc 	return strp;
    905        1.1       jtc }
    906        1.1       jtc 
    907        1.1       jtc /*
    908        1.1       jtc ** Given a pointer into a time zone string, extract an offset, in
    909        1.1       jtc ** [+-]hh[:mm[:ss]] form, from the string.
    910        1.1       jtc ** If any error occurs, return NULL.
    911        1.1       jtc ** Otherwise, return a pointer to the first character not part of the time.
    912        1.1       jtc */
    913        1.1       jtc 
    914        1.1       jtc static const char *
    915       1.74  christos getoffset(const char *strp, int_fast32_t *const offsetp)
    916        1.1       jtc {
    917       1.87  christos 	bool neg = false;
    918        1.1       jtc 
    919        1.1       jtc 	if (*strp == '-') {
    920       1.87  christos 		neg = true;
    921        1.1       jtc 		++strp;
    922        1.5       jtc 	} else if (*strp == '+')
    923        1.5       jtc 		++strp;
    924        1.1       jtc 	strp = getsecs(strp, offsetp);
    925        1.1       jtc 	if (strp == NULL)
    926        1.1       jtc 		return NULL;		/* illegal time */
    927        1.1       jtc 	if (neg)
    928        1.1       jtc 		*offsetp = -*offsetp;
    929        1.1       jtc 	return strp;
    930        1.1       jtc }
    931        1.1       jtc 
    932        1.1       jtc /*
    933        1.1       jtc ** Given a pointer into a time zone string, extract a rule in the form
    934       1.45   mlelstv ** date[/time]. See POSIX section 8 for the format of "date" and "time".
    935        1.1       jtc ** If a valid rule is not found, return NULL.
    936        1.1       jtc ** Otherwise, return a pointer to the first character not part of the rule.
    937        1.1       jtc */
    938        1.1       jtc 
    939        1.1       jtc static const char *
    940       1.49  christos getrule(const char *strp, struct rule *const rulep)
    941        1.1       jtc {
    942        1.1       jtc 	if (*strp == 'J') {
    943        1.1       jtc 		/*
    944        1.1       jtc 		** Julian day.
    945        1.1       jtc 		*/
    946        1.1       jtc 		rulep->r_type = JULIAN_DAY;
    947        1.1       jtc 		++strp;
    948        1.1       jtc 		strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
    949        1.1       jtc 	} else if (*strp == 'M') {
    950        1.1       jtc 		/*
    951        1.1       jtc 		** Month, week, day.
    952        1.1       jtc 		*/
    953        1.1       jtc 		rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
    954        1.1       jtc 		++strp;
    955        1.1       jtc 		strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
    956        1.1       jtc 		if (strp == NULL)
    957        1.1       jtc 			return NULL;
    958        1.1       jtc 		if (*strp++ != '.')
    959        1.1       jtc 			return NULL;
    960        1.1       jtc 		strp = getnum(strp, &rulep->r_week, 1, 5);
    961        1.1       jtc 		if (strp == NULL)
    962        1.1       jtc 			return NULL;
    963        1.1       jtc 		if (*strp++ != '.')
    964        1.1       jtc 			return NULL;
    965        1.1       jtc 		strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
    966        1.5       jtc 	} else if (is_digit(*strp)) {
    967        1.1       jtc 		/*
    968        1.1       jtc 		** Day of year.
    969        1.1       jtc 		*/
    970        1.1       jtc 		rulep->r_type = DAY_OF_YEAR;
    971        1.1       jtc 		strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
    972        1.1       jtc 	} else	return NULL;		/* invalid format */
    973        1.1       jtc 	if (strp == NULL)
    974        1.1       jtc 		return NULL;
    975        1.1       jtc 	if (*strp == '/') {
    976        1.1       jtc 		/*
    977        1.1       jtc 		** Time specified.
    978        1.1       jtc 		*/
    979        1.1       jtc 		++strp;
    980       1.78  christos 		strp = getoffset(strp, &rulep->r_time);
    981        1.1       jtc 	} else	rulep->r_time = 2 * SECSPERHOUR;	/* default = 2:00:00 */
    982        1.1       jtc 	return strp;
    983        1.1       jtc }
    984        1.1       jtc 
    985        1.1       jtc /*
    986       1.81  christos ** Given a year, a rule, and the offset from UT at the time that rule takes
    987       1.81  christos ** effect, calculate the year-relative time that rule takes effect.
    988        1.1       jtc */
    989        1.1       jtc 
    990      1.109  christos static int_fast32_t
    991       1.81  christos transtime(const int year, const struct rule *const rulep,
    992       1.81  christos 	  const int_fast32_t offset)
    993       1.49  christos {
    994       1.87  christos 	bool	leapyear;
    995       1.87  christos 	int_fast32_t value;
    996       1.49  christos 	int	i;
    997        1.1       jtc 	int		d, m1, yy0, yy1, yy2, dow;
    998        1.1       jtc 
    999        1.1       jtc 	INITIALIZE(value);
   1000        1.1       jtc 	leapyear = isleap(year);
   1001        1.1       jtc 	switch (rulep->r_type) {
   1002        1.1       jtc 
   1003        1.1       jtc 	case JULIAN_DAY:
   1004        1.1       jtc 		/*
   1005        1.1       jtc 		** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
   1006        1.1       jtc 		** years.
   1007        1.1       jtc 		** In non-leap years, or if the day number is 59 or less, just
   1008        1.1       jtc 		** add SECSPERDAY times the day number-1 to the time of
   1009        1.1       jtc 		** January 1, midnight, to get the day.
   1010        1.1       jtc 		*/
   1011       1.81  christos 		value = (rulep->r_day - 1) * SECSPERDAY;
   1012        1.1       jtc 		if (leapyear && rulep->r_day >= 60)
   1013        1.1       jtc 			value += SECSPERDAY;
   1014        1.1       jtc 		break;
   1015        1.1       jtc 
   1016        1.1       jtc 	case DAY_OF_YEAR:
   1017        1.1       jtc 		/*
   1018        1.1       jtc 		** n - day of year.
   1019        1.1       jtc 		** Just add SECSPERDAY times the day number to the time of
   1020        1.1       jtc 		** January 1, midnight, to get the day.
   1021        1.1       jtc 		*/
   1022       1.81  christos 		value = rulep->r_day * SECSPERDAY;
   1023        1.1       jtc 		break;
   1024        1.1       jtc 
   1025        1.1       jtc 	case MONTH_NTH_DAY_OF_WEEK:
   1026        1.1       jtc 		/*
   1027        1.1       jtc 		** Mm.n.d - nth "dth day" of month m.
   1028        1.1       jtc 		*/
   1029        1.1       jtc 
   1030        1.1       jtc 		/*
   1031        1.1       jtc 		** Use Zeller's Congruence to get day-of-week of first day of
   1032        1.1       jtc 		** month.
   1033        1.1       jtc 		*/
   1034        1.1       jtc 		m1 = (rulep->r_mon + 9) % 12 + 1;
   1035        1.1       jtc 		yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
   1036        1.1       jtc 		yy1 = yy0 / 100;
   1037        1.1       jtc 		yy2 = yy0 % 100;
   1038        1.1       jtc 		dow = ((26 * m1 - 2) / 10 +
   1039        1.1       jtc 			1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
   1040        1.1       jtc 		if (dow < 0)
   1041        1.1       jtc 			dow += DAYSPERWEEK;
   1042        1.1       jtc 
   1043        1.1       jtc 		/*
   1044       1.45   mlelstv 		** "dow" is the day-of-week of the first day of the month. Get
   1045        1.1       jtc 		** the day-of-month (zero-origin) of the first "dow" day of the
   1046        1.1       jtc 		** month.
   1047        1.1       jtc 		*/
   1048        1.1       jtc 		d = rulep->r_day - dow;
   1049        1.1       jtc 		if (d < 0)
   1050        1.1       jtc 			d += DAYSPERWEEK;
   1051        1.1       jtc 		for (i = 1; i < rulep->r_week; ++i) {
   1052        1.1       jtc 			if (d + DAYSPERWEEK >=
   1053        1.1       jtc 				mon_lengths[leapyear][rulep->r_mon - 1])
   1054        1.1       jtc 					break;
   1055        1.1       jtc 			d += DAYSPERWEEK;
   1056        1.1       jtc 		}
   1057        1.1       jtc 
   1058        1.1       jtc 		/*
   1059        1.1       jtc 		** "d" is the day-of-month (zero-origin) of the day we want.
   1060        1.1       jtc 		*/
   1061       1.81  christos 		value = d * SECSPERDAY;
   1062       1.81  christos 		for (i = 0; i < rulep->r_mon - 1; ++i)
   1063       1.81  christos 			value += mon_lengths[leapyear][i] * SECSPERDAY;
   1064        1.1       jtc 		break;
   1065        1.1       jtc 	}
   1066        1.1       jtc 
   1067        1.1       jtc 	/*
   1068       1.81  christos 	** "value" is the year-relative time of 00:00:00 UT on the day in
   1069       1.81  christos 	** question. To get the year-relative time of the specified local
   1070        1.1       jtc 	** time on that day, add the transition time and the current offset
   1071       1.78  christos 	** from UT.
   1072        1.1       jtc 	*/
   1073       1.81  christos 	return value + rulep->r_time + offset;
   1074        1.1       jtc }
   1075        1.1       jtc 
   1076        1.1       jtc /*
   1077        1.1       jtc ** Given a POSIX section 8-style TZ string, fill in the rule tables as
   1078        1.1       jtc ** appropriate.
   1079        1.1       jtc */
   1080        1.1       jtc 
   1081       1.87  christos static bool
   1082       1.96  christos tzparse(const char *name, struct state *sp, bool lastditch)
   1083       1.87  christos {
   1084       1.87  christos 	const char *	stdname;
   1085       1.87  christos 	const char *	dstname;
   1086       1.87  christos 	size_t		stdlen;
   1087       1.87  christos 	size_t		dstlen;
   1088       1.96  christos 	size_t		charcnt;
   1089       1.87  christos 	int_fast32_t	stdoffset;
   1090       1.87  christos 	int_fast32_t	dstoffset;
   1091       1.87  christos 	char *		cp;
   1092       1.87  christos 	bool		load_ok;
   1093        1.1       jtc 
   1094       1.84    martin 	dstname = NULL; /* XXX gcc */
   1095        1.1       jtc 	stdname = name;
   1096        1.1       jtc 	if (lastditch) {
   1097       1.96  christos 		stdlen = sizeof gmt - 1;
   1098        1.1       jtc 		name += stdlen;
   1099       1.10       jtc 		stdoffset = 0;
   1100        1.1       jtc 	} else {
   1101       1.45   mlelstv 		if (*name == '<') {
   1102       1.45   mlelstv 			name++;
   1103       1.45   mlelstv 			stdname = name;
   1104       1.45   mlelstv 			name = getqzname(name, '>');
   1105       1.45   mlelstv 			if (*name != '>')
   1106       1.87  christos 			  return false;
   1107       1.45   mlelstv 			stdlen = name - stdname;
   1108       1.45   mlelstv 			name++;
   1109       1.45   mlelstv 		} else {
   1110       1.45   mlelstv 			name = getzname(name);
   1111       1.45   mlelstv 			stdlen = name - stdname;
   1112       1.45   mlelstv 		}
   1113       1.96  christos 		if (!stdlen)
   1114       1.87  christos 			return false;
   1115       1.45   mlelstv 		name = getoffset(name, &stdoffset);
   1116        1.1       jtc 		if (name == NULL)
   1117       1.87  christos 			return false;
   1118        1.1       jtc 	}
   1119       1.96  christos 	charcnt = stdlen + 1;
   1120       1.96  christos 	if (sizeof sp->chars < charcnt)
   1121       1.96  christos 		return false;
   1122       1.91  christos 	load_ok = tzload(TZDEFRULES, sp, false) == 0;
   1123       1.87  christos 	if (!load_ok)
   1124        1.1       jtc 		sp->leapcnt = 0;		/* so, we're off a little */
   1125        1.1       jtc 	if (*name != '\0') {
   1126       1.45   mlelstv 		if (*name == '<') {
   1127       1.45   mlelstv 			dstname = ++name;
   1128       1.45   mlelstv 			name = getqzname(name, '>');
   1129       1.45   mlelstv 			if (*name != '>')
   1130       1.87  christos 				return false;
   1131       1.45   mlelstv 			dstlen = name - dstname;
   1132       1.45   mlelstv 			name++;
   1133       1.45   mlelstv 		} else {
   1134       1.45   mlelstv 			dstname = name;
   1135       1.45   mlelstv 			name = getzname(name);
   1136       1.45   mlelstv 			dstlen = name - dstname; /* length of DST zone name */
   1137       1.45   mlelstv 		}
   1138       1.96  christos 		if (!dstlen)
   1139       1.96  christos 		  return false;
   1140       1.96  christos 		charcnt += dstlen + 1;
   1141       1.96  christos 		if (sizeof sp->chars < charcnt)
   1142       1.96  christos 		  return false;
   1143        1.1       jtc 		if (*name != '\0' && *name != ',' && *name != ';') {
   1144       1.45   mlelstv 			name = getoffset(name, &dstoffset);
   1145        1.1       jtc 			if (name == NULL)
   1146       1.87  christos 			  return false;
   1147        1.1       jtc 		} else	dstoffset = stdoffset - SECSPERHOUR;
   1148       1.87  christos 		if (*name == '\0' && !load_ok)
   1149       1.22    kleink 			name = TZDEFRULESTRING;
   1150        1.1       jtc 		if (*name == ',' || *name == ';') {
   1151        1.1       jtc 			struct rule	start;
   1152        1.1       jtc 			struct rule	end;
   1153       1.78  christos 			int		year;
   1154       1.78  christos 			int		yearlim;
   1155       1.81  christos 			int		timecnt;
   1156       1.78  christos 			time_t		janfirst;
   1157      1.106  christos 			int_fast32_t janoffset = 0;
   1158      1.106  christos 			int yearbeg;
   1159        1.1       jtc 
   1160        1.1       jtc 			++name;
   1161       1.45   mlelstv 			if ((name = getrule(name, &start)) == NULL)
   1162       1.87  christos 				return false;
   1163        1.1       jtc 			if (*name++ != ',')
   1164       1.87  christos 				return false;
   1165       1.45   mlelstv 			if ((name = getrule(name, &end)) == NULL)
   1166       1.87  christos 				return false;
   1167        1.1       jtc 			if (*name != '\0')
   1168       1.87  christos 				return false;
   1169        1.1       jtc 			sp->typecnt = 2;	/* standard time and DST */
   1170        1.1       jtc 			/*
   1171       1.45   mlelstv 			** Two transitions per year, from EPOCH_YEAR forward.
   1172        1.1       jtc 			*/
   1173       1.91  christos 			init_ttinfo(&sp->ttis[0], -dstoffset, true,
   1174       1.91  christos 			    (int)(stdlen + 1));
   1175       1.91  christos 			init_ttinfo(&sp->ttis[1], -stdoffset, false, 0);
   1176       1.82  christos 			sp->defaulttype = 0;
   1177       1.81  christos 			timecnt = 0;
   1178        1.1       jtc 			janfirst = 0;
   1179      1.106  christos 			yearbeg = EPOCH_YEAR;
   1180      1.106  christos 
   1181      1.106  christos 			do {
   1182      1.106  christos 			  int_fast32_t yearsecs
   1183      1.106  christos 			    = year_lengths[isleap(yearbeg - 1)] * SECSPERDAY;
   1184      1.106  christos 			  yearbeg--;
   1185      1.106  christos 			  if (increment_overflow_time(&janfirst, -yearsecs)) {
   1186      1.106  christos 			    janoffset = -yearsecs;
   1187      1.106  christos 			    break;
   1188      1.106  christos 			  }
   1189      1.106  christos 			} while (EPOCH_YEAR - YEARSPERREPEAT / 2 < yearbeg);
   1190      1.106  christos 
   1191      1.106  christos 			yearlim = yearbeg + YEARSPERREPEAT + 1;
   1192      1.106  christos 			for (year = yearbeg; year < yearlim; year++) {
   1193       1.81  christos 				int_fast32_t
   1194       1.81  christos 				  starttime = transtime(year, &start, stdoffset),
   1195       1.81  christos 				  endtime = transtime(year, &end, dstoffset);
   1196       1.81  christos 				int_fast32_t
   1197       1.81  christos 				  yearsecs = (year_lengths[isleap(year)]
   1198       1.81  christos 					      * SECSPERDAY);
   1199       1.87  christos 				bool reversed = endtime < starttime;
   1200       1.81  christos 				if (reversed) {
   1201       1.81  christos 					int_fast32_t swap = starttime;
   1202       1.81  christos 					starttime = endtime;
   1203       1.81  christos 					endtime = swap;
   1204       1.81  christos 				}
   1205       1.81  christos 				if (reversed
   1206       1.78  christos 				    || (starttime < endtime
   1207       1.78  christos 					&& (endtime - starttime
   1208       1.78  christos 					    < (yearsecs
   1209       1.78  christos 					       + (stdoffset - dstoffset))))) {
   1210       1.81  christos 					if (TZ_MAX_TIMES - 2 < timecnt)
   1211       1.78  christos 						break;
   1212       1.81  christos 					sp->ats[timecnt] = janfirst;
   1213      1.106  christos 					if (! increment_overflow_time
   1214      1.106  christos 					    (&sp->ats[timecnt],
   1215      1.106  christos 					     janoffset + starttime))
   1216      1.106  christos 					  sp->types[timecnt++] = reversed;
   1217      1.106  christos 					else if (janoffset)
   1218      1.106  christos 					  sp->defaulttype = reversed;
   1219       1.81  christos 					sp->ats[timecnt] = janfirst;
   1220      1.106  christos 					if (! increment_overflow_time
   1221      1.106  christos 					    (&sp->ats[timecnt],
   1222      1.106  christos 					     janoffset + endtime)) {
   1223      1.106  christos 					  sp->types[timecnt++] = !reversed;
   1224      1.106  christos 					  yearlim = year + YEARSPERREPEAT + 1;
   1225      1.106  christos 					} else if (janoffset)
   1226      1.106  christos 					  sp->defaulttype = !reversed;
   1227        1.1       jtc 				}
   1228      1.106  christos 				if (increment_overflow_time
   1229      1.106  christos 				    (&janfirst, janoffset + yearsecs))
   1230       1.45   mlelstv 					break;
   1231      1.106  christos 				janoffset = 0;
   1232        1.1       jtc 			}
   1233       1.81  christos 			sp->timecnt = timecnt;
   1234      1.106  christos 			if (! timecnt)
   1235       1.78  christos 				sp->typecnt = 1;	/* Perpetual DST.  */
   1236      1.106  christos 			else if (YEARSPERREPEAT < year - yearbeg)
   1237      1.106  christos 				sp->goback = sp->goahead = true;
   1238        1.1       jtc 		} else {
   1239       1.74  christos 			int_fast32_t	theirstdoffset;
   1240       1.74  christos 			int_fast32_t	theirdstoffset;
   1241       1.74  christos 			int_fast32_t	theiroffset;
   1242       1.87  christos 			bool		isdst;
   1243       1.74  christos 			int		i;
   1244       1.74  christos 			int		j;
   1245        1.1       jtc 
   1246        1.1       jtc 			if (*name != '\0')
   1247       1.87  christos 				return false;
   1248        1.1       jtc 			/*
   1249       1.69  christos 			** Initial values of theirstdoffset and theirdstoffset.
   1250        1.1       jtc 			*/
   1251        1.1       jtc 			theirstdoffset = 0;
   1252        1.1       jtc 			for (i = 0; i < sp->timecnt; ++i) {
   1253        1.1       jtc 				j = sp->types[i];
   1254        1.1       jtc 				if (!sp->ttis[j].tt_isdst) {
   1255        1.5       jtc 					theirstdoffset =
   1256        1.5       jtc 						-sp->ttis[j].tt_gmtoff;
   1257        1.1       jtc 					break;
   1258        1.1       jtc 				}
   1259        1.1       jtc 			}
   1260       1.45   mlelstv 			theirdstoffset = 0;
   1261       1.45   mlelstv 			for (i = 0; i < sp->timecnt; ++i) {
   1262       1.45   mlelstv 				j = sp->types[i];
   1263       1.45   mlelstv 				if (sp->ttis[j].tt_isdst) {
   1264       1.45   mlelstv 					theirdstoffset =
   1265       1.45   mlelstv 						-sp->ttis[j].tt_gmtoff;
   1266       1.45   mlelstv 					break;
   1267       1.45   mlelstv 				}
   1268       1.45   mlelstv 			}
   1269        1.1       jtc 			/*
   1270        1.1       jtc 			** Initially we're assumed to be in standard time.
   1271        1.1       jtc 			*/
   1272       1.87  christos 			isdst = false;
   1273        1.1       jtc 			theiroffset = theirstdoffset;
   1274        1.1       jtc 			/*
   1275        1.1       jtc 			** Now juggle transition times and types
   1276        1.1       jtc 			** tracking offsets as you do.
   1277        1.1       jtc 			*/
   1278        1.1       jtc 			for (i = 0; i < sp->timecnt; ++i) {
   1279        1.1       jtc 				j = sp->types[i];
   1280        1.1       jtc 				sp->types[i] = sp->ttis[j].tt_isdst;
   1281        1.1       jtc 				if (sp->ttis[j].tt_ttisgmt) {
   1282        1.1       jtc 					/* No adjustment to transition time */
   1283        1.1       jtc 				} else {
   1284        1.1       jtc 					/*
   1285  1.111.2.1  pgoyette 					** If daylight saving time is in
   1286  1.111.2.1  pgoyette 					** effect, and the transition time was
   1287  1.111.2.1  pgoyette 					** not specified as standard time, add
   1288  1.111.2.1  pgoyette 					** the daylight saving time offset to
   1289  1.111.2.1  pgoyette 					** the transition time; otherwise, add
   1290  1.111.2.1  pgoyette 					** the standard time offset to the
   1291  1.111.2.1  pgoyette 					** transition time.
   1292        1.1       jtc 					*/
   1293        1.1       jtc 					/*
   1294        1.1       jtc 					** Transitions from DST to DDST
   1295        1.1       jtc 					** will effectively disappear since
   1296        1.1       jtc 					** POSIX provides for only one DST
   1297        1.1       jtc 					** offset.
   1298        1.1       jtc 					*/
   1299       1.45   mlelstv 					if (isdst && !sp->ttis[j].tt_ttisstd) {
   1300       1.66  christos 						sp->ats[i] += (time_t)
   1301       1.66  christos 						    (dstoffset - theirdstoffset);
   1302       1.45   mlelstv 					} else {
   1303       1.66  christos 						sp->ats[i] += (time_t)
   1304       1.66  christos 						    (stdoffset - theirstdoffset);
   1305       1.45   mlelstv 					}
   1306        1.1       jtc 				}
   1307        1.1       jtc 				theiroffset = -sp->ttis[j].tt_gmtoff;
   1308       1.87  christos 				if (sp->ttis[j].tt_isdst)
   1309       1.39  christos 					theirstdoffset = theiroffset;
   1310       1.45   mlelstv 				else	theirdstoffset = theiroffset;
   1311        1.1       jtc 			}
   1312        1.1       jtc 			/*
   1313        1.1       jtc 			** Finally, fill in ttis.
   1314        1.1       jtc 			*/
   1315       1.91  christos 			init_ttinfo(&sp->ttis[0], -stdoffset, false, 0);
   1316       1.91  christos 			init_ttinfo(&sp->ttis[1], -dstoffset, true,
   1317       1.91  christos 			    (int)(stdlen + 1));
   1318        1.7       jtc 			sp->typecnt = 2;
   1319       1.82  christos 			sp->defaulttype = 0;
   1320        1.1       jtc 		}
   1321        1.1       jtc 	} else {
   1322        1.1       jtc 		dstlen = 0;
   1323        1.1       jtc 		sp->typecnt = 1;		/* only standard time */
   1324        1.1       jtc 		sp->timecnt = 0;
   1325       1.91  christos 		init_ttinfo(&sp->ttis[0], -stdoffset, false, 0);
   1326       1.91  christos 		init_ttinfo(&sp->ttis[1], 0, false, 0);
   1327       1.82  christos 		sp->defaulttype = 0;
   1328        1.1       jtc 	}
   1329       1.99  christos 	sp->charcnt = (int)charcnt;
   1330        1.1       jtc 	cp = sp->chars;
   1331       1.87  christos 	(void) memcpy(cp, stdname, stdlen);
   1332        1.1       jtc 	cp += stdlen;
   1333        1.1       jtc 	*cp++ = '\0';
   1334        1.1       jtc 	if (dstlen != 0) {
   1335       1.87  christos 		(void) memcpy(cp, dstname, dstlen);
   1336        1.1       jtc 		*(cp + dstlen) = '\0';
   1337        1.1       jtc 	}
   1338       1.87  christos 	return true;
   1339        1.1       jtc }
   1340        1.1       jtc 
   1341        1.1       jtc static void
   1342       1.87  christos gmtload(struct state *const sp)
   1343       1.49  christos {
   1344       1.91  christos 	if (tzload(gmt, sp, true) != 0)
   1345       1.87  christos 		(void) tzparse(gmt, sp, true);
   1346       1.49  christos }
   1347       1.49  christos 
   1348       1.91  christos static int
   1349       1.87  christos zoneinit(struct state *sp, char const *name)
   1350       1.49  christos {
   1351       1.87  christos 	if (name && ! name[0]) {
   1352       1.91  christos 		/*
   1353       1.91  christos 		** User wants it fast rather than right.
   1354       1.91  christos 		*/
   1355       1.91  christos 		sp->leapcnt = 0;		/* so, we're off a little */
   1356       1.87  christos 		sp->timecnt = 0;
   1357       1.87  christos 		sp->typecnt = 0;
   1358       1.91  christos 		sp->charcnt = 0;
   1359       1.91  christos 		sp->goback = sp->goahead = false;
   1360       1.91  christos 		init_ttinfo(&sp->ttis[0], 0, false, 0);
   1361       1.87  christos 		strcpy(sp->chars, gmt);
   1362       1.91  christos 		sp->defaulttype = 0;
   1363       1.91  christos 		return 0;
   1364       1.91  christos 	} else {
   1365       1.91  christos 		int err = tzload(name, sp, true);
   1366       1.91  christos 		if (err != 0 && name && name[0] != ':' &&
   1367       1.91  christos 		    tzparse(name, sp, false))
   1368       1.93  christos 			err = 0;
   1369       1.93  christos 		if (err == 0)
   1370       1.93  christos 			scrub_abbrs(sp);
   1371       1.91  christos 		return err;
   1372       1.87  christos 	}
   1373       1.49  christos }
   1374       1.87  christos 
   1375       1.19    kleink static void
   1376       1.87  christos tzsetlcl(char const *name)
   1377        1.1       jtc {
   1378       1.91  christos 	struct state *sp = lclptr;
   1379       1.87  christos 	int lcl = name ? strlen(name) < sizeof lcl_TZname : -1;
   1380       1.87  christos 	if (lcl < 0 ? lcl_is_set < 0
   1381       1.87  christos 	    : 0 < lcl_is_set && strcmp(lcl_TZname, name) == 0)
   1382        1.1       jtc 		return;
   1383        1.1       jtc 
   1384       1.91  christos 	if (! sp)
   1385       1.91  christos 		lclptr = sp = malloc(sizeof *lclptr);
   1386       1.91  christos 	if (sp) {
   1387       1.91  christos 		if (zoneinit(sp, name) != 0)
   1388       1.91  christos 			zoneinit(sp, "");
   1389       1.91  christos 		if (0 < lcl)
   1390       1.91  christos 			strcpy(lcl_TZname, name);
   1391       1.89  christos 	}
   1392       1.45   mlelstv 	settzname();
   1393       1.87  christos 	lcl_is_set = lcl;
   1394        1.1       jtc }
   1395        1.1       jtc 
   1396       1.87  christos #ifdef STD_INSPIRED
   1397        1.1       jtc void
   1398       1.45   mlelstv tzsetwall(void)
   1399       1.19    kleink {
   1400       1.45   mlelstv 	rwlock_wrlock(&lcl_lock);
   1401       1.87  christos 	tzsetlcl(NULL);
   1402       1.45   mlelstv 	rwlock_unlock(&lcl_lock);
   1403       1.19    kleink }
   1404       1.87  christos #endif
   1405       1.87  christos 
   1406       1.87  christos static void
   1407       1.87  christos tzset_unlocked(void)
   1408       1.87  christos {
   1409       1.87  christos 	tzsetlcl(getenv("TZ"));
   1410       1.87  christos }
   1411       1.19    kleink 
   1412       1.45   mlelstv void
   1413       1.87  christos tzset(void)
   1414        1.1       jtc {
   1415       1.87  christos 	rwlock_wrlock(&lcl_lock);
   1416       1.87  christos 	tzset_unlocked();
   1417       1.87  christos 	rwlock_unlock(&lcl_lock);
   1418       1.87  christos }
   1419        1.1       jtc 
   1420       1.87  christos static void
   1421       1.87  christos gmtcheck(void)
   1422       1.87  christos {
   1423       1.87  christos 	static bool gmt_is_set;
   1424       1.87  christos 	rwlock_wrlock(&lcl_lock);
   1425       1.87  christos 	if (! gmt_is_set) {
   1426       1.87  christos 		gmtptr = malloc(sizeof *gmtptr);
   1427       1.87  christos 		if (gmtptr)
   1428       1.87  christos 			gmtload(gmtptr);
   1429       1.87  christos 		gmt_is_set = true;
   1430        1.1       jtc 	}
   1431       1.87  christos 	rwlock_unlock(&lcl_lock);
   1432       1.87  christos }
   1433        1.1       jtc 
   1434       1.87  christos #if NETBSD_INSPIRED
   1435        1.1       jtc 
   1436       1.87  christos timezone_t
   1437       1.87  christos tzalloc(const char *name)
   1438       1.87  christos {
   1439       1.87  christos 	timezone_t sp = malloc(sizeof *sp);
   1440       1.91  christos 	if (sp) {
   1441       1.91  christos 		int err = zoneinit(sp, name);
   1442       1.91  christos 		if (err != 0) {
   1443       1.91  christos 			free(sp);
   1444       1.91  christos 			errno = err;
   1445       1.91  christos 			return NULL;
   1446       1.91  christos 		}
   1447       1.91  christos 	}
   1448       1.91  christos 	return sp;
   1449        1.1       jtc }
   1450        1.1       jtc 
   1451       1.19    kleink void
   1452       1.87  christos tzfree(timezone_t sp)
   1453       1.19    kleink {
   1454       1.87  christos 	free(sp);
   1455       1.19    kleink }
   1456       1.19    kleink 
   1457        1.1       jtc /*
   1458       1.87  christos ** NetBSD 6.1.4 has ctime_rz, but omit it because POSIX says ctime and
   1459       1.87  christos ** ctime_r are obsolescent and have potential security problems that
   1460       1.87  christos ** ctime_rz would share.  Callers can instead use localtime_rz + strftime.
   1461       1.87  christos **
   1462       1.87  christos ** NetBSD 6.1.4 has tzgetname, but omit it because it doesn't work
   1463       1.87  christos ** in zones with three or more time zone abbreviations.
   1464       1.87  christos ** Callers can instead use localtime_rz + strftime.
   1465       1.87  christos */
   1466       1.87  christos 
   1467       1.87  christos #endif
   1468       1.87  christos 
   1469       1.87  christos /*
   1470        1.1       jtc ** The easy way to behave "as if no library function calls" localtime
   1471       1.83  christos ** is to not call it, so we drop its guts into "localsub", which can be
   1472       1.83  christos ** freely called. (And no, the PANS doesn't require the above behavior,
   1473        1.1       jtc ** but it *is* desirable.)
   1474        1.1       jtc **
   1475       1.93  christos ** If successful and SETNAME is nonzero,
   1476       1.91  christos ** set the applicable parts of tzname, timezone and altzone;
   1477       1.91  christos ** however, it's OK to omit this step if the time zone is POSIX-compatible,
   1478       1.91  christos ** since in that case tzset should have already done this step correctly.
   1479       1.93  christos ** SETNAME's type is intfast32_t for compatibility with gmtsub,
   1480       1.93  christos ** but it is actually a boolean and its value should be 0 or 1.
   1481        1.1       jtc */
   1482        1.1       jtc 
   1483        1.1       jtc /*ARGSUSED*/
   1484       1.45   mlelstv static struct tm *
   1485       1.93  christos localsub(struct state const *sp, time_t const *timep, int_fast32_t setname,
   1486       1.87  christos 	 struct tm *const tmp)
   1487       1.49  christos {
   1488       1.49  christos 	const struct ttinfo *	ttisp;
   1489       1.49  christos 	int			i;
   1490       1.49  christos 	struct tm *		result;
   1491        1.1       jtc 	const time_t			t = *timep;
   1492        1.1       jtc 
   1493       1.87  christos 	if (sp == NULL) {
   1494       1.91  christos 		/* Don't bother to set tzname etc.; tzset has already done it.  */
   1495       1.91  christos 		return gmtsub(gmtptr, timep, 0, tmp);
   1496       1.87  christos 	}
   1497       1.45   mlelstv 	if ((sp->goback && t < sp->ats[0]) ||
   1498       1.45   mlelstv 		(sp->goahead && t > sp->ats[sp->timecnt - 1])) {
   1499       1.45   mlelstv 			time_t			newt = t;
   1500       1.49  christos 			time_t		seconds;
   1501       1.78  christos 			time_t		years;
   1502       1.45   mlelstv 
   1503       1.45   mlelstv 			if (t < sp->ats[0])
   1504       1.45   mlelstv 				seconds = sp->ats[0] - t;
   1505       1.45   mlelstv 			else	seconds = t - sp->ats[sp->timecnt - 1];
   1506       1.45   mlelstv 			--seconds;
   1507       1.78  christos 			years = (time_t)((seconds / SECSPERREPEAT + 1) * YEARSPERREPEAT);
   1508       1.78  christos 			seconds = (time_t)(years * AVGSECSPERYEAR);
   1509       1.45   mlelstv 			if (t < sp->ats[0])
   1510       1.45   mlelstv 				newt += seconds;
   1511       1.45   mlelstv 			else	newt -= seconds;
   1512       1.45   mlelstv 			if (newt < sp->ats[0] ||
   1513       1.88  christos 				newt > sp->ats[sp->timecnt - 1]) {
   1514       1.88  christos 				errno = EINVAL;
   1515       1.88  christos 				return NULL;	/* "cannot happen" */
   1516       1.88  christos 			}
   1517       1.93  christos 			result = localsub(sp, &newt, setname, tmp);
   1518       1.87  christos 			if (result) {
   1519       1.87  christos 				int_fast64_t newy;
   1520       1.45   mlelstv 
   1521       1.87  christos 				newy = result->tm_year;
   1522       1.45   mlelstv 				if (t < sp->ats[0])
   1523       1.78  christos 					newy -= years;
   1524       1.78  christos 				else	newy += years;
   1525       1.88  christos 				if (! (INT_MIN <= newy && newy <= INT_MAX)) {
   1526       1.88  christos 					errno = EOVERFLOW;
   1527       1.45   mlelstv 					return NULL;
   1528       1.88  christos 				}
   1529       1.87  christos 				result->tm_year = (int)newy;
   1530       1.45   mlelstv 			}
   1531       1.45   mlelstv 			return result;
   1532        1.1       jtc 	}
   1533        1.1       jtc 	if (sp->timecnt == 0 || t < sp->ats[0]) {
   1534       1.74  christos 		i = sp->defaulttype;
   1535        1.1       jtc 	} else {
   1536       1.49  christos 		int	lo = 1;
   1537       1.49  christos 		int	hi = sp->timecnt;
   1538       1.45   mlelstv 
   1539       1.45   mlelstv 		while (lo < hi) {
   1540       1.49  christos 			int	mid = (lo + hi) / 2;
   1541       1.45   mlelstv 
   1542       1.45   mlelstv 			if (t < sp->ats[mid])
   1543       1.45   mlelstv 				hi = mid;
   1544       1.45   mlelstv 			else	lo = mid + 1;
   1545       1.45   mlelstv 		}
   1546       1.45   mlelstv 		i = (int) sp->types[lo - 1];
   1547        1.1       jtc 	}
   1548        1.1       jtc 	ttisp = &sp->ttis[i];
   1549        1.1       jtc 	/*
   1550        1.1       jtc 	** To get (wrong) behavior that's compatible with System V Release 2.0
   1551        1.1       jtc 	** you'd replace the statement below with
   1552        1.1       jtc 	**	t += ttisp->tt_gmtoff;
   1553        1.1       jtc 	**	timesub(&t, 0L, sp, tmp);
   1554        1.1       jtc 	*/
   1555       1.87  christos 	result = timesub(&t, ttisp->tt_gmtoff, sp, tmp);
   1556       1.87  christos 	if (result) {
   1557       1.92  christos 		result->tm_isdst = ttisp->tt_isdst;
   1558       1.92  christos #ifdef TM_ZONE
   1559       1.93  christos 		result->TM_ZONE = __UNCONST(&sp->chars[ttisp->tt_abbrind]);
   1560       1.92  christos #endif /* defined TM_ZONE */
   1561       1.93  christos 		if (setname)
   1562       1.93  christos 			update_tzname_etc(sp, ttisp);
   1563       1.87  christos 	}
   1564       1.45   mlelstv 	return result;
   1565        1.1       jtc }
   1566        1.1       jtc 
   1567       1.87  christos #if NETBSD_INSPIRED
   1568       1.49  christos 
   1569        1.1       jtc struct tm *
   1570       1.87  christos localtime_rz(timezone_t sp, time_t const *timep, struct tm *tmp)
   1571       1.87  christos {
   1572       1.87  christos 	return localsub(sp, timep, 0, tmp);
   1573       1.87  christos }
   1574       1.87  christos 
   1575       1.87  christos #endif
   1576       1.87  christos 
   1577       1.87  christos static struct tm *
   1578       1.87  christos localtime_tzset(time_t const *timep, struct tm *tmp, bool setname)
   1579        1.1       jtc {
   1580       1.87  christos 	rwlock_wrlock(&lcl_lock);
   1581       1.87  christos 	if (setname || !lcl_is_set)
   1582       1.87  christos 		tzset_unlocked();
   1583       1.87  christos 	tmp = localsub(lclptr, timep, setname, tmp);
   1584       1.45   mlelstv 	rwlock_unlock(&lcl_lock);
   1585       1.49  christos 	return tmp;
   1586        1.1       jtc }
   1587        1.1       jtc 
   1588       1.49  christos struct tm *
   1589       1.96  christos localtime(const time_t *timep)
   1590       1.49  christos {
   1591       1.87  christos 	return localtime_tzset(timep, &tm, true);
   1592       1.49  christos }
   1593       1.35    kleink 
   1594       1.18    kleink struct tm *
   1595       1.87  christos localtime_r(const time_t * __restrict timep, struct tm *tmp)
   1596       1.18    kleink {
   1597      1.101  christos 	return localtime_tzset(timep, tmp, true);
   1598       1.18    kleink }
   1599       1.18    kleink 
   1600       1.18    kleink /*
   1601        1.1       jtc ** gmtsub is to gmtime as localsub is to localtime.
   1602        1.1       jtc */
   1603        1.1       jtc 
   1604       1.45   mlelstv static struct tm *
   1605       1.87  christos gmtsub(struct state const *sp, const time_t *timep, int_fast32_t offset,
   1606       1.87  christos        struct tm *tmp)
   1607        1.1       jtc {
   1608       1.49  christos 	struct tm *	result;
   1609       1.19    kleink 
   1610       1.87  christos 	result = timesub(timep, offset, gmtptr, tmp);
   1611        1.1       jtc #ifdef TM_ZONE
   1612        1.1       jtc 	/*
   1613        1.1       jtc 	** Could get fancy here and deliver something such as
   1614      1.104  christos 	** "+xx" or "-xx" if offset is non-zero,
   1615        1.1       jtc 	** but this is no time for a treasure hunt.
   1616        1.1       jtc 	*/
   1617       1.88  christos 	if (result)
   1618       1.88  christos 		result->TM_ZONE = offset ? __UNCONST(wildabbr) : gmtptr ?
   1619       1.88  christos 		    gmtptr->chars : __UNCONST(gmt);
   1620        1.1       jtc #endif /* defined TM_ZONE */
   1621       1.45   mlelstv 	return result;
   1622        1.1       jtc }
   1623        1.1       jtc 
   1624        1.1       jtc 
   1625       1.18    kleink /*
   1626       1.35    kleink ** Re-entrant version of gmtime.
   1627       1.35    kleink */
   1628       1.35    kleink 
   1629       1.18    kleink struct tm *
   1630       1.96  christos gmtime_r(const time_t *timep, struct tm *tmp)
   1631       1.18    kleink {
   1632       1.87  christos 	gmtcheck();
   1633       1.90  christos 	return gmtsub(NULL, timep, 0, tmp);
   1634       1.18    kleink }
   1635       1.18    kleink 
   1636       1.96  christos struct tm *
   1637       1.96  christos gmtime(const time_t *timep)
   1638       1.96  christos {
   1639       1.96  christos 	return gmtime_r(timep, &tm);
   1640       1.96  christos }
   1641        1.1       jtc #ifdef STD_INSPIRED
   1642        1.1       jtc 
   1643        1.1       jtc struct tm *
   1644       1.96  christos offtime(const time_t *timep, long offset)
   1645        1.1       jtc {
   1646       1.87  christos 	gmtcheck();
   1647       1.90  christos 	return gmtsub(gmtptr, timep, (int_fast32_t)offset, &tm);
   1648       1.49  christos }
   1649       1.49  christos 
   1650       1.49  christos struct tm *
   1651       1.49  christos offtime_r(const time_t *timep, long offset, struct tm *tmp)
   1652       1.49  christos {
   1653       1.87  christos 	gmtcheck();
   1654       1.90  christos 	return gmtsub(NULL, timep, (int_fast32_t)offset, tmp);
   1655        1.1       jtc }
   1656        1.1       jtc 
   1657        1.1       jtc #endif /* defined STD_INSPIRED */
   1658        1.1       jtc 
   1659      1.109  christos #if TZ_TIME_T
   1660      1.105  christos 
   1661      1.109  christos # if USG_COMPAT
   1662      1.105  christos #  define daylight 0
   1663      1.105  christos #  define timezone 0
   1664      1.105  christos # endif
   1665      1.105  christos # ifndef ALTZONE
   1666      1.105  christos #  define altzone 0
   1667      1.105  christos # endif
   1668      1.105  christos 
   1669      1.105  christos /* Convert from the underlying system's time_t to the ersatz time_tz,
   1670      1.105  christos    which is called 'time_t' in this file.  Typically, this merely
   1671      1.105  christos    converts the time's integer width.  On some platforms, the system
   1672      1.105  christos    time is local time not UT, or uses some epoch other than the POSIX
   1673      1.105  christos    epoch.
   1674      1.105  christos 
   1675      1.105  christos    Although this code appears to define a function named 'time' that
   1676      1.105  christos    returns time_t, the macros in private.h cause this code to actually
   1677      1.105  christos    define a function named 'tz_time' that returns tz_time_t.  The call
   1678      1.105  christos    to sys_time invokes the underlying system's 'time' function.  */
   1679      1.105  christos 
   1680      1.105  christos time_t
   1681      1.105  christos time(time_t *p)
   1682      1.105  christos {
   1683      1.105  christos   time_t r = sys_time(0);
   1684      1.105  christos   if (r != (time_t) -1) {
   1685      1.105  christos     int_fast32_t offset = EPOCH_LOCAL ? (daylight ? timezone : altzone) : 0;
   1686      1.105  christos     if (increment_overflow32(&offset, -EPOCH_OFFSET)
   1687      1.105  christos 	|| increment_overflow_time (&r, offset)) {
   1688      1.105  christos       errno = EOVERFLOW;
   1689      1.105  christos       r = -1;
   1690      1.105  christos     }
   1691      1.105  christos   }
   1692      1.105  christos   if (p)
   1693      1.105  christos     *p = r;
   1694      1.105  christos   return r;
   1695      1.105  christos }
   1696      1.105  christos #endif
   1697      1.105  christos 
   1698       1.45   mlelstv /*
   1699       1.45   mlelstv ** Return the number of leap years through the end of the given year
   1700       1.45   mlelstv ** where, to make the math easy, the answer for year zero is defined as zero.
   1701       1.45   mlelstv */
   1702      1.109  christos static int
   1703      1.109  christos leaps_thru_end_of_nonneg(int y)
   1704      1.109  christos {
   1705      1.109  christos 	return y / 4 - y / 100 + y / 400;
   1706      1.109  christos }
   1707       1.45   mlelstv 
   1708       1.87  christos static int ATTRIBUTE_PURE
   1709       1.49  christos leaps_thru_end_of(const int y)
   1710       1.45   mlelstv {
   1711      1.109  christos 	return (y < 0
   1712      1.109  christos 		? -1 - leaps_thru_end_of_nonneg(-1 - y)
   1713      1.109  christos 		: leaps_thru_end_of_nonneg(y));
   1714       1.45   mlelstv }
   1715       1.45   mlelstv 
   1716       1.45   mlelstv static struct tm *
   1717       1.96  christos timesub(const time_t *timep, int_fast32_t offset,
   1718       1.97       riz     const struct state *sp, struct tm *tmp)
   1719       1.49  christos {
   1720       1.49  christos 	const struct lsinfo *	lp;
   1721       1.49  christos 	time_t			tdays;
   1722       1.49  christos 	int			idays;	/* unsigned would be so 2003 */
   1723       1.74  christos 	int_fast64_t		rem;
   1724       1.49  christos 	int			y;
   1725       1.49  christos 	const int *		ip;
   1726       1.74  christos 	int_fast64_t		corr;
   1727      1.108       kre 	int			hit;
   1728       1.49  christos 	int			i;
   1729        1.1       jtc 
   1730        1.1       jtc 	corr = 0;
   1731       1.87  christos 	hit = false;
   1732        1.1       jtc 	i = (sp == NULL) ? 0 : sp->leapcnt;
   1733        1.1       jtc 	while (--i >= 0) {
   1734        1.1       jtc 		lp = &sp->lsis[i];
   1735        1.1       jtc 		if (*timep >= lp->ls_trans) {
   1736        1.1       jtc 			corr = lp->ls_corr;
   1737      1.109  christos 			hit = (*timep == lp->ls_trans
   1738      1.109  christos 			       && (i == 0 ? 0 : lp[-1].ls_corr) < corr);
   1739        1.1       jtc 			break;
   1740        1.1       jtc 		}
   1741        1.1       jtc 	}
   1742       1.45   mlelstv 	y = EPOCH_YEAR;
   1743       1.66  christos 	tdays = (time_t)(*timep / SECSPERDAY);
   1744       1.96  christos 	rem = *timep % SECSPERDAY;
   1745       1.45   mlelstv 	while (tdays < 0 || tdays >= year_lengths[isleap(y)]) {
   1746       1.45   mlelstv 		int		newy;
   1747       1.49  christos 		time_t	tdelta;
   1748       1.49  christos 		int	idelta;
   1749       1.49  christos 		int	leapdays;
   1750       1.45   mlelstv 
   1751       1.45   mlelstv 		tdelta = tdays / DAYSPERLYEAR;
   1752       1.78  christos 		if (! ((! TYPE_SIGNED(time_t) || INT_MIN <= tdelta)
   1753       1.78  christos 		       && tdelta <= INT_MAX))
   1754       1.91  christos 			goto out_of_range;
   1755       1.81  christos 		_DIAGASSERT(__type_fit(int, tdelta));
   1756       1.81  christos 		idelta = (int)tdelta;
   1757       1.45   mlelstv 		if (idelta == 0)
   1758       1.45   mlelstv 			idelta = (tdays < 0) ? -1 : 1;
   1759       1.45   mlelstv 		newy = y;
   1760       1.51  christos 		if (increment_overflow(&newy, idelta))
   1761       1.91  christos 			goto out_of_range;
   1762       1.45   mlelstv 		leapdays = leaps_thru_end_of(newy - 1) -
   1763       1.45   mlelstv 			leaps_thru_end_of(y - 1);
   1764       1.45   mlelstv 		tdays -= ((time_t) newy - y) * DAYSPERNYEAR;
   1765       1.45   mlelstv 		tdays -= leapdays;
   1766       1.45   mlelstv 		y = newy;
   1767       1.45   mlelstv 	}
   1768       1.45   mlelstv 	/*
   1769       1.45   mlelstv 	** Given the range, we can now fearlessly cast...
   1770       1.45   mlelstv 	*/
   1771       1.45   mlelstv 	idays = (int) tdays;
   1772       1.45   mlelstv 	rem += offset - corr;
   1773        1.1       jtc 	while (rem < 0) {
   1774        1.1       jtc 		rem += SECSPERDAY;
   1775       1.45   mlelstv 		--idays;
   1776        1.1       jtc 	}
   1777        1.1       jtc 	while (rem >= SECSPERDAY) {
   1778        1.1       jtc 		rem -= SECSPERDAY;
   1779       1.45   mlelstv 		++idays;
   1780       1.45   mlelstv 	}
   1781       1.45   mlelstv 	while (idays < 0) {
   1782       1.51  christos 		if (increment_overflow(&y, -1))
   1783       1.91  christos 			goto out_of_range;
   1784       1.45   mlelstv 		idays += year_lengths[isleap(y)];
   1785        1.1       jtc 	}
   1786       1.45   mlelstv 	while (idays >= year_lengths[isleap(y)]) {
   1787       1.45   mlelstv 		idays -= year_lengths[isleap(y)];
   1788       1.51  christos 		if (increment_overflow(&y, 1))
   1789       1.91  christos 			goto out_of_range;
   1790       1.45   mlelstv 	}
   1791       1.45   mlelstv 	tmp->tm_year = y;
   1792       1.51  christos 	if (increment_overflow(&tmp->tm_year, -TM_YEAR_BASE))
   1793       1.91  christos 		goto out_of_range;
   1794       1.45   mlelstv 	tmp->tm_yday = idays;
   1795       1.45   mlelstv 	/*
   1796       1.45   mlelstv 	** The "extra" mods below avoid overflow problems.
   1797       1.45   mlelstv 	*/
   1798       1.45   mlelstv 	tmp->tm_wday = EPOCH_WDAY +
   1799       1.45   mlelstv 		((y - EPOCH_YEAR) % DAYSPERWEEK) *
   1800       1.45   mlelstv 		(DAYSPERNYEAR % DAYSPERWEEK) +
   1801       1.45   mlelstv 		leaps_thru_end_of(y - 1) -
   1802       1.45   mlelstv 		leaps_thru_end_of(EPOCH_YEAR - 1) +
   1803       1.45   mlelstv 		idays;
   1804       1.45   mlelstv 	tmp->tm_wday %= DAYSPERWEEK;
   1805       1.45   mlelstv 	if (tmp->tm_wday < 0)
   1806       1.45   mlelstv 		tmp->tm_wday += DAYSPERWEEK;
   1807        1.1       jtc 	tmp->tm_hour = (int) (rem / SECSPERHOUR);
   1808       1.45   mlelstv 	rem %= SECSPERHOUR;
   1809        1.1       jtc 	tmp->tm_min = (int) (rem / SECSPERMIN);
   1810        1.6       jtc 	/*
   1811        1.6       jtc 	** A positive leap second requires a special
   1812       1.45   mlelstv 	** representation. This uses "... ??:59:60" et seq.
   1813        1.6       jtc 	*/
   1814        1.6       jtc 	tmp->tm_sec = (int) (rem % SECSPERMIN) + hit;
   1815       1.45   mlelstv 	ip = mon_lengths[isleap(y)];
   1816       1.45   mlelstv 	for (tmp->tm_mon = 0; idays >= ip[tmp->tm_mon]; ++(tmp->tm_mon))
   1817       1.45   mlelstv 		idays -= ip[tmp->tm_mon];
   1818       1.45   mlelstv 	tmp->tm_mday = (int) (idays + 1);
   1819        1.1       jtc 	tmp->tm_isdst = 0;
   1820        1.1       jtc #ifdef TM_GMTOFF
   1821        1.1       jtc 	tmp->TM_GMTOFF = offset;
   1822        1.1       jtc #endif /* defined TM_GMTOFF */
   1823       1.45   mlelstv 	return tmp;
   1824       1.91  christos out_of_range:
   1825       1.88  christos 	errno = EOVERFLOW;
   1826       1.88  christos 	return NULL;
   1827        1.1       jtc }
   1828        1.1       jtc 
   1829        1.1       jtc char *
   1830       1.96  christos ctime(const time_t *timep)
   1831        1.1       jtc {
   1832        1.1       jtc /*
   1833        1.1       jtc ** Section 4.12.3.2 of X3.159-1989 requires that
   1834       1.18    kleink **	The ctime function converts the calendar time pointed to by timer
   1835       1.45   mlelstv **	to local time in the form of a string. It is equivalent to
   1836        1.1       jtc **		asctime(localtime(timer))
   1837        1.1       jtc */
   1838       1.91  christos 	struct tm *tmp = localtime(timep);
   1839       1.91  christos 	return tmp ? asctime(tmp) : NULL;
   1840       1.18    kleink }
   1841       1.18    kleink 
   1842       1.18    kleink char *
   1843       1.96  christos ctime_r(const time_t *timep, char *buf)
   1844       1.18    kleink {
   1845       1.91  christos 	struct tm mytm;
   1846       1.91  christos 	struct tm *tmp = localtime_r(timep, &mytm);
   1847       1.91  christos 	return tmp ? asctime_r(tmp, buf) : NULL;
   1848        1.1       jtc }
   1849        1.1       jtc 
   1850       1.49  christos char *
   1851       1.49  christos ctime_rz(const timezone_t sp, const time_t * timep, char *buf)
   1852       1.49  christos {
   1853       1.49  christos 	struct tm	mytm, *rtm;
   1854       1.49  christos 
   1855       1.49  christos 	rtm = localtime_rz(sp, timep, &mytm);
   1856       1.49  christos 	if (rtm == NULL)
   1857       1.49  christos 		return NULL;
   1858       1.49  christos 	return asctime_r(rtm, buf);
   1859       1.49  christos }
   1860       1.49  christos 
   1861        1.1       jtc /*
   1862        1.1       jtc ** Adapted from code provided by Robert Elz, who writes:
   1863        1.1       jtc **	The "best" way to do mktime I think is based on an idea of Bob
   1864        1.7       jtc **	Kridle's (so its said...) from a long time ago.
   1865       1.45   mlelstv **	It does a binary search of the time_t space. Since time_t's are
   1866        1.1       jtc **	just 32 bits, its a max of 32 iterations (even at 64 bits it
   1867        1.1       jtc **	would still be very reasonable).
   1868        1.1       jtc */
   1869        1.1       jtc 
   1870        1.1       jtc #ifndef WRONG
   1871       1.51  christos #define WRONG	((time_t)-1)
   1872        1.1       jtc #endif /* !defined WRONG */
   1873        1.1       jtc 
   1874        1.1       jtc /*
   1875       1.87  christos ** Normalize logic courtesy Paul Eggert.
   1876        1.1       jtc */
   1877        1.1       jtc 
   1878       1.87  christos static bool
   1879       1.96  christos increment_overflow(int *ip, int j)
   1880        1.1       jtc {
   1881       1.87  christos 	int const	i = *ip;
   1882        1.1       jtc 
   1883       1.58  christos 	/*
   1884       1.58  christos 	** If i >= 0 there can only be overflow if i + j > INT_MAX
   1885       1.58  christos 	** or if j > INT_MAX - i; given i >= 0, INT_MAX - i cannot overflow.
   1886       1.58  christos 	** If i < 0 there can only be overflow if i + j < INT_MIN
   1887       1.58  christos 	** or if j < INT_MIN - i; given i < 0, INT_MIN - i cannot overflow.
   1888       1.58  christos 	*/
   1889       1.58  christos 	if ((i >= 0) ? (j > INT_MAX - i) : (j < INT_MIN - i))
   1890       1.87  christos 		return true;
   1891       1.58  christos 	*ip += j;
   1892       1.87  christos 	return false;
   1893        1.1       jtc }
   1894        1.1       jtc 
   1895       1.87  christos static bool
   1896       1.74  christos increment_overflow32(int_fast32_t *const lp, int const m)
   1897       1.45   mlelstv {
   1898       1.87  christos 	int_fast32_t const l = *lp;
   1899       1.45   mlelstv 
   1900       1.74  christos 	if ((l >= 0) ? (m > INT_FAST32_MAX - l) : (m < INT_FAST32_MIN - l))
   1901       1.87  christos 		return true;
   1902       1.58  christos 	*lp += m;
   1903       1.87  christos 	return false;
   1904       1.45   mlelstv }
   1905       1.45   mlelstv 
   1906       1.87  christos static bool
   1907       1.81  christos increment_overflow_time(time_t *tp, int_fast32_t j)
   1908       1.81  christos {
   1909       1.81  christos 	/*
   1910       1.81  christos 	** This is like
   1911      1.109  christos 	** 'if (! (TIME_T_MIN <= *tp + j && *tp + j <= TIME_T_MAX)) ...',
   1912       1.81  christos 	** except that it does the right thing even if *tp + j would overflow.
   1913       1.81  christos 	*/
   1914       1.81  christos 	if (! (j < 0
   1915      1.109  christos 	       ? (TYPE_SIGNED(time_t) ? TIME_T_MIN - j <= *tp : -1 - j < *tp)
   1916      1.109  christos 	       : *tp <= TIME_T_MAX - j))
   1917       1.87  christos 		return true;
   1918       1.81  christos 	*tp += j;
   1919       1.87  christos 	return false;
   1920       1.81  christos }
   1921       1.81  christos 
   1922       1.87  christos static bool
   1923       1.49  christos normalize_overflow(int *const tensptr, int *const unitsptr, const int base)
   1924        1.1       jtc {
   1925       1.49  christos 	int	tensdelta;
   1926        1.1       jtc 
   1927        1.1       jtc 	tensdelta = (*unitsptr >= 0) ?
   1928        1.1       jtc 		(*unitsptr / base) :
   1929        1.1       jtc 		(-1 - (-1 - *unitsptr) / base);
   1930        1.1       jtc 	*unitsptr -= tensdelta * base;
   1931        1.1       jtc 	return increment_overflow(tensptr, tensdelta);
   1932        1.1       jtc }
   1933        1.1       jtc 
   1934       1.87  christos static bool
   1935       1.96  christos normalize_overflow32(int_fast32_t *tensptr, int *unitsptr, int base)
   1936       1.45   mlelstv {
   1937       1.49  christos 	int	tensdelta;
   1938       1.45   mlelstv 
   1939       1.45   mlelstv 	tensdelta = (*unitsptr >= 0) ?
   1940       1.45   mlelstv 		(*unitsptr / base) :
   1941       1.45   mlelstv 		(-1 - (-1 - *unitsptr) / base);
   1942       1.45   mlelstv 	*unitsptr -= tensdelta * base;
   1943       1.74  christos 	return increment_overflow32(tensptr, tensdelta);
   1944       1.45   mlelstv }
   1945       1.45   mlelstv 
   1946       1.45   mlelstv static int
   1947       1.87  christos tmcomp(const struct tm *const atmp,
   1948       1.87  christos        const struct tm *const btmp)
   1949        1.1       jtc {
   1950       1.49  christos 	int	result;
   1951        1.1       jtc 
   1952       1.78  christos 	if (atmp->tm_year != btmp->tm_year)
   1953       1.78  christos 		return atmp->tm_year < btmp->tm_year ? -1 : 1;
   1954       1.78  christos 	if ((result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
   1955        1.1       jtc 		(result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
   1956        1.1       jtc 		(result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
   1957        1.1       jtc 		(result = (atmp->tm_min - btmp->tm_min)) == 0)
   1958        1.1       jtc 			result = atmp->tm_sec - btmp->tm_sec;
   1959        1.1       jtc 	return result;
   1960        1.1       jtc }
   1961        1.1       jtc 
   1962        1.1       jtc static time_t
   1963       1.87  christos time2sub(struct tm *const tmp,
   1964       1.87  christos 	 struct tm *(*funcp)(struct state const *, time_t const *,
   1965       1.87  christos 			     int_fast32_t, struct tm *),
   1966       1.87  christos 	 struct state const *sp,
   1967       1.87  christos  	 const int_fast32_t offset,
   1968       1.87  christos 	 bool *okayp,
   1969       1.87  christos 	 bool do_norm_secs)
   1970       1.49  christos {
   1971       1.49  christos 	int			dir;
   1972       1.49  christos 	int			i, j;
   1973       1.49  christos 	int			saved_seconds;
   1974       1.74  christos 	int_fast32_t		li;
   1975       1.49  christos 	time_t			lo;
   1976       1.49  christos 	time_t			hi;
   1977       1.61  christos #ifdef NO_ERROR_IN_DST_GAP
   1978       1.61  christos 	time_t			ilo;
   1979       1.61  christos #endif
   1980       1.74  christos 	int_fast32_t		y;
   1981       1.74  christos 	time_t			newt;
   1982       1.74  christos 	time_t			t;
   1983       1.74  christos 	struct tm		yourtm, mytm;
   1984        1.1       jtc 
   1985       1.87  christos 	*okayp = false;
   1986        1.1       jtc 	yourtm = *tmp;
   1987       1.64  christos #ifdef NO_ERROR_IN_DST_GAP
   1988       1.64  christos again:
   1989       1.64  christos #endif
   1990       1.13       jtc 	if (do_norm_secs) {
   1991       1.13       jtc 		if (normalize_overflow(&yourtm.tm_min, &yourtm.tm_sec,
   1992       1.60  christos 		    SECSPERMIN))
   1993       1.91  christos 			goto out_of_range;
   1994       1.13       jtc 	}
   1995        1.1       jtc 	if (normalize_overflow(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR))
   1996       1.91  christos 		goto out_of_range;
   1997        1.1       jtc 	if (normalize_overflow(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY))
   1998       1.91  christos 		goto out_of_range;
   1999       1.45   mlelstv 	y = yourtm.tm_year;
   2000       1.74  christos 	if (normalize_overflow32(&y, &yourtm.tm_mon, MONSPERYEAR))
   2001       1.91  christos 		goto out_of_range;
   2002        1.1       jtc 	/*
   2003       1.45   mlelstv 	** Turn y into an actual year number for now.
   2004        1.1       jtc 	** It is converted back to an offset from TM_YEAR_BASE later.
   2005        1.1       jtc 	*/
   2006       1.74  christos 	if (increment_overflow32(&y, TM_YEAR_BASE))
   2007       1.91  christos 		goto out_of_range;
   2008        1.1       jtc 	while (yourtm.tm_mday <= 0) {
   2009       1.74  christos 		if (increment_overflow32(&y, -1))
   2010       1.91  christos 			goto out_of_range;
   2011       1.45   mlelstv 		li = y + (1 < yourtm.tm_mon);
   2012       1.45   mlelstv 		yourtm.tm_mday += year_lengths[isleap(li)];
   2013        1.1       jtc 	}
   2014        1.1       jtc 	while (yourtm.tm_mday > DAYSPERLYEAR) {
   2015       1.45   mlelstv 		li = y + (1 < yourtm.tm_mon);
   2016       1.45   mlelstv 		yourtm.tm_mday -= year_lengths[isleap(li)];
   2017       1.74  christos 		if (increment_overflow32(&y, 1))
   2018       1.91  christos 			goto out_of_range;
   2019        1.1       jtc 	}
   2020        1.1       jtc 	for ( ; ; ) {
   2021       1.45   mlelstv 		i = mon_lengths[isleap(y)][yourtm.tm_mon];
   2022        1.1       jtc 		if (yourtm.tm_mday <= i)
   2023        1.1       jtc 			break;
   2024        1.1       jtc 		yourtm.tm_mday -= i;
   2025        1.1       jtc 		if (++yourtm.tm_mon >= MONSPERYEAR) {
   2026        1.1       jtc 			yourtm.tm_mon = 0;
   2027       1.74  christos 			if (increment_overflow32(&y, 1))
   2028       1.91  christos 				goto out_of_range;
   2029        1.1       jtc 		}
   2030        1.1       jtc 	}
   2031       1.74  christos 	if (increment_overflow32(&y, -TM_YEAR_BASE))
   2032       1.91  christos 		goto out_of_range;
   2033       1.87  christos 	if (! (INT_MIN <= y && y <= INT_MAX))
   2034       1.91  christos 		goto out_of_range;
   2035       1.66  christos 	yourtm.tm_year = (int)y;
   2036       1.29    kleink 	if (yourtm.tm_sec >= 0 && yourtm.tm_sec < SECSPERMIN)
   2037       1.29    kleink 		saved_seconds = 0;
   2038       1.45   mlelstv 	else if (y + TM_YEAR_BASE < EPOCH_YEAR) {
   2039        1.1       jtc 		/*
   2040        1.1       jtc 		** We can't set tm_sec to 0, because that might push the
   2041        1.1       jtc 		** time below the minimum representable time.
   2042        1.1       jtc 		** Set tm_sec to 59 instead.
   2043        1.1       jtc 		** This assumes that the minimum representable time is
   2044        1.1       jtc 		** not in the same minute that a leap second was deleted from,
   2045        1.1       jtc 		** which is a safer assumption than using 58 would be.
   2046        1.1       jtc 		*/
   2047        1.1       jtc 		if (increment_overflow(&yourtm.tm_sec, 1 - SECSPERMIN))
   2048       1.91  christos 			goto out_of_range;
   2049        1.1       jtc 		saved_seconds = yourtm.tm_sec;
   2050        1.1       jtc 		yourtm.tm_sec = SECSPERMIN - 1;
   2051        1.1       jtc 	} else {
   2052        1.1       jtc 		saved_seconds = yourtm.tm_sec;
   2053        1.1       jtc 		yourtm.tm_sec = 0;
   2054        1.1       jtc 	}
   2055        1.1       jtc 	/*
   2056       1.45   mlelstv 	** Do a binary search (this works whatever time_t's type is).
   2057        1.1       jtc 	*/
   2058      1.109  christos 	lo = TIME_T_MIN;
   2059      1.109  christos 	hi = TIME_T_MAX;
   2060       1.61  christos #ifdef NO_ERROR_IN_DST_GAP
   2061       1.61  christos 	ilo = lo;
   2062       1.61  christos #endif
   2063        1.1       jtc 	for ( ; ; ) {
   2064       1.45   mlelstv 		t = lo / 2 + hi / 2;
   2065       1.45   mlelstv 		if (t < lo)
   2066       1.45   mlelstv 			t = lo;
   2067       1.45   mlelstv 		else if (t > hi)
   2068       1.45   mlelstv 			t = hi;
   2069       1.87  christos 		if (! funcp(sp, &t, offset, &mytm)) {
   2070       1.45   mlelstv 			/*
   2071       1.45   mlelstv 			** Assume that t is too extreme to be represented in
   2072       1.45   mlelstv 			** a struct tm; arrange things so that it is less
   2073       1.45   mlelstv 			** extreme on the next pass.
   2074       1.45   mlelstv 			*/
   2075       1.45   mlelstv 			dir = (t > 0) ? 1 : -1;
   2076       1.45   mlelstv 		} else	dir = tmcomp(&mytm, &yourtm);
   2077        1.1       jtc 		if (dir != 0) {
   2078       1.45   mlelstv 			if (t == lo) {
   2079      1.109  christos 				if (t == TIME_T_MAX)
   2080       1.91  christos 					goto out_of_range;
   2081       1.45   mlelstv 				++t;
   2082       1.45   mlelstv 				++lo;
   2083       1.45   mlelstv 			} else if (t == hi) {
   2084      1.109  christos 				if (t == TIME_T_MIN)
   2085       1.91  christos 					goto out_of_range;
   2086       1.45   mlelstv 				--t;
   2087       1.45   mlelstv 				--hi;
   2088       1.45   mlelstv 			}
   2089       1.59  christos #ifdef NO_ERROR_IN_DST_GAP
   2090       1.64  christos 			if (ilo != lo && lo - 1 == hi && yourtm.tm_isdst < 0 &&
   2091       1.64  christos 			    do_norm_secs) {
   2092       1.59  christos 				for (i = sp->typecnt - 1; i >= 0; --i) {
   2093       1.59  christos 					for (j = sp->typecnt - 1; j >= 0; --j) {
   2094       1.64  christos 						time_t off;
   2095       1.59  christos 						if (sp->ttis[j].tt_isdst ==
   2096       1.59  christos 						    sp->ttis[i].tt_isdst)
   2097       1.59  christos 							continue;
   2098       1.59  christos 						off = sp->ttis[j].tt_gmtoff -
   2099       1.59  christos 						    sp->ttis[i].tt_gmtoff;
   2100       1.64  christos 						yourtm.tm_sec += off < 0 ?
   2101       1.64  christos 						    -off : off;
   2102       1.64  christos 						goto again;
   2103       1.59  christos 					}
   2104       1.59  christos 				}
   2105       1.59  christos 			}
   2106       1.59  christos #endif
   2107       1.45   mlelstv 			if (lo > hi)
   2108       1.60  christos 				goto invalid;
   2109       1.45   mlelstv 			if (dir > 0)
   2110       1.45   mlelstv 				hi = t;
   2111       1.45   mlelstv 			else	lo = t;
   2112        1.1       jtc 			continue;
   2113        1.1       jtc 		}
   2114       1.87  christos #if defined TM_GMTOFF && ! UNINIT_TRAP
   2115       1.87  christos 		if (mytm.TM_GMTOFF != yourtm.TM_GMTOFF
   2116       1.87  christos 		    && (yourtm.TM_GMTOFF < 0
   2117       1.87  christos 			? (-SECSPERDAY <= yourtm.TM_GMTOFF
   2118       1.87  christos 			   && (mytm.TM_GMTOFF <=
   2119       1.87  christos 			       (/*CONSTCOND*/SMALLEST (INT_FAST32_MAX, LONG_MAX)
   2120       1.87  christos 				+ yourtm.TM_GMTOFF)))
   2121       1.87  christos 			: (yourtm.TM_GMTOFF <= SECSPERDAY
   2122       1.87  christos 			   && ((/*CONSTCOND*/BIGGEST (INT_FAST32_MIN, LONG_MIN)
   2123       1.87  christos 				+ yourtm.TM_GMTOFF)
   2124       1.87  christos 			       <= mytm.TM_GMTOFF)))) {
   2125      1.111  christos 		  /* MYTM matches YOURTM except with the wrong UT offset.
   2126       1.87  christos 		     YOURTM.TM_GMTOFF is plausible, so try it instead.
   2127       1.87  christos 		     It's OK if YOURTM.TM_GMTOFF contains uninitialized data,
   2128       1.87  christos 		     since the guess gets checked.  */
   2129       1.87  christos 		  time_t altt = t;
   2130       1.87  christos 		  int_fast32_t diff = (int_fast32_t)
   2131       1.87  christos 		      (mytm.TM_GMTOFF - yourtm.TM_GMTOFF);
   2132       1.87  christos 		  if (!increment_overflow_time(&altt, diff)) {
   2133       1.87  christos 		    struct tm alttm;
   2134       1.87  christos 		    if (! funcp(sp, &altt, offset, &alttm)
   2135       1.87  christos 			&& alttm.tm_isdst == mytm.tm_isdst
   2136       1.87  christos 			&& alttm.TM_GMTOFF == yourtm.TM_GMTOFF
   2137       1.87  christos 			&& tmcomp(&alttm, &yourtm)) {
   2138       1.87  christos 		      t = altt;
   2139       1.87  christos 		      mytm = alttm;
   2140       1.87  christos 		    }
   2141       1.87  christos 		  }
   2142       1.87  christos 		}
   2143       1.87  christos #endif
   2144        1.1       jtc 		if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
   2145        1.1       jtc 			break;
   2146        1.1       jtc 		/*
   2147        1.1       jtc 		** Right time, wrong type.
   2148        1.1       jtc 		** Hunt for right time, right type.
   2149        1.1       jtc 		** It's okay to guess wrong since the guess
   2150        1.1       jtc 		** gets checked.
   2151        1.1       jtc 		*/
   2152        1.1       jtc 		if (sp == NULL)
   2153       1.60  christos 			goto invalid;
   2154        1.5       jtc 		for (i = sp->typecnt - 1; i >= 0; --i) {
   2155        1.1       jtc 			if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
   2156        1.1       jtc 				continue;
   2157        1.5       jtc 			for (j = sp->typecnt - 1; j >= 0; --j) {
   2158        1.1       jtc 				if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
   2159        1.1       jtc 					continue;
   2160       1.66  christos 				newt = (time_t)(t + sp->ttis[j].tt_gmtoff -
   2161       1.66  christos 				    sp->ttis[i].tt_gmtoff);
   2162       1.87  christos 				if (! funcp(sp, &newt, offset, &mytm))
   2163       1.45   mlelstv 					continue;
   2164        1.1       jtc 				if (tmcomp(&mytm, &yourtm) != 0)
   2165        1.1       jtc 					continue;
   2166        1.1       jtc 				if (mytm.tm_isdst != yourtm.tm_isdst)
   2167        1.1       jtc 					continue;
   2168        1.1       jtc 				/*
   2169        1.1       jtc 				** We have a match.
   2170        1.1       jtc 				*/
   2171        1.1       jtc 				t = newt;
   2172        1.1       jtc 				goto label;
   2173        1.1       jtc 			}
   2174        1.1       jtc 		}
   2175       1.60  christos 		goto invalid;
   2176        1.1       jtc 	}
   2177        1.1       jtc label:
   2178        1.1       jtc 	newt = t + saved_seconds;
   2179        1.1       jtc 	if ((newt < t) != (saved_seconds < 0))
   2180       1.91  christos 		goto out_of_range;
   2181        1.1       jtc 	t = newt;
   2182       1.87  christos 	if (funcp(sp, &t, offset, tmp)) {
   2183       1.87  christos 		*okayp = true;
   2184       1.51  christos 		return t;
   2185       1.60  christos 	}
   2186       1.91  christos out_of_range:
   2187       1.60  christos 	errno = EOVERFLOW;
   2188       1.60  christos 	return WRONG;
   2189       1.60  christos invalid:
   2190       1.60  christos 	errno = EINVAL;
   2191       1.60  christos 	return WRONG;
   2192       1.13       jtc }
   2193       1.13       jtc 
   2194       1.13       jtc static time_t
   2195       1.87  christos time2(struct tm * const	tmp,
   2196       1.87  christos       struct tm *(*funcp)(struct state const *, time_t const *,
   2197       1.87  christos 			  int_fast32_t, struct tm *),
   2198       1.87  christos       struct state const *sp,
   2199       1.87  christos       const int_fast32_t offset,
   2200       1.87  christos       bool *okayp)
   2201       1.13       jtc {
   2202       1.13       jtc 	time_t	t;
   2203       1.13       jtc 
   2204       1.13       jtc 	/*
   2205       1.13       jtc 	** First try without normalization of seconds
   2206       1.13       jtc 	** (in case tm_sec contains a value associated with a leap second).
   2207       1.13       jtc 	** If that fails, try with normalization of seconds.
   2208       1.13       jtc 	*/
   2209       1.87  christos 	t = time2sub(tmp, funcp, sp, offset, okayp, false);
   2210       1.87  christos 	return *okayp ? t : time2sub(tmp, funcp, sp, offset, okayp, true);
   2211        1.1       jtc }
   2212        1.1       jtc 
   2213        1.1       jtc static time_t
   2214       1.87  christos time1(struct tm *const tmp,
   2215       1.87  christos       struct tm *(*funcp) (struct state const *, time_t const *,
   2216       1.87  christos 			   int_fast32_t, struct tm *),
   2217       1.87  christos       struct state const *sp,
   2218       1.87  christos       const int_fast32_t offset)
   2219       1.49  christos {
   2220       1.49  christos 	time_t			t;
   2221       1.49  christos 	int			samei, otheri;
   2222       1.49  christos 	int			sameind, otherind;
   2223       1.49  christos 	int			i;
   2224       1.49  christos 	int			nseen;
   2225       1.90  christos 	int			save_errno;
   2226       1.83  christos 	char				seen[TZ_MAX_TYPES];
   2227       1.83  christos 	unsigned char			types[TZ_MAX_TYPES];
   2228       1.87  christos 	bool				okay;
   2229        1.1       jtc 
   2230       1.58  christos 	if (tmp == NULL) {
   2231       1.58  christos 		errno = EINVAL;
   2232       1.58  christos 		return WRONG;
   2233       1.58  christos 	}
   2234        1.1       jtc 	if (tmp->tm_isdst > 1)
   2235        1.1       jtc 		tmp->tm_isdst = 1;
   2236       1.90  christos 	save_errno = errno;
   2237       1.87  christos 	t = time2(tmp, funcp, sp, offset, &okay);
   2238       1.90  christos 	if (okay) {
   2239       1.90  christos 		errno = save_errno;
   2240        1.1       jtc 		return t;
   2241       1.90  christos 	}
   2242        1.1       jtc 	if (tmp->tm_isdst < 0)
   2243       1.82  christos #ifdef PCTS
   2244       1.82  christos 		/*
   2245       1.82  christos 		** POSIX Conformance Test Suite code courtesy Grant Sullivan.
   2246       1.82  christos 		*/
   2247        1.1       jtc 		tmp->tm_isdst = 0;	/* reset to std and try again */
   2248       1.82  christos #else
   2249        1.1       jtc 		return t;
   2250        1.1       jtc #endif /* !defined PCTS */
   2251        1.1       jtc 	/*
   2252        1.1       jtc 	** We're supposed to assume that somebody took a time of one type
   2253        1.1       jtc 	** and did some math on it that yielded a "struct tm" that's bad.
   2254        1.1       jtc 	** We try to divine the type they started from and adjust to the
   2255        1.1       jtc 	** type they need.
   2256        1.1       jtc 	*/
   2257       1.60  christos 	if (sp == NULL) {
   2258       1.60  christos 		errno = EINVAL;
   2259        1.1       jtc 		return WRONG;
   2260       1.60  christos 	}
   2261       1.35    kleink 	for (i = 0; i < sp->typecnt; ++i)
   2262       1.87  christos 		seen[i] = false;
   2263       1.35    kleink 	nseen = 0;
   2264       1.35    kleink 	for (i = sp->timecnt - 1; i >= 0; --i)
   2265       1.35    kleink 		if (!seen[sp->types[i]]) {
   2266       1.87  christos 			seen[sp->types[i]] = true;
   2267       1.35    kleink 			types[nseen++] = sp->types[i];
   2268       1.35    kleink 		}
   2269       1.35    kleink 	for (sameind = 0; sameind < nseen; ++sameind) {
   2270       1.35    kleink 		samei = types[sameind];
   2271        1.1       jtc 		if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
   2272        1.1       jtc 			continue;
   2273       1.35    kleink 		for (otherind = 0; otherind < nseen; ++otherind) {
   2274       1.35    kleink 			otheri = types[otherind];
   2275        1.1       jtc 			if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
   2276        1.1       jtc 				continue;
   2277       1.21  christos 			tmp->tm_sec += (int)(sp->ttis[otheri].tt_gmtoff -
   2278       1.21  christos 					sp->ttis[samei].tt_gmtoff);
   2279        1.1       jtc 			tmp->tm_isdst = !tmp->tm_isdst;
   2280       1.87  christos 			t = time2(tmp, funcp, sp, offset, &okay);
   2281       1.90  christos 			if (okay) {
   2282       1.90  christos 				errno = save_errno;
   2283        1.1       jtc 				return t;
   2284       1.90  christos 			}
   2285       1.21  christos 			tmp->tm_sec -= (int)(sp->ttis[otheri].tt_gmtoff -
   2286       1.21  christos 					sp->ttis[samei].tt_gmtoff);
   2287        1.1       jtc 			tmp->tm_isdst = !tmp->tm_isdst;
   2288        1.1       jtc 		}
   2289        1.1       jtc 	}
   2290       1.60  christos 	errno = EOVERFLOW;
   2291        1.1       jtc 	return WRONG;
   2292        1.1       jtc }
   2293        1.1       jtc 
   2294       1.87  christos static time_t
   2295       1.87  christos mktime_tzname(timezone_t sp, struct tm *tmp, bool setname)
   2296       1.87  christos {
   2297       1.87  christos 	if (sp)
   2298       1.87  christos 		return time1(tmp, localsub, sp, setname);
   2299       1.87  christos 	else {
   2300       1.87  christos 		gmtcheck();
   2301       1.87  christos 		return time1(tmp, gmtsub, gmtptr, 0);
   2302       1.87  christos 	}
   2303       1.87  christos }
   2304       1.87  christos 
   2305       1.87  christos #if NETBSD_INSPIRED
   2306       1.87  christos 
   2307        1.1       jtc time_t
   2308       1.87  christos mktime_z(timezone_t sp, struct tm *const tmp)
   2309       1.49  christos {
   2310       1.87  christos 	return mktime_tzname(sp, tmp, false);
   2311       1.49  christos }
   2312       1.49  christos 
   2313       1.87  christos #endif
   2314       1.87  christos 
   2315       1.49  christos time_t
   2316       1.96  christos mktime(struct tm *tmp)
   2317        1.1       jtc {
   2318       1.87  christos 	time_t t;
   2319       1.19    kleink 
   2320       1.45   mlelstv 	rwlock_wrlock(&lcl_lock);
   2321       1.45   mlelstv 	tzset_unlocked();
   2322       1.87  christos 	t = mktime_tzname(lclptr, tmp, true);
   2323       1.45   mlelstv 	rwlock_unlock(&lcl_lock);
   2324       1.87  christos 	return t;
   2325        1.1       jtc }
   2326        1.1       jtc 
   2327        1.1       jtc #ifdef STD_INSPIRED
   2328        1.1       jtc 
   2329        1.1       jtc time_t
   2330       1.68  christos timelocal_z(const timezone_t sp, struct tm *const tmp)
   2331       1.49  christos {
   2332       1.49  christos 	if (tmp != NULL)
   2333       1.49  christos 		tmp->tm_isdst = -1;	/* in case it wasn't initialized */
   2334       1.49  christos 	return mktime_z(sp, tmp);
   2335       1.49  christos }
   2336       1.49  christos 
   2337       1.49  christos time_t
   2338       1.96  christos timelocal(struct tm *tmp)
   2339        1.1       jtc {
   2340       1.58  christos 	if (tmp != NULL)
   2341       1.58  christos 		tmp->tm_isdst = -1;	/* in case it wasn't initialized */
   2342        1.1       jtc 	return mktime(tmp);
   2343        1.1       jtc }
   2344        1.1       jtc 
   2345        1.1       jtc time_t
   2346       1.96  christos timegm(struct tm *tmp)
   2347        1.1       jtc {
   2348       1.51  christos 
   2349       1.87  christos 	return timeoff(tmp, 0);
   2350        1.1       jtc }
   2351        1.1       jtc 
   2352        1.1       jtc time_t
   2353       1.96  christos timeoff(struct tm *tmp, long offset)
   2354        1.1       jtc {
   2355       1.87  christos 	if (tmp)
   2356       1.58  christos 		tmp->tm_isdst = 0;
   2357       1.87  christos 	gmtcheck();
   2358       1.87  christos 	return time1(tmp, gmtsub, gmtptr, (int_fast32_t)offset);
   2359        1.1       jtc }
   2360        1.1       jtc 
   2361        1.1       jtc #endif /* defined STD_INSPIRED */
   2362        1.1       jtc 
   2363        1.1       jtc /*
   2364        1.1       jtc ** XXX--is the below the right way to conditionalize??
   2365        1.1       jtc */
   2366        1.1       jtc 
   2367        1.1       jtc #ifdef STD_INSPIRED
   2368        1.1       jtc 
   2369        1.1       jtc /*
   2370  1.111.2.1  pgoyette ** IEEE Std 1003.1 (POSIX) says that 536457599
   2371       1.14       jtc ** shall correspond to "Wed Dec 31 23:59:59 UTC 1986", which
   2372        1.1       jtc ** is not the case if we are accounting for leap seconds.
   2373        1.1       jtc ** So, we provide the following conversion routines for use
   2374        1.1       jtc ** when exchanging timestamps with POSIX conforming systems.
   2375        1.1       jtc */
   2376        1.1       jtc 
   2377       1.74  christos static int_fast64_t
   2378       1.87  christos leapcorr(const timezone_t sp, time_t t)
   2379        1.1       jtc {
   2380       1.87  christos 	struct lsinfo const * lp;
   2381       1.49  christos 	int		i;
   2382        1.1       jtc 
   2383        1.1       jtc 	i = sp->leapcnt;
   2384        1.1       jtc 	while (--i >= 0) {
   2385        1.1       jtc 		lp = &sp->lsis[i];
   2386       1.87  christos 		if (t >= lp->ls_trans)
   2387        1.1       jtc 			return lp->ls_corr;
   2388        1.1       jtc 	}
   2389        1.1       jtc 	return 0;
   2390        1.1       jtc }
   2391        1.1       jtc 
   2392      1.109  christos NETBSD_INSPIRED_EXTERN time_t
   2393       1.87  christos time2posix_z(timezone_t sp, time_t t)
   2394       1.49  christos {
   2395       1.87  christos 	return (time_t)(t - leapcorr(sp, t));
   2396       1.49  christos }
   2397       1.49  christos 
   2398       1.49  christos time_t
   2399       1.49  christos time2posix(time_t t)
   2400        1.1       jtc {
   2401       1.45   mlelstv 	rwlock_wrlock(&lcl_lock);
   2402       1.87  christos 	if (!lcl_is_set)
   2403       1.87  christos 		tzset_unlocked();
   2404       1.87  christos 	if (lclptr)
   2405       1.87  christos 		t = (time_t)(t - leapcorr(lclptr, t));
   2406       1.45   mlelstv 	rwlock_unlock(&lcl_lock);
   2407       1.87  christos 	return t;
   2408        1.1       jtc }
   2409        1.1       jtc 
   2410      1.109  christos NETBSD_INSPIRED_EXTERN time_t
   2411       1.87  christos posix2time_z(timezone_t sp, time_t t)
   2412        1.1       jtc {
   2413        1.1       jtc 	time_t	x;
   2414        1.1       jtc 	time_t	y;
   2415        1.1       jtc 
   2416        1.1       jtc 	/*
   2417        1.1       jtc 	** For a positive leap second hit, the result
   2418       1.45   mlelstv 	** is not unique. For a negative leap second
   2419        1.1       jtc 	** hit, the corresponding time doesn't exist,
   2420        1.1       jtc 	** so we return an adjacent second.
   2421        1.1       jtc 	*/
   2422       1.87  christos 	x = (time_t)(t + leapcorr(sp, t));
   2423       1.87  christos 	y = (time_t)(x - leapcorr(sp, x));
   2424        1.1       jtc 	if (y < t) {
   2425        1.1       jtc 		do {
   2426        1.1       jtc 			x++;
   2427       1.87  christos 			y = (time_t)(x - leapcorr(sp, x));
   2428        1.1       jtc 		} while (y < t);
   2429       1.87  christos 		x -= y != t;
   2430        1.1       jtc 	} else if (y > t) {
   2431        1.1       jtc 		do {
   2432        1.1       jtc 			--x;
   2433       1.87  christos 			y = (time_t)(x - leapcorr(sp, x));
   2434        1.1       jtc 		} while (y > t);
   2435       1.87  christos 		x += y != t;
   2436        1.1       jtc 	}
   2437       1.49  christos 	return x;
   2438       1.49  christos }
   2439       1.49  christos 
   2440       1.49  christos time_t
   2441       1.49  christos posix2time(time_t t)
   2442       1.49  christos {
   2443       1.49  christos 	rwlock_wrlock(&lcl_lock);
   2444       1.87  christos 	if (!lcl_is_set)
   2445       1.87  christos 		tzset_unlocked();
   2446       1.87  christos 	if (lclptr)
   2447       1.87  christos 		t = posix2time_z(lclptr, t);
   2448       1.45   mlelstv 	rwlock_unlock(&lcl_lock);
   2449       1.87  christos 	return t;
   2450        1.1       jtc }
   2451        1.1       jtc 
   2452        1.1       jtc #endif /* defined STD_INSPIRED */
   2453