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