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