]> git.mxchange.org Git - simgear.git/blob - simgear/timing/lowleveltime.cxx
Mark's dynamic sun color changes.
[simgear.git] / simgear / timing / lowleveltime.cxx
1 /* -*- Mode: C++ -*- *****************************************************
2  * Written by various people (I"ll look up the exact credits later)
3  * Modified by Durk Talsma, July 1999 for use in FlightGear
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18  *
19  **************************************************************************/
20
21 /********************************************************************
22  * This file redefines some low-level Unix-like time functions for  *
23  * use with FlightGear. Most notably, localtime() is adapted to use *
24  * a custom timezone, in order to get the 'local' time for a given  *
25  * aircraft's position, and not only for the current location of the*
26  * computer running the sim.                                        *
27  *                                                                  *
28  * Software adapted from glibc functions, by Durk Talsma. Started   *
29  * July, 17, 1999.                                                  *
30  ********************************************************************/
31
32
33 #include <time.h>
34 #include <stdio.h>
35 #include <ctype.h>
36 #include <errno.h>
37 //#include <libc-lock.h>
38 #include <stddef.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <limits.h>
43 #include "lowleveltime.h"
44
45
46 /* BIG FAT WARNING: NOTICE THAT I HARDCODED ENDIANNES. PLEASE CHANGE THIS */
47 #ifndef BIG_ENDIAN 
48 #define BIG_ENDIAN 4321
49 #endif
50
51 #ifndef LITTLE_ENDIAN
52 #define LITTLE_ENDIAN 1234
53 #endif
54
55 #ifndef BYTE_ORDER 
56 #define BYTE_ORDER LITTLE_ENDIAN
57 #endif
58
59
60 #ifndef BYTE_ORDER
61 #define BYTE_ORDER 
62 #endif
63
64 /* END OF BIG FAT WARNING */
65
66 //#include "tzfile.h"
67
68 #define min(a, b)       ((a) < (b) ? (a) : (b))
69 #define max(a, b)       ((a) > (b) ? (a) : (b))
70 #define sign(x)         ((x) < 0 ? -1 : 1)
71
72 struct leap
73   {
74     time_t transition;          /* Time the transition takes effect.  */
75     long int change;            /* Seconds of correction to apply.  */
76   };
77
78 /* Header for a list of buffers containing time zone strings.  */
79 struct tzstring_head
80 {
81   struct tzstring_head *next;
82   /* The buffer itself immediately follows the header.
83      The buffer contains zero or more (possibly overlapping) strings.
84      The last string is followed by 2 '\0's instead of the usual 1.  */
85 };
86
87
88 /* First in a list of buffers containing time zone strings.
89    All the buffers but the last are read-only.  */
90 static struct
91 {
92   struct tzstring_head head;
93   char data[48];
94 } tzstring_list;
95
96 /* Size of the last buffer in the list, not counting its header.  */
97 static size_t tzstring_last_buffer_size = sizeof tzstring_list.data;
98
99
100 static char *old_fgtz = NULL;
101 static int use_fgtzfile = 1;
102 static int fgdaylight;
103 static char* fgtzname[2];
104 static long int fgtimezone;
105
106
107 static size_t num_transitions;
108 static time_t *transitions = NULL;
109 static unsigned char *type_idxs = NULL;
110 static size_t num_types;
111 static struct ttinfo *types = NULL;
112 static char *zone_names = NULL;
113 static size_t num_leaps;
114 static struct leap *leaps = NULL;
115
116
117 static void fgtzset_internal (int always, const char *tz);
118 static int fgtz_compute(time_t timer, const struct tm *tm);
119 static int fgcompute_change(fgtz_rule *rule, int year);
120 static struct ttinfo *fgfind_transition (time_t timer);
121 static void fgcompute_tzname_max (size_t chars);
122 static inline int decode (const void *ptr);
123 void fgtzfile_read (const char *file);
124 static void offtime (const time_t *t, long int offset, struct tm *tp);
125 static char *tzstring (const char* string);
126
127 /* tz_rules[0] is standard, tz_rules[1] is daylight.  */
128 static fgtz_rule fgtz_rules[2];
129
130 int fgtzfile_compute (time_t timer, int use_localtime,
131                   long int *leap_correct, int *leap_hit);
132 struct ttinfo
133   {
134     long int offset;            /* Seconds east of GMT.  */
135     unsigned char isdst;        /* Used to set tm_isdst.  */
136     unsigned char idx;          /* Index into `zone_names'.  */
137     unsigned char isstd;        /* Transition times are in standard time.  */
138     unsigned char isgmt;        /* Transition times are in GMT.  */
139   };
140
141
142
143 /* How many days come before each month (0-12).  */
144 const unsigned short int mon_yday[2][13] =
145   {
146     /* Normal years.  */
147     { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
148     /* Leap years.  */
149     { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
150   };
151
152
153 /* The C Standard says that localtime and gmtime return the same pointer.  */
154 struct tm _fgtmbuf;
155
156
157 #ifndef isleap
158 /* Nonzero if YEAR is a leap year (every 4 years,
159    except every 100th isn't, and every 400th is).  */
160 # define isleap(year) \
161   ((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0))
162 #endif
163
164
165
166
167 /* Return the `struct tm' representation of *T in local time.  */
168 struct tm * fgLocaltime (const time_t *t, const char *tzName)
169 {
170   return fgtz_convert (t, 1, &_fgtmbuf, tzName);
171 }
172
173
174 /* Return the `struct tm' representation of *TIMER in the local timezone.
175    Use local time if USE_LOCALTIME is nonzero, UTC otherwise.  */
176 struct tm * fgtz_convert (const time_t *timer, int use_localtime, struct tm *tp, const char *tzName)
177 {
178   long int leap_correction;
179   long int offsetCorr;                 // ADDED TO RESOLVE NON-ANSI FIELDS IN struct tm
180   int leap_extra_secs;
181
182   if (timer == NULL)
183     {
184       //set_errno (EINVAL);
185       return NULL;
186     }
187
188   //libc_lock_lock (tzset_lock);
189
190   /* Update internal database according to current TZ setting.
191      POSIX.1 8.3.7.2 says that localtime_r is not required to set tzname.
192      This is a good idea since this allows at least a bit more parallelism.
193      By analogy we apply the same rule to gmtime_r.  */
194   fgtzset_internal (tp == &_fgtmbuf, tzName);
195
196   if (use_fgtzfile)
197     {
198       if (! fgtzfile_compute (*timer, use_localtime,
199                               &leap_correction, &leap_extra_secs))
200         tp = NULL;
201     }
202   else
203     {
204       offtime (timer, 0, tp);
205       if (! fgtz_compute (*timer, tp))
206         tp = NULL;
207       leap_correction = 0L;
208       leap_extra_secs = 0;
209     }
210
211   if (tp)
212     {
213       if (use_localtime)
214         {
215           tp->tm_isdst = fgdaylight;
216           //tp->tm_zone = fgtzname[fgdaylight];       // NON_ANSI
217           //tp->tm_gmtoff = -fgtimezone;              // NON_ANSI
218           offsetCorr = -fgtimezone;
219         }
220       else
221         {
222           tp->tm_isdst = 0;
223           //tp->tm_zone = "GMT";                     // NON_ANSI
224           //tp->tm_gmtoff = 0L;                      // NON_ANSI
225           offsetCorr = -fgtimezone;
226         }
227
228       //offtime (timer, tp->tm_gmtoff - leap_correction, tp);
229       offtime (timer, offsetCorr - leap_correction, tp);
230       tp->tm_sec += leap_extra_secs;
231     }
232
233   //libc_lock_unlock (tzset_lock);
234
235   return tp;
236 }
237
238
239
240 /* the following stuff is adapted from the tzCode package */
241
242 static size_t   longest;
243 static char *   abbr (struct tm * tmp);
244
245 void show(const char *zone, time_t t, int v)
246 {
247         struct tm *     tmp;
248
249         (void) printf("%-*s  ", (int) longest, zone);
250         if (v)
251                 (void) printf("%.24s UTC = ", asctime(gmtime(&t)));
252         tmp = fgLocaltime(&t, zone);
253         (void) printf("%.24s", asctime(tmp));
254         if (*abbr(tmp) != '\0')
255                 (void) printf(" %s", abbr(tmp));
256         if (v) {
257                 (void) printf(" isdst=%d", tmp->tm_isdst);
258 #ifdef TM_GMTOFF
259                 (void) printf(" gmtoff=%ld", tmp->TM_GMTOFF);
260 #endif /* defined TM_GMTOFF */
261         }
262         (void) printf("\n");
263 }
264
265 static char *abbr(struct tm *tmp)
266 {
267         register char * result;
268         static char     nada;
269
270         if (tmp->tm_isdst != 0 && tmp->tm_isdst != 1)
271                 return &nada;
272         result = fgtzname[tmp->tm_isdst];
273         return (result == NULL) ? &nada : result;
274 }
275
276
277
278 /***********************************************************************/
279
280
281 /* Interpret the TZ envariable.  */
282 static void fgtzset_internal (int always, const char *tz)
283 {
284   time_t now;
285   time(&now);
286   static int is_initialized = 0;
287   //register const char *tz;
288   // register size_t l;
289   // char *tzbuf;
290   // unsigned short int hh, mm, ss;
291   // unsigned short int whichrule;
292
293   if (is_initialized && !always)
294     return;
295   is_initialized = 1;
296
297   /* Examine the TZ environment variable.  */
298   //tz = getenv ("TZ");
299   if (tz == NULL)
300     /* No user specification; use the site-wide default.  */
301     tz = TZDEFAULT;
302   else if (*tz == '\0')
303     /* User specified the empty string; use UTC explicitly.  */
304     tz = "Universal";
305
306 #ifdef macintosh
307   /* as you well know, mac paths contain leading colon, this code
308      messes things up.... */
309 #else
310   /* A leading colon means "implementation defined syntax".
311      We ignore the colon and always use the same algorithm:
312      try a data file, and if none exists parse the 1003.1 syntax.  */
313   if (tz && *tz == ':')
314     ++tz;
315 #endif
316
317   /* Check whether the value changes since the last run.  */
318   if (old_fgtz != NULL && tz != NULL && strcmp (tz, old_fgtz) == 0)
319     /* No change, simply return.  */
320     return;
321
322   fgtz_rules[0].name = NULL;
323   fgtz_rules[1].name = NULL;
324
325   /* Save the value of `tz'.  */
326   if (old_fgtz != NULL)
327     free (old_fgtz);
328   old_fgtz = tz ? strdup (tz) : NULL;
329
330   /* Try to read a data file.  */
331   fgtzfile_read (tz);
332   if (use_fgtzfile)
333     return;
334   // The default behaviour of the originale tzset_internal (int always, char* tz) 
335   // function is to set up a default timezone, in any casetz file_read() fails
336   // Currently this leads to problems, because it modidifies the system timezone
337   // and not the local aircraft timezone, contained in FlightGear. I could adapt 
338   // this in future versions of this code, but doubt whether this is what we really
339   // want. So right now, exit when timezone information reading failed. 
340   // Guess I'll change that to something like 12 * (FG_LON / 180.0)
341   // 
342   // For now, I'll leave it like this.
343   else
344   {
345     printf ("Timezone reading failed\n");
346     exit(1);
347   }
348   // this emacs "comment out" function is cool!
349  
350 //   // /* No data file found.  Default to UTC if nothing specified.  */
351 // //   printf ("1. Current local time          = %24s", asctime(localtime(&now)));
352 //   if (tz == NULL || *tz == '\0')
353 //     {
354 //       fgtz_rules[0].name = fgtz_rules[1].name = "UTC";
355 //       fgtz_rules[0].type = fgtz_rules[1].type = fgtz_rule::J0;
356 //       fgtz_rules[0].m = fgtz_rules[0].n = fgtz_rules[0].d = 0;
357 //       fgtz_rules[1].m = fgtz_rules[1].n = fgtz_rules[1].d = 0;
358 //       fgtz_rules[0].secs = fgtz_rules[1].secs = 0;
359 //       fgtz_rules[0].offset = fgtz_rules[1].offset = 0L;
360 //       fgtz_rules[0].change = fgtz_rules[1].change = (time_t) -1;
361 //       fgtz_rules[0].computed_for = fgtz_rules[1].computed_for = 0;
362 //       return;
363 //     }
364
365 //   /* Clear out old state and reset to unnamed UTC.  */
366 //   //printf ("2. Current local time          = %24s", asctime(localtime(&now)));
367 //   memset (fgtz_rules, 0, sizeof fgtz_rules);
368 //   fgtz_rules[0].name = fgtz_rules[1].name = "";
369
370 //   /* Get the standard timezone name.  */
371 //   tzbuf = malloc (strlen (tz) + 1);
372 //   if (! tzbuf)
373 //     {
374 //       /* Clear the old tz name so we will try again.  */
375 //       free (old_fgtz);
376 //       old_fgtz = NULL;
377 //       return;
378 //     }
379 //   //printf ("3. Current local time          = %24s", asctime(localtime(&now)));
380 //   if (sscanf (tz, "%[^0-9,+-]", tzbuf) != 1 ||
381 //       (l = strlen (tzbuf)) < 3)
382 //     {
383 //       free (tzbuf);
384 //       return;
385 //     }
386
387 //   fgtz_rules[0].name = tzstring (tzbuf);
388
389 //   tz += l;
390 //   //printf ("4. Current local time          = %24s", asctime(localtime(&now)));
391 //   /* Figure out the standard offset from UTC.  */
392 //   if (*tz == '\0' || (*tz != '+' && *tz != '-' && !isdigit (*tz)))
393 //     {
394 //       free (tzbuf);
395 //       return;
396 //     }
397 //   //printf ("5. Current local time          = %24s", asctime(localtime(&now)));
398 //   if (*tz == '-' || *tz == '+')
399 //     fgtz_rules[0].offset = *tz++ == '-' ? 1L : -1L;
400 //   else
401 //     fgtz_rules[0].offset = -1L;
402 //   switch (sscanf (tz, "%hu:%hu:%hu", &hh, &mm, &ss))
403 //     {
404 //     default:
405 //       free (tzbuf);
406 //       return;
407 //     case 1:
408 //       mm = 0;
409 //     case 2:
410 //       ss = 0;
411 //     case 3:
412 //       break;
413 //     }
414 //     //printf ("6. Current local time          = %24s", asctime(localtime(&now)));
415 //   fgtz_rules[0].offset *= (min (ss, 59) + (min (mm, 59) * 60) +
416 //                       (min (hh, 23) * 60 * 60));
417
418 //   for (l = 0; l < 3; ++l)
419 //     {
420 //       while (isdigit(*tz))
421 //      ++tz;
422 //       if (l < 2 && *tz == ':')
423 //      ++tz;
424 //     }
425 //   //printf ("7. Current local time          = %24s", asctime(localtime(&now)));
426 //   /* Get the DST timezone name (if any).  */
427 //   if (*tz != '\0')
428 //     {
429 //       char *n = tzbuf + strlen (tzbuf) + 1;
430 //       if (sscanf (tz, "%[^0-9,+-]", n) != 1 ||
431 //        (l = strlen (n)) < 3)
432 //      goto done_names;        /* Punt on name, set up the offsets.  */
433 //   //printf ("7.1 Current local time          = %24s", asctime(localtime(&now)));
434 //       fgtz_rules[1].name = tzstring (n);
435
436 //       tz += l;
437
438 //       /* Figure out the DST offset from GMT.  */
439 //       if (*tz == '-' || *tz == '+')
440 //      fgtz_rules[1].offset = *tz++ == '-' ? 1L : -1L;
441 //       else
442 //      fgtz_rules[1].offset = -1L;
443 //   //printf ("7.2 Current local time          = %24s", asctime(localtime(&now)));
444 //       switch (sscanf (tz, "%hu:%hu:%hu", &hh, &mm, &ss))
445 //      {
446 //      default:
447 //        /* Default to one hour later than standard time.  */
448 //        fgtz_rules[1].offset = fgtz_rules[0].offset + (60 * 60);
449 //        break;
450
451 //      case 1:
452 //        mm = 0;
453 //      case 2:
454 //        ss = 0;
455 //      case 3:
456 //        fgtz_rules[1].offset *= (min (ss, 59) + (min (mm, 59) * 60) +
457 //                               (min (hh, 23) * (60 * 60)));
458 //        break;
459 //      }
460 //   //printf ("7.3 Current local time          = %24s", asctime(localtime(&now)));
461 //       for (l = 0; l < 3; ++l)
462 //      {
463 //        while (isdigit (*tz))
464 //          ++tz;
465 //        if (l < 2 && *tz == ':')
466 //          ++tz;
467 //      }
468 //   //printf ("7.4 Current local time          = %24s", asctime(localtime(&now)));
469 //       if (*tz == '\0' || (tz[0] == ',' && tz[1] == '\0'))
470 //      {
471 //        /* There is no rule.  See if there is a default rule file.  */
472 //   //printf ("7.4.1 Current local time          = %24s", asctime(localtime(&now)));
473 //        tzfile_default (fgtz_rules[0].name, fgtz_rules[1].name,
474 //                          fgtz_rules[0].offset, fgtz_rules[1].offset);
475 //   //printf ("7.4.2 Current local time          = %24s", asctime(localtime(&now)));
476 //        if (use_fgtzfile)
477 //          {
478 //            free (old_fgtz);
479 //            old_fgtz = NULL;
480 //            free (tzbuf);
481 //            return;
482 //          }
483 //      }
484 //     }
485 //   else
486 //     {
487 //       /* There is no DST.  */
488 //       fgtz_rules[1].name = fgtz_rules[0].name;
489 //       free (tzbuf);
490 //       return;
491 //     }
492 //   //printf ("7.5 Current local time          = %24s", asctime(localtime(&now)));
493 //  done_names:
494 //   //printf ("8. Current local time          = %24s", asctime(localtime(&now)));
495 //   free (tzbuf);
496
497 //   /* Figure out the standard <-> DST rules.  */
498 //   for (whichrule = 0; whichrule < 2; ++whichrule)
499 //     {
500 //       register fgtz_rule *tzr = &fgtz_rules[whichrule];
501
502 //       /* Ignore comma to support string following the incorrect
503 //       specification in early POSIX.1 printings.  */
504 //       tz += *tz == ',';
505
506 //       /* Get the date of the change.  */
507 //       if (*tz == 'J' || isdigit (*tz))
508 //      {
509 //        char *end;
510 //        tzr->type = *tz == 'J' ? fgtz_rule::J1 : fgtz_rule::J0;
511 //        if (tzr->type == fgtz_rule::J1 && !isdigit (*++tz))
512 //          return;
513 //        tzr->d = (unsigned short int) strtoul (tz, &end, 10);
514 //        if (end == tz || tzr->d > 365)
515 //          return;
516 //        else if (tzr->type == fgtz_rule::J1 && tzr->d == 0)
517 //          return;
518 //        tz = end;
519 //      }
520 //       else if (*tz == 'M')
521 //      {
522 //        int n;
523 //        tzr->type = fgtz_rule::M;
524 //        if (sscanf (tz, "M%hu.%hu.%hu%n",
525 //                    &tzr->m, &tzr->n, &tzr->d, &n) != 3 ||
526 //            tzr->m < 1 || tzr->m > 12 ||
527 //            tzr->n < 1 || tzr->n > 5 || tzr->d > 6)
528 //          return;
529 //        tz += n;
530 //      }
531 //       else if (*tz == '\0')
532 //      {
533 //        /* United States Federal Law, the equivalent of "M4.1.0,M10.5.0".  */
534 //        tzr->type = fgtz_rule::M;
535 //        if (tzr == &fgtz_rules[0])
536 //          {
537 //            tzr->m = 4;
538 //            tzr->n = 1;
539 //            tzr->d = 0;
540 //          }
541 //        else
542 //          {
543 //            tzr->m = 10;
544 //            tzr->n = 5;
545 //            tzr->d = 0;
546 //          }
547 //      }
548 //       else
549 //      return;
550 //       //printf ("9. Current local time          = %24s", asctime(localtime(&now)));
551 //       if (*tz != '\0' && *tz != '/' && *tz != ',')
552 //      return;
553 //       else if (*tz == '/')
554 //      {
555 //        /* Get the time of day of the change.  */
556 //        ++tz;
557 //        if (*tz == '\0')
558 //          return;
559 //        switch (sscanf (tz, "%hu:%hu:%hu", &hh, &mm, &ss))
560 //          {
561 //          default:
562 //            hh = 2;           /* Default to 2:00 AM.  */
563 //          case 1:
564 //            mm = 0;
565 //          case 2:
566 //            ss = 0;
567 //          case 3:
568 //            break;
569 //          }
570 //        for (l = 0; l < 3; ++l)
571 //          {
572 //            while (isdigit (*tz))
573 //              ++tz;
574 //            if (l < 2 && *tz == ':')
575 //              ++tz;
576 //          }
577 //        tzr->secs = (hh * 60 * 60) + (mm * 60) + ss;
578 //      }
579 //       else
580 //      /* Default to 2:00 AM.  */
581 //      tzr->secs = 2 * 60 * 60;
582
583 //       tzr->computed_for = -1;
584 //     }
585 // //   printf ("10. Current local time          = %24s", asctime(localtime(&now)));
586 // 
587 }
588
589 /************************************************************************/
590
591
592 /* Figure out the correct timezone for *TIMER and TM (which must be the same)
593    and set `tzname', `timezone', and `daylight' accordingly.
594    Return nonzero on success, zero on failure.  */
595 size_t fgtzname_cur_max;
596
597 static int fgtz_compute (time_t timer, const struct tm* tm)
598   //     time_t timer;
599   // const struct tm *tm;
600 {
601   if (! fgcompute_change (&fgtz_rules[0], 1900 + tm->tm_year) ||
602       ! fgcompute_change (&fgtz_rules[1], 1900 + tm->tm_year))
603     return 0;
604
605   fgdaylight = timer >= fgtz_rules[0].change && timer < fgtz_rules[1].change;
606   fgtimezone = -fgtz_rules[fgdaylight].offset;
607   fgtzname[0] = (char *) fgtz_rules[0].name;
608   fgtzname[1] = (char *) fgtz_rules[1].name;
609
610   {
611     /* Keep tzname_cur_max up to date.  */
612     size_t len0 = strlen (fgtzname[0]);
613     size_t len1 = strlen (fgtzname[1]);
614     if (len0 > fgtzname_cur_max)
615       fgtzname_cur_max = len0;
616     if (len1 > fgtzname_cur_max)
617       fgtzname_cur_max = len1;
618   }
619
620   return 1;
621 }
622
623 /**********************************************************************/
624
625 /* Figure out the exact time (as a time_t) in YEAR
626    when the change described by RULE will occur and
627    put it in RULE->change, saving YEAR in RULE->computed_for.
628    Return nonzero if successful, zero on failure.  */
629 static int fgcompute_change (fgtz_rule *rule, int year)
630   //     tz_rule *rule;
631   // int year;
632 {
633   register time_t t;
634   int y;
635
636   if (year != -1 && rule->computed_for == year)
637     /* Operations on times in 1969 will be slower.  Oh well.  */
638     return 1;
639
640   /* First set T to January 1st, 0:00:00 GMT in YEAR.  */
641   t = 0;
642   for (y = 1970; y < year; ++y)
643     t += SECSPERDAY * (isleap (y) ? 366 : 365);
644
645   switch (rule->type)
646     {
647     case fgtz_rule::J1:
648       /* Jn - Julian day, 1 == January 1, 60 == March 1 even in leap years.
649          In non-leap years, or if the day number is 59 or less, just
650          add SECSPERDAY times the day number-1 to the time of
651          January 1, midnight, to get the day.  */
652       t += (rule->d - 1) * SECSPERDAY;
653       if (rule->d >= 60 && isleap (year))
654         t += SECSPERDAY;
655       break;
656
657     case fgtz_rule::J0:
658       /* n - Day of year.
659          Just add SECSPERDAY times the day number to the time of Jan 1st.  */
660       t += rule->d * SECSPERDAY;
661       break;
662
663     case fgtz_rule::M:
664       /* Mm.n.d - Nth "Dth day" of month M.  */
665       {
666         register int i, d, m1, yy0, yy1, yy2, dow;
667         register const unsigned short int *myday =
668           &mon_yday[isleap (year)][rule->m];
669
670         /* First add SECSPERDAY for each day in months before M.  */
671         t += myday[-1] * SECSPERDAY;
672
673         /* Use Zeller's Congruence to get day-of-week of first day of month. */
674         m1 = (rule->m + 9) % 12 + 1;
675         yy0 = (rule->m <= 2) ? (year - 1) : year;
676         yy1 = yy0 / 100;
677         yy2 = yy0 % 100;
678         dow = ((26 * m1 - 2) / 10 + 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
679         if (dow < 0)
680           dow += 7;
681
682         /* DOW is the day-of-week of the first day of the month.  Get the
683            day-of-month (zero-origin) of the first DOW day of the month.  */
684         d = rule->d - dow;
685         if (d < 0)
686           d += 7;
687         for (i = 1; i < rule->n; ++i)
688           {
689             if (d + 7 >= myday[0] - myday[-1])
690               break;
691             d += 7;
692           }
693
694         /* D is the day-of-month (zero-origin) of the day we want.  */
695         t += d * SECSPERDAY;
696       }
697       break;
698     }
699
700   /* T is now the Epoch-relative time of 0:00:00 GMT on the day we want.
701      Just add the time of day and local offset from GMT, and we're done.  */
702
703   rule->change = t - rule->offset + rule->secs;
704   rule->computed_for = year;
705   return 1;
706 }
707
708 /*************************************************************************/
709
710 int fgtzfile_compute (time_t timer, int use_localtime,
711                   long int *leap_correct, int *leap_hit)
712 {
713   register size_t i;
714
715   if (use_localtime)
716     {
717       struct ttinfo *info = fgfind_transition (timer);
718       fgdaylight = info->isdst;
719       fgtimezone = -info->offset;
720       for (i = 0;
721            i < num_types && i < sizeof (fgtzname) / sizeof (fgtzname[0]);
722            ++i)
723         fgtzname[types[i].isdst] = &zone_names[types[i].idx];
724       if (info->isdst < sizeof (fgtzname) / sizeof (fgtzname[0]))
725         fgtzname[info->isdst] = &zone_names[info->idx];
726     }
727
728   *leap_correct = 0L;
729   *leap_hit = 0;
730
731   /* Find the last leap second correction transition time before TIMER.  */
732   i = num_leaps;
733   do
734     if (i-- == 0)
735       return 1;
736   while (timer < leaps[i].transition);
737
738   /* Apply its correction.  */
739   *leap_correct = leaps[i].change;
740
741   if (timer == leaps[i].transition && /* Exactly at the transition time.  */
742       ((i == 0 && leaps[i].change > 0) ||
743        leaps[i].change > leaps[i - 1].change))
744     {
745       *leap_hit = 1;
746       while (i > 0 &&
747              leaps[i].transition == leaps[i - 1].transition + 1 &&
748              leaps[i].change == leaps[i - 1].change + 1)
749         {
750           ++*leap_hit;
751           --i;
752         }
753     }
754
755   return 1;
756 }
757
758 /**************************************************************************/
759
760 static struct ttinfo * fgfind_transition (time_t timer)
761 {
762   size_t i;
763
764   if (num_transitions == 0 || timer < transitions[0])
765     {
766       /* TIMER is before any transition (or there are no transitions).
767          Choose the first non-DST type
768          (or the first if they're all DST types).  */
769       i = 0;
770       while (i < num_types && types[i].isdst)
771         ++i;
772       if (i == num_types)
773         i = 0;
774     }
775   else
776     {
777       /* Find the first transition after TIMER, and
778          then pick the type of the transition before it.  */
779       for (i = 1; i < num_transitions; ++i)
780         if (timer < transitions[i])
781           break;
782       i = type_idxs[i - 1];
783     }
784
785   return &types[i];
786 }
787
788
789 /**************************************************************************/
790 void fgtzfile_read (const char *file)
791 {
792   // static const char default_tzdir[] = TZDIR;
793   size_t num_isstd, num_isgmt;
794   register FILE *f;
795   struct tzhead tzhead;
796   size_t chars;
797   register size_t i;
798   struct ttinfo *info;
799
800   use_fgtzfile = 0;
801
802   if (transitions != NULL)
803     free ((void *) transitions);
804   transitions = NULL;
805   if (type_idxs != NULL)
806     free ((void *) type_idxs);
807   type_idxs = NULL;
808   if (types != NULL)
809     free ((void *) types);
810   types = NULL;
811   if (zone_names != NULL)
812     free ((void *) zone_names);
813   zone_names = NULL;
814   if (leaps != NULL)
815     free ((void *) leaps);
816   leaps = NULL;
817
818   if (file == NULL)
819     /* No user specification; use the site-wide default.  */
820     file = TZDEFAULT;
821   else if (*file == '\0')
822     /* User specified the empty string; use UTC with no leap seconds.  */
823     return;
824   else
825     {
826       /* We must not allow to read an arbitrary file in a setuid
827          program.  So we fail for any file which is not in the
828          directory hierachy starting at TZDIR
829          and which is not the system wide default TZDEFAULT.  */
830       //if (libc_enable_secure
831       //  && ((*file == '/'
832       //       && memcmp (file, TZDEFAULT, sizeof TZDEFAULT)
833       //       && memcmp (file, default_tzdir, sizeof (default_tzdir) - 1))
834       //      || strstr (file, "../") != NULL))
835         /* This test is certainly a bit too restrictive but it should
836            catch all critical cases.  */
837       //return;
838     }
839
840 //   if (*file != '/') // if a relative path is used, append what file points to
841 //                     // to the path indicated by TZDIR.
842 //     {
843 //       const char *tzdir;
844 //       unsigned int len, tzdir_len;
845 //       char *_new;
846
847 //       tzdir = getenv ("TZDIR");
848 //       if (tzdir == NULL || *tzdir == '\0')
849 //      {
850 //        tzdir = default_tzdir;
851 //        tzdir_len = sizeof (default_tzdir) - 1;
852 //      }
853 //       else
854 //      tzdir_len = strlen (tzdir);
855 //       len = strlen (file) + 1;
856 //       _new = (char *) alloca (tzdir_len + 1 + len);
857 //       memcpy (_new, tzdir, tzdir_len);
858 //       _new[tzdir_len] = '/';
859 //       memcpy (&_new[tzdir_len + 1], file, len);
860 //       file = _new;
861 //     }
862
863   f = fopen (file, "rb");
864
865   if (f == NULL) {
866       perror( "fgtzfile_read(): " );
867       errno = 0;
868       return;
869   }
870
871   if (fread ((void *) &tzhead, sizeof (tzhead), 1, f) != 1)
872     goto lose;
873
874   num_transitions = (size_t) decode (tzhead.tzh_timecnt);
875   num_types = (size_t) decode (tzhead.tzh_typecnt);
876   chars = (size_t) decode (tzhead.tzh_charcnt);
877   num_leaps = (size_t) decode (tzhead.tzh_leapcnt);
878   num_isstd = (size_t) decode (tzhead.tzh_ttisstdcnt);
879   num_isgmt = (size_t) decode (tzhead.tzh_ttisgmtcnt);
880
881   if (num_transitions > 0)
882     {
883       transitions = (time_t *) malloc (num_transitions * sizeof(time_t));
884       if (transitions == NULL)
885         goto lose;
886       type_idxs = (unsigned char *) malloc (num_transitions);
887       if (type_idxs == NULL)
888         goto lose;
889     }
890   if (num_types > 0)
891     {
892       types = (struct ttinfo *) malloc (num_types * sizeof (struct ttinfo));
893       if (types == NULL)
894         goto lose;
895     }
896   if (chars > 0)
897     {
898       zone_names = (char *) malloc (chars);
899       if (zone_names == NULL)
900         goto lose;
901     }
902   if (num_leaps > 0)
903     {
904       leaps = (struct leap *) malloc (num_leaps * sizeof (struct leap));
905       if (leaps == NULL)
906         goto lose;
907     }
908
909   if (sizeof (time_t) < 4)
910       abort ();
911
912   if (fread(transitions, 4, num_transitions, f) != num_transitions ||
913       fread(type_idxs, 1, num_transitions, f) != num_transitions)
914     goto lose;
915
916   /* Check for bogus indices in the data file, so we can hereafter
917      safely use type_idxs[T] as indices into `types' and never crash.  */
918   for (i = 0; i < num_transitions; ++i)
919     if (type_idxs[i] >= num_types)
920       goto lose;
921
922   if (BYTE_ORDER != BIG_ENDIAN || sizeof (time_t) != 4)
923     {
924       /* Decode the transition times, stored as 4-byte integers in
925          network (big-endian) byte order.  We work from the end of
926          the array so as not to clobber the next element to be
927          processed when sizeof (time_t) > 4.  */
928       i = num_transitions;
929       while (i-- > 0)
930         transitions[i] = decode ((char *) transitions + i*4);
931     }
932
933   for (i = 0; i < num_types; ++i)
934     {
935       unsigned char x[4];
936       if (fread (x, 1, 4, f) != 4 ||
937           fread (&types[i].isdst, 1, 1, f) != 1 ||
938           fread (&types[i].idx, 1, 1, f) != 1)
939         goto lose;
940       if (types[i].idx >= chars) /* Bogus index in data file.  */
941         goto lose;
942       types[i].offset = (long int) decode (x);
943     }
944
945   if (fread (zone_names, 1, chars, f) != chars)
946     goto lose;
947
948   for (i = 0; i < num_leaps; ++i)
949     {
950       unsigned char x[4];
951       if (fread (x, 1, sizeof (x), f) != sizeof (x))
952         goto lose;
953       leaps[i].transition = (time_t) decode (x);
954       if (fread (x, 1, sizeof (x), f) != sizeof (x))
955         goto lose;
956       leaps[i].change = (long int) decode (x);
957     }
958
959   for (i = 0; i < num_isstd; ++i)
960     {
961       int c = getc (f);
962       if (c == EOF)
963         goto lose;
964       types[i].isstd = c != 0;
965     }
966   while (i < num_types)
967     types[i++].isstd = 0;
968
969   for (i = 0; i < num_isgmt; ++i)
970     {
971       int c = getc (f);
972       if (c == EOF)
973         goto lose;
974       types[i].isgmt = c != 0;
975     }
976   while (i < num_types)
977     types[i++].isgmt = 0;
978
979   fclose (f);
980
981   info = fgfind_transition (0);
982   for (i = 0; i < num_types && i < sizeof (fgtzname) / sizeof (fgtzname[0]);
983        ++i)
984     fgtzname[types[i].isdst] = tzstring (&zone_names[types[i].idx]);
985   if (info->isdst < sizeof (fgtzname) / sizeof (fgtzname[0]))
986     fgtzname[info->isdst] = tzstring (&zone_names[info->idx]);
987
988   fgcompute_tzname_max (chars);
989
990   use_fgtzfile = 1;
991   return;
992
993  lose:;
994   fclose(f);
995 }
996
997 /****************************************************************************/
998 static void fgcompute_tzname_max (size_t chars)
999 {
1000   // extern size_t tzname_cur_max; /* Defined in tzset.c. */
1001
1002   const char *p;
1003
1004   p = zone_names;
1005   do
1006     {
1007       const char *start = p;
1008       while (*p != '\0')
1009         ++p;
1010       if ((size_t) (p - start) > fgtzname_cur_max)
1011         fgtzname_cur_max = p - start;
1012     } while (++p < &zone_names[chars]);
1013 }
1014
1015 /**************************************************************************/
1016
1017 //#include <endian.h>
1018
1019 /* Decode the four bytes at PTR as a signed integer in network byte order.  */
1020 static inline int decode (const void *ptr)
1021 {
1022   if ((BYTE_ORDER == BIG_ENDIAN) && sizeof (int) == 4)
1023     return *(const int *) ptr;
1024   else
1025     {
1026       const unsigned char *p = (unsigned char *)ptr;
1027       int result = *p & (1 << (CHAR_BIT - 1)) ? ~0 : 0;
1028
1029       result = (result << 8) | *p++;
1030       result = (result << 8) | *p++;
1031       result = (result << 8) | *p++;
1032       result = (result << 8) | *p++;
1033
1034       return result;
1035     }
1036 }
1037
1038
1039
1040 #define SECS_PER_HOUR   (60 * 60)
1041 #define SECS_PER_DAY    (SECS_PER_HOUR * 24)
1042
1043 /* Compute the `struct tm' representation of *T,
1044    offset OFFSET seconds east of UTC,
1045    and store year, yday, mon, mday, wday, hour, min, sec into *TP.  */
1046
1047 void offtime (const time_t *t, long int offset, struct tm *tp)
1048   //    const time_t *t;
1049   // long int offset;
1050   // struct tm *tp;
1051 {
1052   register long int days, rem, y;
1053   register const unsigned short int *ip;
1054
1055   days = *t / SECS_PER_DAY;
1056   rem = *t % SECS_PER_DAY;
1057   rem += offset;
1058   while (rem < 0)
1059     {
1060       rem += SECS_PER_DAY;
1061       --days;
1062     }
1063   while (rem >= SECS_PER_DAY)
1064     {
1065       rem -= SECS_PER_DAY;
1066       ++days;
1067     }
1068   tp->tm_hour = rem / SECS_PER_HOUR;
1069   rem %= SECS_PER_HOUR;
1070   tp->tm_min = rem / 60;
1071   tp->tm_sec = rem % 60;
1072   /* January 1, 1970 was a Thursday.  */
1073   tp->tm_wday = (4 + days) % 7;
1074   if (tp->tm_wday < 0)
1075     tp->tm_wday += 7;
1076   y = 1970;
1077
1078 #define LEAPS_THRU_END_OF(y) ((y) / 4 - (y) / 100 + (y) / 400)
1079
1080   while (days < 0 || days >= (isleap (y) ? 366 : 365))
1081     {
1082       /* Guess a corrected year, assuming 365 days per year.  */
1083       long int yg = y + days / 365 - (days % 365 < 0);
1084
1085       /* Adjust DAYS and Y to match the guessed year.  */
1086       days -= ((yg - y) * 365
1087                + LEAPS_THRU_END_OF (yg - 1)
1088                - LEAPS_THRU_END_OF (y - 1));
1089       y = yg;
1090     }
1091   tp->tm_year = y - 1900;
1092   tp->tm_yday = days;
1093   ip = mon_yday[isleap(y)];
1094   for (y = 11; days < ip[y]; --y)
1095     continue;
1096   days -= ip[y];
1097   tp->tm_mon = y;
1098   tp->tm_mday = days + 1;
1099 }
1100
1101 /* Allocate a time zone string with given contents.
1102    The string will never be moved or deallocated.
1103    However, its contents may be shared with other such strings.  */
1104 char *tzstring (const char* string)
1105   //const char *string;
1106 {
1107   struct tzstring_head *h = &tzstring_list.head;
1108   size_t needed;
1109   char *p;
1110
1111   /* Look through time zone string list for a duplicate of this one.  */
1112   for (h = &tzstring_list.head;  ;  h = h->next)
1113     {
1114       for (p = (char *) (h + 1);  p[0] | p[1];  ++p)
1115         if (strcmp (p, string) == 0)
1116           return p;
1117       if (! h->next)
1118         break;
1119     }
1120
1121   /* No duplicate was found.  Copy to the end of this buffer if there's room;
1122      otherwise, append a large-enough new buffer to the list and use it.  */
1123   ++p;
1124   needed = strlen (string) + 2; /* Need 2 trailing '\0's after last string.  */
1125
1126   if ((size_t) ((char *) (h + 1) + tzstring_last_buffer_size - p) < needed)
1127     {
1128       size_t buffer_size = tzstring_last_buffer_size;
1129       while ((buffer_size *= 2) < needed)
1130         continue;
1131       if (! (h = h->next = (struct tzstring_head *)malloc (sizeof *h + buffer_size)))
1132         return NULL;
1133       h->next = NULL;
1134       tzstring_last_buffer_size = buffer_size;
1135       p = (char *) (h + 1);
1136     }
1137
1138   return strncpy (p, string, needed);
1139 }