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