:pserver:cvsanon@mok.lvcm.com:/CVS/ReactOS reactos
[reactos.git] / lib / crtdll / time / ctime.c
1
2 // fix djdir
3
4 /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
5 /* This file has been modified by DJ Delorie.  These modifications are
6 ** Copyright (C) 1995 DJ Delorie, 24 Kirsten Ave, Rochester NH,
7 ** 03867-2954, USA.
8 */
9
10 /*
11  * Copyright (c) 1987, 1989 Regents of the University of California.
12  * All rights reserved.
13  *
14  * This code is derived from software contributed to Berkeley by
15  * Arthur David Olson of the National Cancer Institute.
16  *
17  * Redistribution and use in source and binary forms are permitted provided
18  * that: (1) source distributions retain this entire copyright notice and
19  * comment, and (2) distributions including binaries display the following
20  * acknowledgement:  ``This product includes software developed by the
21  * University of California, Berkeley and its contributors'' in the
22  * documentation or other materials provided with the distribution and in
23  * all advertising materials mentioning features or use of this software.
24  * Neither the name of the University nor the names of its contributors may
25  * be used to endorse or promote products derived from this software without
26  * specific prior written permission.
27  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
28  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
29  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
30  */
31
32 #if defined(LIBC_SCCS) && !defined(lint)
33 static char sccsid[] = "@(#)ctime.c     5.23 (Berkeley) 6/22/90";
34 #endif /* LIBC_SCCS and not lint */
35
36 /*
37 ** Leap second handling from Bradley White (bww@k.gp.cs.cmu.edu).
38 ** POSIX-style TZ environment variable handling from Guy Harris
39 ** (guy@auspex.com).
40 */
41
42
43
44
45 #include <crtdll/fcntl.h>
46 #include <crtdll/time.h>
47 #include <crtdll/string.h>
48 #include <crtdll/ctype.h>
49 #include <crtdll/stdio.h>
50 #include <crtdll/stdlib.h>
51
52 #include <windows.h>
53 #include "tzfile.h"
54
55 #include <crtdll/io.h>
56
57 #include "posixrul.h"
58
59 #define P(s)            s
60 #define alloc_size_t    size_t
61 #define qsort_size_t    size_t
62 #define fread_size_t    size_t
63 #define fwrite_size_t   size_t
64
65 #define ACCESS_MODE     O_RDONLY|O_BINARY
66 #define OPEN_MODE       O_RDONLY|O_BINARY
67
68 /*
69 ** Someone might make incorrect use of a time zone abbreviation:
70 **      1.      They might reference tzname[0] before calling tzset (explicitly
71 **              or implicitly).
72 **      2.      They might reference tzname[1] before calling tzset (explicitly
73 **              or implicitly).
74 **      3.      They might reference tzname[1] after setting to a time zone
75 **              in which Daylight Saving Time is never observed.
76 **      4.      They might reference tzname[0] after setting to a time zone
77 **              in which Standard Time is never observed.
78 **      5.      They might reference tm.TM_ZONE after calling offtime.
79 ** What's best to do in the above cases is open to debate;
80 ** for now, we just set things up so that in any of the five cases
81 ** WILDABBR is used.  Another possibility:  initialize tzname[0] to the
82 ** string "tzname[0] used before set", and similarly for the other cases.
83 ** And another:  initialize tzname[0] to "ERA", with an explanation in the
84 ** manual page of what this "time zone abbreviation" means (doing this so
85 ** that tzname[0] has the "normal" length of three characters).
86 */
87 int _daylight_dll;
88 int _timezone_dll;
89
90 static char WILDABBR[] = "   ";
91
92 #ifndef TRUE
93 #define TRUE            1
94 #define FALSE           0
95 #endif /* !defined TRUE */
96
97 static const char GMT[] = "GMT";
98
99 struct ttinfo {         /* time type information */
100   long tt_gmtoff;       /* GMT offset in seconds */
101   int tt_isdst;         /* used to set tm_isdst */
102   int tt_abbrind;       /* abbreviation list index */
103   int tt_ttisstd;       /* TRUE if transition is std time */
104 };
105
106 struct lsinfo {         /* leap second information */
107   time_t ls_trans;      /* transition time */
108   long ls_corr;         /* correction to apply */
109 };
110
111 struct state {
112   int leapcnt;
113   int timecnt;
114   int typecnt;
115   int charcnt;
116   time_t ats[TZ_MAX_TIMES];
117   unsigned char types[TZ_MAX_TIMES];
118   struct ttinfo ttis[TZ_MAX_TYPES];
119   char chars[(TZ_MAX_CHARS + 1 > sizeof GMT) ? TZ_MAX_CHARS + 1 : sizeof GMT];
120   struct lsinfo lsis[TZ_MAX_LEAPS];
121 };
122
123 struct rule {
124   int r_type;           /* type of rule--see below */
125   int r_day;            /* day number of rule */
126   int r_week;           /* week number of rule */
127   int r_mon;            /* month number of rule */
128   long r_time;          /* transition time of rule */
129 };
130
131 #define JULIAN_DAY              0       /* Jn - Julian day */
132 #define DAY_OF_YEAR             1       /* n - day of year */
133 #define MONTH_NTH_DAY_OF_WEEK   2       /* Mm.n.d - month, week, day of week */
134
135 /*
136 ** Prototypes for static functions.
137 */
138
139 static long             detzcode P((const char * codep));
140 static const char *     getzname P((const char * strp));
141 static const char *     getnum P((const char * strp, int * nump, int min,
142                                 int max));
143 static const char *     getsecs P((const char * strp, long * secsp));
144 static const char *     getoffset P((const char * strp, long * offsetp));
145 static const char *     getrule P((const char * strp, struct rule * rulep));
146 static void             gmtload P((struct state * sp));
147 static void             gmtsub P((const time_t * timep, long offset,
148                                 struct tm * tmp));
149 static void             localsub P((const time_t * timep, long offset,
150                                 struct tm * tmp));
151 static void             normalize P((int * tensptr, int * unitsptr, int base));
152 static void             settzname P((void));
153 static time_t           time1 P((struct tm * tmp, void (* funcp)(const time_t * const, const long, struct tm * const),
154                                 long offset));
155 static time_t           time2 P((struct tm *tmp, void (* funcp)(const time_t * const, const long, struct tm * const),
156                                 long offset, int * okayp));
157 static void             timesub P((const time_t * timep, long offset,
158                                 const struct state * sp, struct tm * tmp));
159 static int              tmcomp P((const struct tm * atmp,
160                                 const struct tm * btmp));
161 static time_t           transtime P((time_t janfirst, int year,
162                                 const struct rule * rulep, long offset));
163 static int              tzload P((const char * name, struct state * sp));
164 static int              tzparse P((const char * name, struct state * sp,
165                                 int lastditch));
166 static void             tzsetwall(void);
167
168 #ifdef ALL_STATE
169 static struct state *lclptr;
170 static struct state *gmtptr;
171 #endif /* defined ALL_STATE */
172
173 #ifndef ALL_STATE
174 static struct state lclmem;
175 static struct state gmtmem;
176 #define lclptr (&lclmem)
177 #define gmtptr (&gmtmem)
178 #endif /* State Farm */
179
180 static int lcl_is_set;
181 static int gmt_is_set;
182
183 char * _tzname[2] = {
184   WILDABBR,
185   WILDABBR
186 };
187
188 static long
189 detzcode(const char * const codep)
190 {
191   long result;
192   int i;
193
194   result = 0;
195   for (i = 0; i < 4; ++i)
196     result = (result << 8) | (codep[i] & 0xff);
197   return result;
198 }
199
200 static void
201 settzname(void)
202 {
203   const struct state * const sp = lclptr;
204   int i;
205
206   _tzname[0] = WILDABBR;
207   _tzname[1] = WILDABBR;
208 #ifdef ALL_STATE
209   if (sp == NULL)
210   {
211     _tzname[0] = _tzname[1] = GMT;
212     return;
213   }
214 #endif /* defined ALL_STATE */
215   for (i = 0; i < sp->typecnt; ++i)
216   {
217     register const struct ttinfo * const ttisp = &sp->ttis[i];
218
219     _tzname[ttisp->tt_isdst] =
220       (char *)&sp->chars[ttisp->tt_abbrind];
221 #if 0
222     if (ttisp->tt_isdst)
223       _daylight = 1;
224     if (i == 0 || !ttisp->tt_isdst)
225       _timezone_dll = -(ttisp->tt_gmtoff);
226     if (i == 0 || ttisp->tt_isdst)
227       _altzone = -(ttisp->tt_gmtoff);
228 #endif
229   }
230   /*
231    ** And to get the latest zone names into tzname. . .
232    */
233   for (i = 0; i < sp->timecnt; ++i)
234   {
235     const struct ttinfo * const ttisp = &sp->ttis[sp->types[i]];
236
237     _tzname[ttisp->tt_isdst] = (char *)&sp->chars[ttisp->tt_abbrind];
238   }
239 }
240
241 static char *
242 tzdir(void)
243 {
244   static char dir[80]={0}, *cp;
245   if (dir[0] == 0)
246   {
247     if ((cp = getenv("TZDIR")))
248     {
249       strcpy(dir, cp);
250     }
251     else if ((cp = getenv("DJDIR")))
252     {
253       strcpy(dir, cp);
254       strcat(dir, "/zoneinfo");
255     }
256     else
257       strcpy(dir, "./");
258   }
259   return dir;
260 }
261
262 static int
263 tzload(const char *name, struct state * const sp)
264 {
265   const char * p;
266   int i;
267   int fid;
268   char fullname[FILENAME_MAX + 1];
269   const struct tzhead * tzhp;
270   char buf[sizeof *sp + sizeof *tzhp];
271   int ttisstdcnt;
272
273   if (name == NULL && (name = TZDEFAULT) == NULL)
274     return -1;
275
276   if (name[0] == ':')
277     ++name;
278   if (name[0] != '/')
279   {
280     if ((p = tzdir()) == NULL)
281       return -1;
282     if ((strlen(p) + strlen(name) + 1) >= sizeof fullname)
283       return -1;
284     strcpy(fullname, p);
285     strcat(fullname, "/");
286     strcat(fullname, name);
287     name = fullname;
288   }
289
290   if ((fid = open(name, OPEN_MODE)) == -1)
291   {
292     const char *base = strrchr(name, '/');
293     if (base)
294       base++;
295     else
296       base = name;
297     if (strcmp(base, "posixrules"))
298       return -1;
299
300     /* We've got a built-in copy of posixrules just in case */
301     memcpy(buf, _posixrules_data, sizeof(_posixrules_data));
302     i = sizeof(_posixrules_data);
303   }
304   else
305   {
306     i = read(fid, buf, sizeof buf);
307     if (close(fid) != 0 || i < sizeof *tzhp)
308       return -1;
309   }
310
311   tzhp = (struct tzhead *) buf;
312   ttisstdcnt = (int) detzcode(tzhp->tzh_ttisstdcnt);
313   sp->leapcnt = (int) detzcode(tzhp->tzh_leapcnt);
314   sp->timecnt = (int) detzcode(tzhp->tzh_timecnt);
315   sp->typecnt = (int) detzcode(tzhp->tzh_typecnt);
316   sp->charcnt = (int) detzcode(tzhp->tzh_charcnt);
317   if (sp->leapcnt < 0 || sp->leapcnt > TZ_MAX_LEAPS ||
318       sp->typecnt <= 0 || sp->typecnt > TZ_MAX_TYPES ||
319       sp->timecnt < 0 || sp->timecnt > TZ_MAX_TIMES ||
320       sp->charcnt < 0 || sp->charcnt > TZ_MAX_CHARS ||
321       (ttisstdcnt != sp->typecnt && ttisstdcnt != 0))
322     return -1;
323   if (i < sizeof *tzhp +
324       sp->timecnt * (4 + sizeof (char)) +
325       sp->typecnt * (4 + 2 * sizeof (char)) +
326       sp->charcnt * sizeof (char) +
327       sp->leapcnt * 2 * 4 +
328       ttisstdcnt * sizeof (char))
329     return -1;
330   p = buf + sizeof *tzhp;
331   for (i = 0; i < sp->timecnt; ++i)
332   {
333     sp->ats[i] = detzcode(p);
334     p += 4;
335   }
336   for (i = 0; i < sp->timecnt; ++i)
337   {
338     sp->types[i] = (unsigned char) *p++;
339     if (sp->types[i] >= sp->typecnt)
340       return -1;
341   }
342   for (i = 0; i < sp->typecnt; ++i)
343   {
344     struct ttinfo * ttisp;
345
346     ttisp = &sp->ttis[i];
347     ttisp->tt_gmtoff = detzcode(p);
348     p += 4;
349     ttisp->tt_isdst = (unsigned char) *p++;
350     if (ttisp->tt_isdst != 0 && ttisp->tt_isdst != 1)
351       return -1;
352     ttisp->tt_abbrind = (unsigned char) *p++;
353     if (ttisp->tt_abbrind < 0 ||
354         ttisp->tt_abbrind > sp->charcnt)
355       return -1;
356   }
357   for (i = 0; i < sp->charcnt; ++i)
358     sp->chars[i] = *p++;
359   sp->chars[i] = '\0';          /* ensure '\0' at end */
360   for (i = 0; i < sp->leapcnt; ++i)
361   {
362     struct lsinfo * lsisp;
363
364     lsisp = &sp->lsis[i];
365     lsisp->ls_trans = detzcode(p);
366     p += 4;
367     lsisp->ls_corr = detzcode(p);
368     p += 4;
369   }
370   for (i = 0; i < sp->typecnt; ++i)
371   {
372     struct ttinfo * ttisp;
373
374     ttisp = &sp->ttis[i];
375     if (ttisstdcnt == 0)
376       ttisp->tt_ttisstd = FALSE;
377     else
378     {
379       ttisp->tt_ttisstd = *p++;
380       if (ttisp->tt_ttisstd != TRUE &&
381           ttisp->tt_ttisstd != FALSE)
382         return -1;
383     }
384   }
385   return 0;
386 }
387
388 static const int mon_lengths[2][MONSPERYEAR] = {
389 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
390 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
391 };
392
393 static const int year_lengths[2] = {
394 DAYSPERNYEAR, DAYSPERLYEAR
395 };
396
397 /*
398 ** Given a pointer into a time zone string, scan until a character that is not
399 ** a valid character in a zone name is found.  Return a pointer to that
400 ** character.
401 */
402
403 static const char *
404 getzname(const char *strp)
405 {
406   char c;
407
408   while ((c = *strp) != '\0' && !isdigit(c) && c != ',' && c != '-' &&
409          c != '+')
410     ++strp;
411   return strp;
412 }
413
414 /*
415 ** Given a pointer into a time zone string, extract a number from that string.
416 ** Check that the number is within a specified range; if it is not, return
417 ** NULL.
418 ** Otherwise, return a pointer to the first character not part of the number.
419 */
420
421 static const char *
422 getnum(const char *strp, int * const nump, const int min, const int max)
423 {
424   char c;
425   int num;
426
427   if (strp == NULL || !isdigit(*strp))
428     return NULL;
429   num = 0;
430   while ((c = *strp) != '\0' && isdigit(c))
431   {
432     num = num * 10 + (c - '0');
433     if (num > max)
434       return NULL;
435     ++strp;
436   }
437   if (num < min)
438     return NULL;
439   *nump = num;
440   return strp;
441 }
442
443 /*
444 ** Given a pointer into a time zone string, extract a number of seconds,
445 ** in hh[:mm[:ss]] form, from the string.
446 ** If any error occurs, return NULL.
447 ** Otherwise, return a pointer to the first character not part of the number
448 ** of seconds.
449 */
450
451 static const char *
452 getsecs(const char *strp, long * const secsp)
453 {
454   int num;
455
456   strp = getnum(strp, &num, 0, HOURSPERDAY);
457   if (strp == NULL)
458     return NULL;
459   *secsp = num * SECSPERHOUR;
460   if (*strp == ':')
461   {
462     ++strp;
463     strp = getnum(strp, &num, 0, MINSPERHOUR - 1);
464     if (strp == NULL)
465       return NULL;
466     *secsp += num * SECSPERMIN;
467     if (*strp == ':')
468     {
469       ++strp;
470       strp = getnum(strp, &num, 0, SECSPERMIN - 1);
471       if (strp == NULL)
472         return NULL;
473       *secsp += num;
474     }
475   }
476   return strp;
477 }
478
479 /*
480 ** Given a pointer into a time zone string, extract an offset, in
481 ** [+-]hh[:mm[:ss]] form, from the string.
482 ** If any error occurs, return NULL.
483 ** Otherwise, return a pointer to the first character not part of the time.
484 */
485
486 static const char *
487 getoffset(const char *strp, long * const offsetp)
488 {
489   int neg;
490
491   if (*strp == '-')
492   {
493     neg = 1;
494     ++strp;
495   }
496   else if (isdigit(*strp) || *strp++ == '+')
497     neg = 0;
498   else
499     return NULL; /* illegal offset */
500   strp = getsecs(strp, offsetp);
501   if (strp == NULL)
502     return NULL; /* illegal time */
503   if (neg)
504     *offsetp = -*offsetp;
505   return strp;
506 }
507
508 /*
509 ** Given a pointer into a time zone string, extract a rule in the form
510 ** date[/time].  See POSIX section 8 for the format of "date" and "time".
511 ** If a valid rule is not found, return NULL.
512 ** Otherwise, return a pointer to the first character not part of the rule.
513 */
514
515 static const char *
516 getrule(const char *strp, struct rule * const rulep)
517 {
518   if (*strp == 'J')
519   {
520     /*
521      ** Julian day.
522      */
523     rulep->r_type = JULIAN_DAY;
524     ++strp;
525     strp = getnum(strp, &rulep->r_day, 1, DAYSPERNYEAR);
526   }
527   else if (*strp == 'M')
528   {
529     /*
530      ** Month, week, day.
531      */
532     rulep->r_type = MONTH_NTH_DAY_OF_WEEK;
533     ++strp;
534     strp = getnum(strp, &rulep->r_mon, 1, MONSPERYEAR);
535     if (strp == NULL)
536       return NULL;
537     if (*strp++ != '.')
538       return NULL;
539     strp = getnum(strp, &rulep->r_week, 1, 5);
540     if (strp == NULL)
541       return NULL;
542     if (*strp++ != '.')
543       return NULL;
544     strp = getnum(strp, &rulep->r_day, 0, DAYSPERWEEK - 1);
545   }
546   else if (isdigit(*strp))
547   {
548     /*
549      ** Day of year.
550      */
551     rulep->r_type = DAY_OF_YEAR;
552     strp = getnum(strp, &rulep->r_day, 0, DAYSPERLYEAR - 1);
553   }
554   else
555     return NULL;                /* invalid format */
556   if (strp == NULL)
557     return NULL;
558   if (*strp == '/')
559   {
560     /*
561      ** Time specified.
562      */
563     ++strp;
564     strp = getsecs(strp, &rulep->r_time);
565   }
566   else
567     rulep->r_time = 2 * SECSPERHOUR; /* default = 2:00:00 */
568   return strp;
569 }
570
571 /*
572 ** Given the Epoch-relative time of January 1, 00:00:00 GMT, in a year, the
573 ** year, a rule, and the offset from GMT at the time that rule takes effect,
574 ** calculate the Epoch-relative time that rule takes effect.
575 */
576
577 static time_t
578 transtime(const time_t janfirst, const int year, const struct rule * const rulep, const long offset)
579 {
580   int leapyear;
581   time_t value=0;
582   int i;
583   int d, m1, yy0, yy1, yy2, dow;
584
585   leapyear = isleap(year);
586   switch (rulep->r_type)
587   {
588
589   case JULIAN_DAY:
590     /*
591      ** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap
592      ** years.
593      ** In non-leap years, or if the day number is 59 or less, just
594      ** add SECSPERDAY times the day number-1 to the time of
595      ** January 1, midnight, to get the day.
596      */
597     value = janfirst + (rulep->r_day - 1) * SECSPERDAY;
598     if (leapyear && rulep->r_day >= 60)
599       value += SECSPERDAY;
600     break;
601
602   case DAY_OF_YEAR:
603     /*
604      ** n - day of year.
605      ** Just add SECSPERDAY times the day number to the time of
606      ** January 1, midnight, to get the day.
607      */
608     value = janfirst + rulep->r_day * SECSPERDAY;
609     break;
610
611   case MONTH_NTH_DAY_OF_WEEK:
612     /*
613      ** Mm.n.d - nth "dth day" of month m.
614      */
615     value = janfirst;
616     for (i = 0; i < rulep->r_mon - 1; ++i)
617       value += mon_lengths[leapyear][i] * SECSPERDAY;
618
619     /*
620      ** Use Zeller's Congruence to get day-of-week of first day of
621      ** month.
622      */
623     m1 = (rulep->r_mon + 9) % 12 + 1;
624     yy0 = (rulep->r_mon <= 2) ? (year - 1) : year;
625     yy1 = yy0 / 100;
626     yy2 = yy0 % 100;
627     dow = ((26 * m1 - 2) / 10 +
628            1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
629     if (dow < 0)
630       dow += DAYSPERWEEK;
631
632     /*
633      ** "dow" is the day-of-week of the first day of the month.  Get
634      ** the day-of-month (zero-origin) of the first "dow" day of the
635      ** month.
636      */
637     d = rulep->r_day - dow;
638     if (d < 0)
639       d += DAYSPERWEEK;
640     for (i = 1; i < rulep->r_week; ++i)
641     {
642       if (d + DAYSPERWEEK >=
643           mon_lengths[leapyear][rulep->r_mon - 1])
644         break;
645       d += DAYSPERWEEK;
646     }
647
648     /*
649      ** "d" is the day-of-month (zero-origin) of the day we want.
650      */
651     value += d * SECSPERDAY;
652     break;
653   }
654
655   /*
656    ** "value" is the Epoch-relative time of 00:00:00 GMT on the day in
657    ** question.  To get the Epoch-relative time of the specified local
658    ** time on that day, add the transition time and the current offset
659    ** from GMT.
660    */
661   return value + rulep->r_time + offset;
662 }
663
664 /*
665 ** Given a POSIX section 8-style TZ string, fill in the rule tables as
666 ** appropriate.
667 */
668
669 static int
670 tzparse(const char *name, struct state * const sp, const int lastditch)
671 {
672   const char * stdname;
673   const char * dstname=0;
674   int stdlen;
675   int dstlen;
676   long stdoffset;
677   long dstoffset;
678   time_t * atp;
679   unsigned char * typep;
680   char * cp;
681   int load_result;
682
683   stdname = name;
684   if (lastditch)
685   {
686     stdlen = strlen(name);      /* length of standard zone name */
687     name += stdlen;
688     if (stdlen >= sizeof sp->chars)
689       stdlen = (sizeof sp->chars) - 1;
690   }
691   else
692   {
693     name = getzname(name);
694     stdlen = name - stdname;
695     if (stdlen < 3)
696       return -1;
697   }
698   if (*name == '\0')
699     return -1;
700   else
701   {
702     name = getoffset(name, &stdoffset);
703     if (name == NULL)
704       return -1;
705   }
706   load_result = tzload(TZDEFRULES, sp);
707   if (load_result != 0)
708     sp->leapcnt = 0;            /* so, we're off a little */
709   if (*name != '\0')
710   {
711     dstname = name;
712     name = getzname(name);
713     dstlen = name - dstname;    /* length of DST zone name */
714     if (dstlen < 3)
715       return -1;
716     if (*name != '\0' && *name != ',' && *name != ';')
717     {
718       name = getoffset(name, &dstoffset);
719       if (name == NULL)
720         return -1;
721     }
722     else
723       dstoffset = stdoffset - SECSPERHOUR;
724     if (*name == ',' || *name == ';')
725     {
726       struct rule start;
727       struct rule end;
728       int year;
729       time_t janfirst;
730       time_t starttime;
731       time_t endtime;
732
733       ++name;
734       if ((name = getrule(name, &start)) == NULL)
735         return -1;
736       if (*name++ != ',')
737         return -1;
738       if ((name = getrule(name, &end)) == NULL)
739         return -1;
740       if (*name != '\0')
741         return -1;
742       sp->typecnt = 2;          /* standard time and DST */
743       /*
744        ** Two transitions per year, from EPOCH_YEAR to 2037.
745        */
746       sp->timecnt = 2 * (2037 - EPOCH_YEAR + 1);
747       if (sp->timecnt > TZ_MAX_TIMES)
748         return -1;
749       sp->ttis[0].tt_gmtoff = -dstoffset;
750       sp->ttis[0].tt_isdst = 1;
751       sp->ttis[0].tt_abbrind = stdlen + 1;
752       sp->ttis[1].tt_gmtoff = -stdoffset;
753       sp->ttis[1].tt_isdst = 0;
754       sp->ttis[1].tt_abbrind = 0;
755       atp = sp->ats;
756       typep = sp->types;
757       janfirst = 0;
758       for (year = EPOCH_YEAR; year <= 2037; ++year)
759       {
760         starttime = transtime(janfirst, year, &start,
761                               stdoffset);
762         endtime = transtime(janfirst, year, &end,
763                             dstoffset);
764         if (starttime > endtime)
765         {
766           *atp++ = endtime;
767           *typep++ = 1;         /* DST ends */
768           *atp++ = starttime;
769           *typep++ = 0;         /* DST begins */
770         }
771         else
772         {
773           *atp++ = starttime;
774           *typep++ = 0;         /* DST begins */
775           *atp++ = endtime;
776           *typep++ = 1;         /* DST ends */
777         }
778         janfirst +=
779           year_lengths[isleap(year)] * SECSPERDAY;
780       }
781     }
782     else
783     {
784       int sawstd;
785       int sawdst;
786       long stdfix;
787       long dstfix;
788       long oldfix;
789       int isdst;
790       int i;
791
792       if (*name != '\0')
793         return -1;
794       if (load_result != 0)
795         return -1;
796       /*
797        ** Compute the difference between the real and
798        ** prototype standard and summer time offsets
799        ** from GMT, and put the real standard and summer
800        ** time offsets into the rules in place of the
801        ** prototype offsets.
802        */
803       sawstd = FALSE;
804       sawdst = FALSE;
805       stdfix = 0;
806       dstfix = 0;
807       for (i = 0; i < sp->typecnt; ++i)
808       {
809         if (sp->ttis[i].tt_isdst)
810         {
811           oldfix = dstfix;
812           dstfix =
813             sp->ttis[i].tt_gmtoff + dstoffset;
814           if (sawdst && (oldfix != dstfix))
815             return -1;
816           sp->ttis[i].tt_gmtoff = -dstoffset;
817           sp->ttis[i].tt_abbrind = stdlen + 1;
818           sawdst = TRUE;
819         }
820         else
821         {
822           oldfix = stdfix;
823           stdfix =
824             sp->ttis[i].tt_gmtoff + stdoffset;
825           if (sawstd && (oldfix != stdfix))
826             return -1;
827           sp->ttis[i].tt_gmtoff = -stdoffset;
828           sp->ttis[i].tt_abbrind = 0;
829           sawstd = TRUE;
830         }
831       }
832       /*
833        ** Make sure we have both standard and summer time.
834        */
835       if (!sawdst || !sawstd)
836         return -1;
837       /*
838        ** Now correct the transition times by shifting
839        ** them by the difference between the real and
840        ** prototype offsets.  Note that this difference
841        ** can be different in standard and summer time;
842        ** the prototype probably has a 1-hour difference
843        ** between standard and summer time, but a different
844        ** difference can be specified in TZ.
845        */
846       isdst = FALSE; /* we start in standard time */
847       for (i = 0; i < sp->timecnt; ++i)
848       {
849         const struct ttinfo * ttisp;
850
851         /*
852          ** If summer time is in effect, and the
853          ** transition time was not specified as
854          ** standard time, add the summer time
855          ** offset to the transition time;
856          ** otherwise, add the standard time offset
857          ** to the transition time.
858          */
859         ttisp = &sp->ttis[sp->types[i]];
860         sp->ats[i] +=
861           (isdst && !ttisp->tt_ttisstd) ?
862             dstfix : stdfix;
863         isdst = ttisp->tt_isdst;
864       }
865     }
866   }
867   else
868   {
869     dstlen = 0;
870     sp->typecnt = 1;            /* only standard time */
871     sp->timecnt = 0;
872     sp->ttis[0].tt_gmtoff = -stdoffset;
873     sp->ttis[0].tt_isdst = 0;
874     sp->ttis[0].tt_abbrind = 0;
875   }
876   sp->charcnt = stdlen + 1;
877   if (dstlen != 0)
878     sp->charcnt += dstlen + 1;
879   if (sp->charcnt > sizeof sp->chars)
880     return -1;
881   cp = sp->chars;
882   (void) strncpy(cp, stdname, stdlen);
883   cp += stdlen;
884   *cp++ = '\0';
885   if (dstlen != 0)
886   {
887     (void) strncpy(cp, dstname, dstlen);
888     *(cp + dstlen) = '\0';
889   }
890   return 0;
891 }
892
893 static void
894 gmtload(struct state * const sp)
895 {
896   if (tzload(GMT, sp) != 0)
897     (void) tzparse(GMT, sp, TRUE);
898 }
899
900 void
901 _tzset(void)
902 {
903   const char * name;
904
905   name = getenv("TZ");
906   if (name == NULL)
907   {
908     tzsetwall();
909     return;
910   }
911   lcl_is_set = TRUE;
912 #ifdef ALL_STATE
913   if (lclptr == NULL)
914   {
915     lclptr = (struct state *) malloc(sizeof *lclptr);
916     if (lclptr == NULL)
917     {
918       settzname();              /* all we can do */
919       return;
920     }
921   }
922 #endif /* defined ALL_STATE */
923   if (*name == '\0')
924   {
925     /*
926      ** User wants it fast rather than right.
927      */
928     lclptr->leapcnt = 0;        /* so, we're off a little */
929     lclptr->timecnt = 0;
930     lclptr->ttis[0].tt_gmtoff = 0;
931     lclptr->ttis[0].tt_abbrind = 0;
932     (void) strcpy(lclptr->chars, GMT);
933   }
934   else if (tzload(name, lclptr) != 0)
935     if (name[0] == ':' || tzparse(name, lclptr, FALSE) != 0)
936       gmtload(lclptr);
937   settzname();
938 }
939
940 void
941 tzsetwall(void)
942 {
943   lcl_is_set = TRUE;
944 #ifdef ALL_STATE
945   if (lclptr == NULL)
946   {
947     lclptr = (struct state *) malloc(sizeof *lclptr);
948     if (lclptr == NULL)
949     {
950       settzname();              /* all we can do */
951       return;
952     }
953   }
954 #endif /* defined ALL_STATE */
955   if (tzload((char *) NULL, lclptr) != 0)
956     gmtload(lclptr);
957   settzname();
958 }
959
960 /*
961 ** The easy way to behave "as if no library function calls" localtime
962 ** is to not call it--so we drop its guts into "localsub", which can be
963 ** freely called.  (And no, the PANS doesn't require the above behavior--
964 ** but it *is* desirable.)
965 **
966 ** The unused offset argument is for the benefit of mktime variants.
967 */
968
969 /*ARGSUSED*/
970 static void
971 localsub(const time_t * const timep, const long offset, struct tm * const tmp)
972 {
973   const struct state * sp;
974   const struct ttinfo * ttisp;
975   int i;
976   const time_t t = *timep;
977
978   if (!lcl_is_set)
979     _tzset();
980   sp = lclptr;
981 #ifdef ALL_STATE
982   if (sp == NULL)
983   {
984     gmtsub(timep, offset, tmp);
985     return;
986   }
987 #endif /* defined ALL_STATE */
988   if (sp->timecnt == 0 || t < sp->ats[0])
989   {
990     i = 0;
991     while (sp->ttis[i].tt_isdst)
992       if (++i >= sp->typecnt)
993       {
994         i = 0;
995         break;
996       }
997   }
998   else
999   {
1000     for (i = 1; i < sp->timecnt; ++i)
1001       if (t < sp->ats[i])
1002         break;
1003     i = sp->types[i - 1];
1004   }
1005   ttisp = &sp->ttis[i];
1006   /*
1007    ** To get (wrong) behavior that's compatible with System V Release 2.0
1008    ** you'd replace the statement below with
1009    ** t += ttisp->tt_gmtoff;
1010    ** timesub(&t, 0L, sp, tmp);
1011    */
1012   timesub(&t, ttisp->tt_gmtoff, sp, tmp);
1013   tmp->tm_isdst = ttisp->tt_isdst;
1014   _tzname[tmp->tm_isdst] = (char *)&sp->chars[ttisp->tt_abbrind];
1015   tmp->tm_zone = (char *)&sp->chars[ttisp->tt_abbrind];
1016 }
1017
1018 struct tm *
1019 localtime(const time_t * const timep)
1020 {
1021   static struct tm tm;
1022
1023   localsub(timep, 0L, &tm);
1024   return &tm;
1025 }
1026
1027 /*
1028 ** gmtsub is to gmtime as localsub is to localtime.
1029 */
1030
1031 static void
1032 gmtsub(const time_t * const timep, const long offset, struct tm * const tmp)
1033 {
1034   if (!gmt_is_set)
1035   {
1036     gmt_is_set = TRUE;
1037 #ifdef ALL_STATE
1038     gmtptr = (struct state *) malloc(sizeof *gmtptr);
1039     if (gmtptr != NULL)
1040 #endif /* defined ALL_STATE */
1041       gmtload(gmtptr);
1042   }
1043   timesub(timep, offset, gmtptr, tmp);
1044   /*
1045    ** Could get fancy here and deliver something such as
1046    ** "GMT+xxxx" or "GMT-xxxx" if offset is non-zero,
1047    ** but this is no time for a treasure hunt.
1048    */
1049   if (offset != 0)
1050     tmp->tm_zone = WILDABBR;
1051   else
1052   {
1053 #ifdef ALL_STATE
1054     if (gmtptr == NULL)
1055       tmp->TM_ZONE = GMT;
1056     else
1057       tmp->TM_ZONE = gmtptr->chars;
1058 #endif /* defined ALL_STATE */
1059 #ifndef ALL_STATE
1060     tmp->tm_zone = gmtptr->chars;
1061 #endif /* State Farm */
1062   }
1063 }
1064
1065 struct tm *
1066 gmtime(const time_t * const timep)
1067 {
1068   static struct tm tm;
1069
1070   gmtsub(timep, 0L, &tm);
1071   return &tm;
1072 }
1073
1074 static void
1075 timesub(const time_t * const timep, const long offset, const struct state * const sp, struct tm * const tmp)
1076 {
1077   const struct lsinfo * lp;
1078   long days;
1079   long rem;
1080   int y;
1081   int yleap;
1082   const int * ip;
1083   long corr;
1084   int hit;
1085   int i;
1086
1087   corr = 0;
1088   hit = FALSE;
1089 #ifdef ALL_STATE
1090   i = (sp == NULL) ? 0 : sp->leapcnt;
1091 #endif /* defined ALL_STATE */
1092 #ifndef ALL_STATE
1093   i = sp->leapcnt;
1094 #endif /* State Farm */
1095   while (--i >= 0)
1096   {
1097     lp = &sp->lsis[i];
1098     if (*timep >= lp->ls_trans)
1099     {
1100       if (*timep == lp->ls_trans)
1101         hit = ((i == 0 && lp->ls_corr > 0) ||
1102                lp->ls_corr > sp->lsis[i - 1].ls_corr);
1103       corr = lp->ls_corr;
1104       break;
1105     }
1106   }
1107   days = *timep / SECSPERDAY;
1108   rem = *timep % SECSPERDAY;
1109 #ifdef mc68k
1110   if (*timep == 0x80000000)
1111   {
1112     /*
1113      ** A 3B1 muffs the division on the most negative number.
1114      */
1115     days = -24855;
1116     rem = -11648;
1117   }
1118 #endif /* mc68k */
1119   rem += (offset - corr);
1120   while (rem < 0)
1121   {
1122     rem += SECSPERDAY;
1123     --days;
1124   }
1125   while (rem >= SECSPERDAY)
1126   {
1127     rem -= SECSPERDAY;
1128     ++days;
1129   }
1130   tmp->tm_hour = (int) (rem / SECSPERHOUR);
1131   rem = rem % SECSPERHOUR;
1132   tmp->tm_min = (int) (rem / SECSPERMIN);
1133   tmp->tm_sec = (int) (rem % SECSPERMIN);
1134   if (hit)
1135     /*
1136      ** A positive leap second requires a special
1137      ** representation.  This uses "... ??:59:60".
1138      */
1139     ++(tmp->tm_sec);
1140   tmp->tm_wday = (int) ((EPOCH_WDAY + days) % DAYSPERWEEK);
1141   if (tmp->tm_wday < 0)
1142     tmp->tm_wday += DAYSPERWEEK;
1143   y = EPOCH_YEAR;
1144   if (days >= 0)
1145     for ( ; ; )
1146     {
1147       yleap = isleap(y);
1148       if (days < (long) year_lengths[yleap])
1149         break;
1150       ++y;
1151       days = days - (long) year_lengths[yleap];
1152     }
1153   else
1154     do {
1155     --y;
1156     yleap = isleap(y);
1157     days = days + (long) year_lengths[yleap];
1158   } while (days < 0);
1159   tmp->tm_year = y - TM_YEAR_BASE;
1160   tmp->tm_yday = (int) days;
1161   ip = mon_lengths[yleap];
1162   for (tmp->tm_mon = 0; days >= (long) ip[tmp->tm_mon]; ++(tmp->tm_mon))
1163     days = days - (long) ip[tmp->tm_mon];
1164   tmp->tm_mday = (int) (days + 1);
1165   tmp->tm_isdst = 0;
1166   tmp->tm_gmtoff = offset;
1167 }
1168
1169 /*
1170 ** A la X3J11
1171 */
1172
1173 char *
1174 asctime(const struct tm *timeptr)
1175 {
1176   static const char wday_name[DAYSPERWEEK][3] = {
1177     "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
1178   };
1179   static const char mon_name[MONSPERYEAR][3] = {
1180     "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1181     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1182   };
1183   static char result[26];
1184
1185   (void) sprintf(result, "%.3s %.3s%3d %02d:%02d:%02d %d\n",
1186                  wday_name[timeptr->tm_wday],
1187                  mon_name[timeptr->tm_mon],
1188                  timeptr->tm_mday, timeptr->tm_hour,
1189                  timeptr->tm_min, timeptr->tm_sec,
1190                  TM_YEAR_BASE + timeptr->tm_year);
1191   return result;
1192 }
1193
1194 char *
1195 ctime(const time_t * const timep)
1196 {
1197   return asctime(localtime(timep));
1198 }
1199
1200 /*
1201 ** Adapted from code provided by Robert Elz, who writes:
1202 **      The "best" way to do mktime I think is based on an idea of Bob
1203 **      Kridle's (so its said...) from a long time ago. (mtxinu!kridle now).
1204 **      It does a binary search of the time_t space.  Since time_t's are
1205 **      just 32 bits, its a max of 32 iterations (even at 64 bits it
1206 **      would still be very reasonable).
1207 */
1208
1209 #ifndef WRONG
1210 #define WRONG   (-1)
1211 #endif /* !defined WRONG */
1212
1213 static void
1214 normalize(int * const tensptr, int * const unitsptr, const int base)
1215 {
1216   if (*unitsptr >= base)
1217   {
1218     *tensptr += *unitsptr / base;
1219     *unitsptr %= base;
1220   }
1221   else if (*unitsptr < 0)
1222   {
1223     --*tensptr;
1224     *unitsptr += base;
1225     if (*unitsptr < 0)
1226     {
1227       *tensptr -= 1 + (-*unitsptr) / base;
1228       *unitsptr = base - (-*unitsptr) % base;
1229     }
1230   }
1231 }
1232
1233 static int
1234 tmcomp(const struct tm * const atmp, const struct tm * const btmp)
1235 {
1236   int result;
1237
1238   if ((result = (atmp->tm_year - btmp->tm_year)) == 0 &&
1239       (result = (atmp->tm_mon - btmp->tm_mon)) == 0 &&
1240       (result = (atmp->tm_mday - btmp->tm_mday)) == 0 &&
1241       (result = (atmp->tm_hour - btmp->tm_hour)) == 0 &&
1242       (result = (atmp->tm_min - btmp->tm_min)) == 0)
1243     result = atmp->tm_sec - btmp->tm_sec;
1244   return result;
1245 }
1246
1247 static time_t
1248 time2(struct tm *tmp, void (*const funcp)(const time_t *const,const long,struct tm *), const long offset, int * const okayp)
1249 {
1250   const struct state * sp;
1251   int dir;
1252   int bits;
1253   int i, j ;
1254   int saved_seconds;
1255   time_t newt;
1256   time_t t;
1257   struct tm yourtm, mytm;
1258
1259   *okayp = FALSE;
1260   yourtm = *tmp;
1261   if (yourtm.tm_sec >= SECSPERMIN + 2 || yourtm.tm_sec < 0)
1262     normalize(&yourtm.tm_min, &yourtm.tm_sec, SECSPERMIN);
1263   normalize(&yourtm.tm_hour, &yourtm.tm_min, MINSPERHOUR);
1264   normalize(&yourtm.tm_mday, &yourtm.tm_hour, HOURSPERDAY);
1265   normalize(&yourtm.tm_year, &yourtm.tm_mon, MONSPERYEAR);
1266   while (yourtm.tm_mday <= 0)
1267   {
1268     --yourtm.tm_year;
1269     yourtm.tm_mday +=
1270       year_lengths[isleap(yourtm.tm_year + TM_YEAR_BASE)];
1271   }
1272   for ( ; ; )
1273   {
1274     i = mon_lengths[isleap(yourtm.tm_year +
1275                            TM_YEAR_BASE)][yourtm.tm_mon];
1276     if (yourtm.tm_mday <= i)
1277       break;
1278     yourtm.tm_mday -= i;
1279     if (++yourtm.tm_mon >= MONSPERYEAR)
1280     {
1281       yourtm.tm_mon = 0;
1282       ++yourtm.tm_year;
1283     }
1284   }
1285   saved_seconds = yourtm.tm_sec;
1286   yourtm.tm_sec = 0;
1287   /*
1288    ** Calculate the number of magnitude bits in a time_t
1289    ** (this works regardless of whether time_t is
1290    ** signed or unsigned, though lint complains if unsigned).
1291    */
1292   for (bits = 0, t = 1; t > 0; ++bits, t <<= 1)
1293     ;
1294   /*
1295    ** If time_t is signed, then 0 is the median value,
1296    ** if time_t is unsigned, then 1 << bits is median.
1297    */
1298   t = (time_t) 1 << bits;
1299   for ( ; ; )
1300   {
1301     (*funcp)(&t, offset, &mytm);
1302     dir = tmcomp(&mytm, &yourtm);
1303     if (dir != 0)
1304     {
1305       if (bits-- < 0)
1306         return WRONG;
1307       if (bits < 0)
1308         --t;
1309       else if (dir > 0)
1310         t -= (time_t) 1 << bits;
1311       else t += (time_t) 1 << bits;
1312       continue;
1313     }
1314     if (yourtm.tm_isdst < 0 || mytm.tm_isdst == yourtm.tm_isdst)
1315       break;
1316     /*
1317      ** Right time, wrong type.
1318      ** Hunt for right time, right type.
1319      ** It's okay to guess wrong since the guess
1320      ** gets checked.
1321      */
1322     sp = (const struct state *)
1323       ((funcp == localsub) ? lclptr : gmtptr);
1324 #ifdef ALL_STATE
1325     if (sp == NULL)
1326       return WRONG;
1327 #endif /* defined ALL_STATE */
1328     for (i = 0; i < sp->typecnt; ++i)
1329     {
1330       if (sp->ttis[i].tt_isdst != yourtm.tm_isdst)
1331         continue;
1332       for (j = 0; j < sp->typecnt; ++j)
1333       {
1334         if (sp->ttis[j].tt_isdst == yourtm.tm_isdst)
1335           continue;
1336         newt = t + sp->ttis[j].tt_gmtoff -
1337           sp->ttis[i].tt_gmtoff;
1338         (*funcp)(&newt, offset, &mytm);
1339         if (tmcomp(&mytm, &yourtm) != 0)
1340           continue;
1341         if (mytm.tm_isdst != yourtm.tm_isdst)
1342           continue;
1343         /*
1344          ** We have a match.
1345          */
1346         t = newt;
1347         goto label;
1348       }
1349     }
1350     return WRONG;
1351   }
1352  label:
1353   t += saved_seconds;
1354   (*funcp)(&t, offset, tmp);
1355   *okayp = TRUE;
1356   return t;
1357 }
1358
1359 static time_t
1360 time1(struct tm * const tmp, void (*const funcp)(const time_t * const, const long, struct tm *), const long offset)
1361 {
1362   time_t t;
1363   const struct state * sp;
1364   int samei, otheri;
1365   int okay;
1366
1367   if (tmp->tm_isdst > 1)
1368     tmp->tm_isdst = 1;
1369   t = time2(tmp, funcp, offset, &okay);
1370   if (okay || tmp->tm_isdst < 0)
1371     return t;
1372   /*
1373    ** We're supposed to assume that somebody took a time of one type
1374    ** and did some math on it that yielded a "struct tm" that's bad.
1375    ** We try to divine the type they started from and adjust to the
1376    ** type they need.
1377    */
1378   sp = (const struct state *) ((funcp == localsub) ? lclptr : gmtptr);
1379 #ifdef ALL_STATE
1380   if (sp == NULL)
1381     return WRONG;
1382 #endif /* defined ALL_STATE */
1383   for (samei = 0; samei < sp->typecnt; ++samei)
1384   {
1385     if (sp->ttis[samei].tt_isdst != tmp->tm_isdst)
1386       continue;
1387     for (otheri = 0; otheri < sp->typecnt; ++otheri)
1388     {
1389       if (sp->ttis[otheri].tt_isdst == tmp->tm_isdst)
1390         continue;
1391       tmp->tm_sec += sp->ttis[otheri].tt_gmtoff -
1392         sp->ttis[samei].tt_gmtoff;
1393       tmp->tm_isdst = !tmp->tm_isdst;
1394       t = time2(tmp, funcp, offset, &okay);
1395       if (okay)
1396         return t;
1397       tmp->tm_sec -= sp->ttis[otheri].tt_gmtoff -
1398         sp->ttis[samei].tt_gmtoff;
1399       tmp->tm_isdst = !tmp->tm_isdst;
1400     }
1401   }
1402   return WRONG;
1403 }
1404
1405 time_t
1406 mktime(struct tm * tmp)
1407 {
1408   return time1(tmp, localsub, 0L);
1409 }
1410
1411
1412
1413