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