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