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