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