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