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