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