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