Update.
[platform/upstream/glibc.git] / time / tzset.c
1 /* Copyright (C) 1991, 92, 93, 94, 95, 96, 97 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3
4    The GNU C Library is free software; you can redistribute it and/or
5    modify it under the terms of the GNU Library General Public License as
6    published by the Free Software Foundation; either version 2 of the
7    License, or (at your option) any later version.
8
9    The GNU C Library is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    Library General Public License for more details.
13
14    You should have received a copy of the GNU Library General Public
15    License along with the GNU C Library; see the file COPYING.LIB.  If not,
16    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17    Boston, MA 02111-1307, USA.  */
18
19 #include <ctype.h>
20 #include <stddef.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <time.h>
25
26 /* Defined in mktime.c.  */
27 extern const unsigned short int __mon_yday[2][13];
28
29 #define NOID
30 #include "tzfile.h"
31
32 extern int __use_tzfile;
33 extern void __tzfile_read __P ((const char *file));
34 extern void __tzfile_default __P ((const char *std, const char *dst,
35                                    long int stdoff, long int dstoff));
36 extern char * __tzstring __P ((const char *string));
37 extern int __tz_compute __P ((time_t timer, const struct tm *tm));
38
39 char *__tzname[2] = { (char *) "GMT", (char *) "GMT" };
40 int __daylight = 0;
41 long int __timezone = 0L;
42
43 weak_alias (__tzname, tzname)
44 weak_alias (__daylight, daylight)
45 weak_alias (__timezone, timezone)
46
47
48 #define min(a, b)       ((a) < (b) ? (a) : (b))
49 #define max(a, b)       ((a) > (b) ? (a) : (b))
50 #define sign(x)         ((x) < 0 ? -1 : 1)
51
52
53 /* This structure contains all the information about a
54    timezone given in the POSIX standard TZ envariable.  */
55 typedef struct
56   {
57     const char *name;
58
59     /* When to change.  */
60     enum { J0, J1, M } type;    /* Interpretation of:  */
61     unsigned short int m, n, d; /* Month, week, day.  */
62     unsigned int secs;          /* Time of day.  */
63
64     long int offset;            /* Seconds east of GMT (west if < 0).  */
65
66     /* We cache the computed time of change for a
67        given year so we don't have to recompute it.  */
68     time_t change;      /* When to change to this zone.  */
69     int computed_for;   /* Year above is computed for.  */
70   } tz_rule;
71
72 /* tz_rules[0] is standard, tz_rules[1] is daylight.  */
73 static tz_rule tz_rules[2];
74
75
76 static int compute_change __P ((tz_rule *rule, int year));
77 \f
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 /* First in a list of buffers containing time zone strings.
88    All the buffers but the last are read-only.  */
89 static struct
90 {
91   struct tzstring_head head;
92   char data[48];
93 } tzstring_list;
94
95 /* Size of the last buffer in the list, not counting its header.  */
96 static size_t tzstring_last_buffer_size = sizeof tzstring_list.data;
97
98 /* Allocate a time zone string with given contents.
99    The string will never be moved or deallocated.
100    However, its contents may be shared with other such strings.  */
101 char *
102 __tzstring (string)
103      const char *string;
104 {
105   struct tzstring_head *h = &tzstring_list.head;
106   size_t needed;
107   char *p;
108
109   /* Look through time zone string list for a duplicate of this one.  */
110   for (h = &tzstring_list.head;  ;  h = h->next)
111     {
112       for (p = (char *) (h + 1);  p[0] | p[1];  ++p)
113         if (strcmp (p, string) == 0)
114           return p;
115       if (! h->next)
116         break;
117     }
118
119   /* No duplicate was found.  Copy to the end of this buffer if there's room;
120      otherwise, append a large-enough new buffer to the list and use it.  */
121   ++p;
122   needed = strlen (string) + 2; /* Need 2 trailing '\0's after last string.  */
123
124   if ((size_t) ((char *) (h + 1) + tzstring_last_buffer_size - p) < needed)
125     {
126       size_t buffer_size = tzstring_last_buffer_size;
127       while ((buffer_size *= 2) < needed)
128         continue;
129       if (! (h = h->next = malloc (sizeof *h + buffer_size)))
130         return NULL;
131       h->next = NULL;
132       tzstring_last_buffer_size = buffer_size;
133       p = (char *) (h + 1);
134     }
135
136   return strncpy (p, string, needed);
137 }
138 \f
139 static char *old_tz = NULL;
140
141 /* Interpret the TZ envariable.  */
142 void __tzset_internal __P ((int always));
143 void
144 __tzset_internal (always)
145      int always;
146 {
147   static int is_initialized = 0;
148   register const char *tz;
149   register size_t l;
150   char *tzbuf;
151   unsigned short int hh, mm, ss;
152   unsigned short int whichrule;
153
154   if (is_initialized && !always)
155     return;
156   is_initialized = 1;
157
158   /* Examine the TZ environment variable.  */
159   tz = getenv ("TZ");
160   if (tz == NULL)
161     /* No user specification; use the site-wide default.  */
162     tz = TZDEFAULT;
163   else if (*tz == '\0')
164     /* User specified the empty string; use UTC explicitly.  */
165     tz = "Universal";
166
167   /* A leading colon means "implementation defined syntax".
168      We ignore the colon and always use the same algorithm:
169      try a data file, and if none exists parse the 1003.1 syntax.  */
170   if (tz && *tz == ':')
171     ++tz;
172
173   /* Check whether the value changes since the last run.  */
174   if (old_tz != NULL && tz != NULL && strcmp (tz, old_tz) == 0)
175     /* No change, simply return.  */
176     return;
177
178   tz_rules[0].name = NULL;
179   tz_rules[1].name = NULL;
180
181   /* Save the value of `tz'.  */
182   if (old_tz != NULL)
183     free (old_tz);
184   old_tz = tz ? __strdup (tz) : NULL;
185
186   /* Try to read a data file.  */
187   __tzfile_read (tz);
188   if (__use_tzfile)
189     return;
190
191   /* No data file found.  Default to UTC if nothing specified.  */
192
193   if (tz == NULL || *tz == '\0')
194     {
195       tz_rules[0].name = tz_rules[1].name = "UTC";
196       tz_rules[0].type = tz_rules[1].type = J0;
197       tz_rules[0].m = tz_rules[0].n = tz_rules[0].d = 0;
198       tz_rules[1].m = tz_rules[1].n = tz_rules[1].d = 0;
199       tz_rules[0].secs = tz_rules[1].secs = 0;
200       tz_rules[0].offset = tz_rules[1].offset = 0L;
201       tz_rules[0].change = tz_rules[1].change = (time_t) -1;
202       tz_rules[0].computed_for = tz_rules[1].computed_for = 0;
203       return;
204     }
205
206   /* Clear out old state and reset to unnamed UTC.  */
207   memset (tz_rules, 0, sizeof tz_rules);
208   tz_rules[0].name = tz_rules[1].name = "";
209
210   /* Get the standard timezone name.  */
211   tzbuf = malloc (strlen (tz) + 1);
212   if (! tzbuf)
213     {
214       /* Clear the old tz name so we will try again.  */
215       free (old_tz);
216       old_tz = NULL;
217       return;
218     }
219
220   if (sscanf (tz, "%[^0-9,+-]", tzbuf) != 1 ||
221       (l = strlen (tzbuf)) < 3)
222     {
223       free (tzbuf);
224       return;
225     }
226
227   tz_rules[0].name = __tzstring (tzbuf);
228
229   tz += l;
230
231   /* Figure out the standard offset from UTC.  */
232   if (*tz == '\0' || (*tz != '+' && *tz != '-' && !isdigit (*tz)))
233     {
234       free (tzbuf);
235       return;
236     }
237
238   if (*tz == '-' || *tz == '+')
239     tz_rules[0].offset = *tz++ == '-' ? 1L : -1L;
240   else
241     tz_rules[0].offset = -1L;
242   switch (sscanf (tz, "%hu:%hu:%hu", &hh, &mm, &ss))
243     {
244     default:
245       free (tzbuf);
246       return;
247     case 1:
248       mm = 0;
249     case 2:
250       ss = 0;
251     case 3:
252       break;
253     }
254   tz_rules[0].offset *= (min (ss, 59) + (min (mm, 59) * 60) +
255                          (min (hh, 23) * 60 * 60));
256
257   for (l = 0; l < 3; ++l)
258     {
259       while (isdigit(*tz))
260         ++tz;
261       if (l < 2 && *tz == ':')
262         ++tz;
263     }
264
265   /* Get the DST timezone name (if any).  */
266   if (*tz != '\0')
267     {
268       char *n = tzbuf + strlen (tzbuf) + 1;
269       if (sscanf (tz, "%[^0-9,+-]", n) != 1 ||
270           (l = strlen (n)) < 3)
271         goto done_names;        /* Punt on name, set up the offsets.  */
272
273       tz_rules[1].name = __tzstring (n);
274
275       tz += l;
276
277       /* Figure out the DST offset from GMT.  */
278       if (*tz == '-' || *tz == '+')
279         tz_rules[1].offset = *tz++ == '-' ? 1L : -1L;
280       else
281         tz_rules[1].offset = -1L;
282
283       switch (sscanf (tz, "%hu:%hu:%hu", &hh, &mm, &ss))
284         {
285         default:
286           /* Default to one hour later than standard time.  */
287           tz_rules[1].offset = tz_rules[0].offset + (60 * 60);
288           break;
289
290         case 1:
291           mm = 0;
292         case 2:
293           ss = 0;
294         case 3:
295           tz_rules[1].offset *= (min (ss, 59) + (min (mm, 59) * 60) +
296                                  (min (hh, 23) * (60 * 60)));
297           break;
298         }
299       for (l = 0; l < 3; ++l)
300         {
301           while (isdigit (*tz))
302             ++tz;
303           if (l < 2 && *tz == ':')
304             ++tz;
305         }
306       if (*tz == '\0' || (tz[0] == ',' && tz[1] == '\0'))
307         {
308           /* There is no rule.  See if there is a default rule file.  */
309           __tzfile_default (tz_rules[0].name, tz_rules[1].name,
310                             tz_rules[0].offset, tz_rules[1].offset);
311           if (__use_tzfile)
312             {
313               free (old_tz);
314               old_tz = NULL;
315               free (tzbuf);
316               return;
317             }
318         }
319     }
320   else
321     {
322       /* There is no DST.  */
323       tz_rules[1].name = tz_rules[0].name;
324       free (tzbuf);
325       return;
326     }
327
328  done_names:
329   free (tzbuf);
330
331   /* Figure out the standard <-> DST rules.  */
332   for (whichrule = 0; whichrule < 2; ++whichrule)
333     {
334       register tz_rule *tzr = &tz_rules[whichrule];
335
336       /* Ignore comma to support string following the incorrect
337          specification in early POSIX.1 printings.  */
338       tz += *tz == ',';
339
340       /* Get the date of the change.  */
341       if (*tz == 'J' || isdigit (*tz))
342         {
343           char *end;
344           tzr->type = *tz == 'J' ? J1 : J0;
345           if (tzr->type == J1 && !isdigit (*++tz))
346             return;
347           tzr->d = (unsigned short int) strtoul (tz, &end, 10);
348           if (end == tz || tzr->d > 365)
349             return;
350           else if (tzr->type == J1 && tzr->d == 0)
351             return;
352           tz = end;
353         }
354       else if (*tz == 'M')
355         {
356           int n;
357           tzr->type = M;
358           if (sscanf (tz, "M%hu.%hu.%hu%n",
359                       &tzr->m, &tzr->n, &tzr->d, &n) != 3 ||
360               tzr->m < 1 || tzr->m > 12 ||
361               tzr->n < 1 || tzr->n > 5 || tzr->d > 6)
362             return;
363           tz += n;
364         }
365       else if (*tz == '\0')
366         {
367           /* United States Federal Law, the equivalent of "M4.1.0,M10.5.0".  */
368           tzr->type = M;
369           if (tzr == &tz_rules[0])
370             {
371               tzr->m = 4;
372               tzr->n = 1;
373               tzr->d = 0;
374             }
375           else
376             {
377               tzr->m = 10;
378               tzr->n = 5;
379               tzr->d = 0;
380             }
381         }
382       else
383         return;
384
385       if (*tz != '\0' && *tz != '/' && *tz != ',')
386         return;
387       else if (*tz == '/')
388         {
389           /* Get the time of day of the change.  */
390           ++tz;
391           if (*tz == '\0')
392             return;
393           switch (sscanf (tz, "%hu:%hu:%hu", &hh, &mm, &ss))
394             {
395             default:
396               hh = 2;           /* Default to 2:00 AM.  */
397             case 1:
398               mm = 0;
399             case 2:
400               ss = 0;
401             case 3:
402               break;
403             }
404           for (l = 0; l < 3; ++l)
405             {
406               while (isdigit (*tz))
407                 ++tz;
408               if (l < 2 && *tz == ':')
409                 ++tz;
410             }
411           tzr->secs = (hh * 60 * 60) + (mm * 60) + ss;
412         }
413       else
414         /* Default to 2:00 AM.  */
415         tzr->secs = 2 * 60 * 60;
416
417       tzr->computed_for = -1;
418     }
419 }
420 \f
421 /* Maximum length of a timezone name.  __tz_compute keeps this up to date
422    (never decreasing it) when ! __use_tzfile.
423    tzfile.c keeps it up to date when __use_tzfile.  */
424 size_t __tzname_cur_max;
425
426 long int
427 __tzname_max ()
428 {
429   __tzset_internal (0);
430
431   return __tzname_cur_max;
432 }
433 \f
434 /* Figure out the exact time (as a time_t) in YEAR
435    when the change described by RULE will occur and
436    put it in RULE->change, saving YEAR in RULE->computed_for.
437    Return nonzero if successful, zero on failure.  */
438 static int
439 compute_change (rule, year)
440      tz_rule *rule;
441      int year;
442 {
443   register time_t t;
444   int y;
445
446   if (year != -1 && rule->computed_for == year)
447     /* Operations on times in 1969 will be slower.  Oh well.  */
448     return 1;
449
450   /* First set T to January 1st, 0:00:00 GMT in YEAR.  */
451   t = 0;
452   for (y = 1970; y < year; ++y)
453     t += SECSPERDAY * (__isleap (y) ? 366 : 365);
454
455   switch (rule->type)
456     {
457     case J1:
458       /* Jn - Julian day, 1 == January 1, 60 == March 1 even in leap years.
459          In non-leap years, or if the day number is 59 or less, just
460          add SECSPERDAY times the day number-1 to the time of
461          January 1, midnight, to get the day.  */
462       t += (rule->d - 1) * SECSPERDAY;
463       if (rule->d >= 60 && __isleap (year))
464         t += SECSPERDAY;
465       break;
466
467     case J0:
468       /* n - Day of year.
469          Just add SECSPERDAY times the day number to the time of Jan 1st.  */
470       t += rule->d * SECSPERDAY;
471       break;
472
473     case M:
474       /* Mm.n.d - Nth "Dth day" of month M.  */
475       {
476         register int i, d, m1, yy0, yy1, yy2, dow;
477         register const unsigned short int *myday =
478           &__mon_yday[__isleap (year)][rule->m];
479
480         /* First add SECSPERDAY for each day in months before M.  */
481         t += myday[-1] * SECSPERDAY;
482
483         /* Use Zeller's Congruence to get day-of-week of first day of month. */
484         m1 = (rule->m + 9) % 12 + 1;
485         yy0 = (rule->m <= 2) ? (year - 1) : year;
486         yy1 = yy0 / 100;
487         yy2 = yy0 % 100;
488         dow = ((26 * m1 - 2) / 10 + 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
489         if (dow < 0)
490           dow += 7;
491
492         /* DOW is the day-of-week of the first day of the month.  Get the
493            day-of-month (zero-origin) of the first DOW day of the month.  */
494         d = rule->d - dow;
495         if (d < 0)
496           d += 7;
497         for (i = 1; i < rule->n; ++i)
498           {
499             if (d + 7 >= myday[0] - myday[-1])
500               break;
501             d += 7;
502           }
503
504         /* D is the day-of-month (zero-origin) of the day we want.  */
505         t += d * SECSPERDAY;
506       }
507       break;
508     }
509
510   /* T is now the Epoch-relative time of 0:00:00 GMT on the day we want.
511      Just add the time of day and local offset from GMT, and we're done.  */
512
513   rule->change = t - rule->offset + rule->secs;
514   rule->computed_for = year;
515   return 1;
516 }
517
518
519 /* Figure out the correct timezone for *TIMER and TM (which must be the same)
520    and set `__tzname', `__timezone', and `__daylight' accordingly.
521    Return nonzero on success, zero on failure.  */
522 int
523 __tz_compute (timer, tm)
524      time_t timer;
525      const struct tm *tm;
526 {
527   __tzset_internal (0);
528
529   if (! compute_change (&tz_rules[0], 1900 + tm->tm_year) ||
530       ! compute_change (&tz_rules[1], 1900 + tm->tm_year))
531     return 0;
532
533   __daylight = timer >= tz_rules[0].change && timer < tz_rules[1].change;
534   __timezone = tz_rules[__daylight ? 1 : 0].offset;
535   __tzname[0] = (char *) tz_rules[0].name;
536   __tzname[1] = (char *) tz_rules[1].name;
537
538   {
539     /* Keep __tzname_cur_max up to date.  */
540     size_t len0 = strlen (__tzname[0]);
541     size_t len1 = strlen (__tzname[1]);
542     if (len0 > __tzname_cur_max)
543       __tzname_cur_max = len0;
544     if (len1 > __tzname_cur_max)
545       __tzname_cur_max = len1;
546   }
547
548   return 1;
549 }
550 \f
551 #include <bits/libc-lock.h>
552
553 /* This locks all the state variables in tzfile.c and this file.  */
554 __libc_lock_define (, __tzset_lock)
555
556 /* Reinterpret the TZ environment variable and set `tzname'.  */
557 #undef tzset
558
559 void
560 __tzset (void)
561 {
562   __libc_lock_lock (__tzset_lock);
563
564   __tzset_internal (1);
565
566   if (!__use_tzfile)
567     {
568       /* Set `tzname'.  */
569       __tzname[0] = (char *) tz_rules[0].name;
570       __tzname[1] = (char *) tz_rules[1].name;
571     }
572
573   __libc_lock_unlock (__tzset_lock);
574 }
575 weak_alias (__tzset, tzset)