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