085dfcaa33574b2514dae47f5f0b15ad7a830b5d
[platform/upstream/glibc.git] / time / tzset.c
1 /* Copyright (C) 1991, 92, 93, 94, 95, 96 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 ((char *std, char *dst,
35                                    long int stdoff, long int dstoff));
36 extern int __tz_compute __P ((time_t timer, const struct tm *tm));
37
38 char *__tzname[2] = { (char *) "GMT", (char *) "GMT" };
39 int __daylight = 0;
40 long int __timezone = 0L;
41
42 weak_alias (__tzname, tzname)
43 weak_alias (__daylight, daylight)
44 weak_alias (__timezone, timezone)
45
46
47 #define min(a, b)       ((a) < (b) ? (a) : (b))
48 #define max(a, b)       ((a) > (b) ? (a) : (b))
49 #define sign(x)         ((x) < 0 ? -1 : 1)
50
51
52 /* This structure contains all the information about a
53    timezone given in the POSIX standard TZ envariable.  */
54 typedef struct
55   {
56     char *name;
57
58     /* When to change.  */
59     enum { J0, J1, M } type;    /* Interpretation of:  */
60     unsigned short int m, n, d; /* Month, week, day.  */
61     unsigned int secs;          /* Time of day.  */
62
63     long int offset;            /* Seconds east of GMT (west if < 0).  */
64
65     /* We cache the computed time of change for a
66        given year so we don't have to recompute it.  */
67     time_t change;      /* When to change to this zone.  */
68     int computed_for;   /* Year above is computed for.  */
69   } tz_rule;
70
71 /* tz_rules[0] is standard, tz_rules[1] is daylight.  */
72 static tz_rule tz_rules[2];
73
74
75 static int compute_change __P ((tz_rule *rule, int year));
76 \f
77 static char *old_tz = NULL;
78
79 /* Interpret the TZ envariable.  */
80 void
81 __tzset_internal ()
82 {
83   register const char *tz;
84   register size_t l;
85   unsigned short int hh, mm, ss;
86   unsigned short int whichrule;
87
88   /* Examine the TZ environment variable.  */
89   tz = getenv ("TZ");
90
91   /* A leading colon means "implementation defined syntax".
92      We ignore the colon and always use the same algorithm:
93      try a data file, and if none exists parse the 1003.1 syntax.  */
94   if (tz && *tz == ':')
95     ++tz;
96
97   /* Check whether the value changes since the last run.  */
98   if (old_tz != NULL && tz != NULL && strcmp (tz, old_tz) == 0)
99     /* No change, simply return.  */
100     return;
101
102   /* Free old storage.  */
103   if (tz_rules[0].name != NULL && *tz_rules[0].name != '\0')
104     {
105       free((void *) tz_rules[0].name);
106       tz_rules[0].name = NULL;
107     }
108   if (tz_rules[1].name != NULL && *tz_rules[1].name != '\0' &&
109       tz_rules[1].name != tz_rules[0].name)
110     {
111       free((void *) tz_rules[1].name);
112       tz_rules[1].name = NULL;
113     }
114
115   /* Save the value of `tz'.  */
116   if (old_tz != NULL)
117     free (old_tz);
118   old_tz = tz ? __strdup (tz) : NULL;
119
120   /* Try to read a data file.  */
121   __tzfile_read (tz);
122   if (__use_tzfile)
123     return;
124
125   /* No data file found.  Default to UTC if nothing specified.  */
126
127   if (tz == NULL || *tz == '\0')
128     {
129       static const char UTC[] = "UTC";
130       size_t len = sizeof UTC;
131       tz_rules[0].name = (char *) malloc (len);
132       if (tz_rules[0].name == NULL)
133         return;
134       tz_rules[1].name = (char *) malloc (len);
135       if (tz_rules[1].name == NULL)
136         return;
137       memcpy ((void *) tz_rules[0].name, UTC, len);
138       memcpy ((void *) tz_rules[1].name, UTC, len);
139       tz_rules[0].type = tz_rules[1].type = J0;
140       tz_rules[0].m = tz_rules[0].n = tz_rules[0].d = 0;
141       tz_rules[1].m = tz_rules[1].n = tz_rules[1].d = 0;
142       tz_rules[0].secs = tz_rules[1].secs = 0;
143       tz_rules[0].offset = tz_rules[1].offset = 0L;
144       tz_rules[0].change = tz_rules[1].change = (time_t) -1;
145       tz_rules[0].computed_for = tz_rules[1].computed_for = 0;
146       return;
147     }
148
149   /* Clear out old state and reset to unnamed UTC.  */
150   memset (tz_rules, 0, sizeof tz_rules);
151   tz_rules[0].name = tz_rules[1].name = (char *) "";
152
153   /* Get the standard timezone name.  */
154   tz_rules[0].name = (char *) malloc (strlen (tz) + 1);
155   if (tz_rules[0].name == NULL)
156     {
157       /* Clear the old tz name so we will try again.  */
158       free (old_tz);
159       old_tz = NULL;
160       return;
161     }
162
163   if (sscanf(tz, "%[^0-9,+-]", tz_rules[0].name) != 1 ||
164       (l = strlen(tz_rules[0].name)) < 3)
165     {
166       free (tz_rules[0].name);
167       tz_rules[0].name = (char *) "";
168       return;
169     }
170
171   {
172     char *n = realloc ((void *) tz_rules[0].name, l + 1);
173     if (n != NULL)
174       tz_rules[0].name = n;
175   }
176
177   tz += l;
178
179   /* Figure out the standard offset from UTC.  */
180   if (*tz == '\0' || (*tz != '+' && *tz != '-' && !isdigit(*tz)))
181     return;
182
183   if (*tz == '-' || *tz == '+')
184     tz_rules[0].offset = *tz++ == '-' ? 1L : -1L;
185   else
186     tz_rules[0].offset = -1L;
187   switch (sscanf (tz, "%hu:%hu:%hu", &hh, &mm, &ss))
188     {
189     default:
190       return;
191     case 1:
192       mm = 0;
193     case 2:
194       ss = 0;
195     case 3:
196       break;
197     }
198   tz_rules[0].offset *= (min (ss, 59) + (min (mm, 59) * 60) +
199                          (min (hh, 23) * 60 * 60));
200
201   for (l = 0; l < 3; ++l)
202     {
203       while (isdigit(*tz))
204         ++tz;
205       if (l < 2 && *tz == ':')
206         ++tz;
207     }
208
209   /* Get the DST timezone name (if any).  */
210   if (*tz != '\0')
211     {
212       char *n = malloc (strlen (tz) + 1);
213       if (n != NULL)
214         {
215           tz_rules[1].name = n;
216           if (sscanf (tz, "%[^0-9,+-]", tz_rules[1].name) != 1 ||
217               (l = strlen (tz_rules[1].name)) < 3)
218             {
219               free (n);
220               tz_rules[1].name = (char *) "";
221               goto done_names;  /* Punt on name, set up the offsets.  */
222             }
223           n = realloc ((void *) tz_rules[1].name, l + 1);
224           if (n != NULL)
225             tz_rules[1].name = n;
226
227           tz += l;
228         }
229     }
230
231   /* Figure out the DST offset from GMT.  */
232   if (*tz == '-' || *tz == '+')
233     tz_rules[1].offset = *tz++ == '-' ? 1L : -1L;
234   else
235     tz_rules[1].offset = -1L;
236
237   switch (sscanf (tz, "%hu:%hu:%hu", &hh, &mm, &ss))
238     {
239     default:
240       /* Default to one hour later than standard time.  */
241       tz_rules[1].offset = tz_rules[0].offset + (60 * 60);
242       break;
243
244     case 1:
245       mm = 0;
246     case 2:
247       ss = 0;
248     case 3:
249       tz_rules[1].offset *= (min (ss, 59) + (min (mm, 59) * 60) +
250                              (min (hh, 23) * (60 * 60)));
251       break;
252     }
253   for (l = 0; l < 3; ++l)
254     {
255       while (isdigit (*tz))
256         ++tz;
257       if (l < 2 && *tz == ':')
258         ++tz;
259     }
260
261  done_names:
262
263   if (*tz == '\0' || (tz[0] == ',' && tz[1] == '\0'))
264     {
265       /* There is no rule.  See if there is a default rule file.  */
266       __tzfile_default (tz_rules[0].name, tz_rules[1].name,
267                         tz_rules[0].offset, tz_rules[1].offset);
268       if (__use_tzfile)
269         {
270           free (old_tz);
271           old_tz = NULL;
272           return;
273         }
274     }
275
276   /* Figure out the standard <-> DST rules.  */
277   for (whichrule = 0; whichrule < 2; ++whichrule)
278     {
279       register tz_rule *tzr = &tz_rules[whichrule];
280
281       if (*tz == ',')
282         {
283           ++tz;
284           if (*tz == '\0')
285             return;
286         }
287
288       /* Get the date of the change.  */
289       if (*tz == 'J' || isdigit (*tz))
290         {
291           char *end;
292           tzr->type = *tz == 'J' ? J1 : J0;
293           if (tzr->type == J1 && !isdigit (*++tz))
294             return;
295           tzr->d = (unsigned short int) strtoul (tz, &end, 10);
296           if (end == tz || tzr->d > 365)
297             return;
298           else if (tzr->type == J1 && tzr->d == 0)
299             return;
300           tz = end;
301         }
302       else if (*tz == 'M')
303         {
304           int n;
305           tzr->type = M;
306           if (sscanf (tz, "M%hu.%hu.%hu%n",
307                       &tzr->m, &tzr->n, &tzr->d, &n) != 3 ||
308               tzr->m < 1 || tzr->m > 12 ||
309               tzr->n < 1 || tzr->n > 5 || tzr->d > 6)
310             return;
311           tz += n;
312         }
313       else if (*tz == '\0')
314         {
315           /* United States Federal Law, the equivalent of "M4.1.0,M10.5.0".  */
316           tzr->type = M;
317           if (tzr == &tz_rules[0])
318             {
319               tzr->m = 4;
320               tzr->n = 1;
321               tzr->d = 0;
322             }
323           else
324             {
325               tzr->m = 10;
326               tzr->n = 5;
327               tzr->d = 0;
328             }
329         }
330       else
331         return;
332
333       if (*tz != '\0' && *tz != '/' && *tz != ',')
334         return;
335       else if (*tz == '/')
336         {
337           /* Get the time of day of the change.  */
338           ++tz;
339           if (*tz == '\0')
340             return;
341           switch (sscanf (tz, "%hu:%hu:%hu", &hh, &mm, &ss))
342             {
343             default:
344               hh = 2;           /* Default to 2:00 AM.  */
345             case 1:
346               mm = 0;
347             case 2:
348               ss = 0;
349             case 3:
350               break;
351             }
352           for (l = 0; l < 3; ++l)
353             {
354               while (isdigit (*tz))
355                 ++tz;
356               if (l < 2 && *tz == ':')
357                 ++tz;
358             }
359           tzr->secs = (hh * 60 * 60) + (mm * 60) + ss;
360         }
361       else
362         /* Default to 2:00 AM.  */
363         tzr->secs = 2 * 60 * 60;
364
365       tzr->computed_for = -1;
366     }
367 }
368 \f
369 /* Maximum length of a timezone name.  __tz_compute keeps this up to date
370    (never decreasing it) when ! __use_tzfile.
371    tzfile.c keeps it up to date when __use_tzfile.  */
372 size_t __tzname_cur_max;
373
374 long int
375 __tzname_max ()
376 {
377   __tzset_internal ();
378
379   return __tzname_cur_max;
380 }
381 \f
382 /* Figure out the exact time (as a time_t) in YEAR
383    when the change described by RULE will occur and
384    put it in RULE->change, saving YEAR in RULE->computed_for.
385    Return nonzero if successful, zero on failure.  */
386 static int
387 compute_change (rule, year)
388      tz_rule *rule;
389      int year;
390 {
391   register time_t t;
392   int y;
393
394   if (year != -1 && rule->computed_for == year)
395     /* Operations on times in 1969 will be slower.  Oh well.  */
396     return 1;
397
398   /* First set T to January 1st, 0:00:00 GMT in YEAR.  */
399   t = 0;
400   for (y = 1970; y < year; ++y)
401     t += SECSPERDAY * (__isleap (y) ? 366 : 365);
402
403   switch (rule->type)
404     {
405     case J1:
406       /* Jn - Julian day, 1 == January 1, 60 == March 1 even in leap years.
407          In non-leap years, or if the day number is 59 or less, just
408          add SECSPERDAY times the day number-1 to the time of
409          January 1, midnight, to get the day.  */
410       t += (rule->d - 1) * SECSPERDAY;
411       if (rule->d >= 60 && __isleap (year))
412         t += SECSPERDAY;
413       break;
414
415     case J0:
416       /* n - Day of year.
417          Just add SECSPERDAY times the day number to the time of Jan 1st.  */
418       t += rule->d * SECSPERDAY;
419       break;
420
421     case M:
422       /* Mm.n.d - Nth "Dth day" of month M.  */
423       {
424         register int i, d, m1, yy0, yy1, yy2, dow;
425         register const unsigned short int *myday =
426           &__mon_yday[__isleap (year)][rule->m];
427
428         /* First add SECSPERDAY for each day in months before M.  */
429         t += myday[-1] * SECSPERDAY;
430
431         /* Use Zeller's Congruence to get day-of-week of first day of month. */
432         m1 = (rule->m + 9) % 12 + 1;
433         yy0 = (rule->m <= 2) ? (year - 1) : year;
434         yy1 = yy0 / 100;
435         yy2 = yy0 % 100;
436         dow = ((26 * m1 - 2) / 10 + 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
437         if (dow < 0)
438           dow += 7;
439
440         /* DOW is the day-of-week of the first day of the month.  Get the
441            day-of-month (zero-origin) of the first DOW day of the month.  */
442         d = rule->d - dow;
443         if (d < 0)
444           d += 7;
445         for (i = 1; i < rule->n; ++i)
446           {
447             if (d + 7 >= myday[0] - myday[-1])
448               break;
449             d += 7;
450           }
451
452         /* D is the day-of-month (zero-origin) of the day we want.  */
453         t += d * SECSPERDAY;
454       }
455       break;
456     }
457
458   /* T is now the Epoch-relative time of 0:00:00 GMT on the day we want.
459      Just add the time of day and local offset from GMT, and we're done.  */
460
461   rule->change = t - rule->offset + rule->secs;
462   rule->computed_for = year;
463   return 1;
464 }
465
466
467 /* Figure out the correct timezone for *TIMER and TM (which must be the same)
468    and set `__tzname', `__timezone', and `__daylight' accordingly.
469    Return nonzero on success, zero on failure.  */
470 int
471 __tz_compute (timer, tm)
472      time_t timer;
473      const struct tm *tm;
474 {
475   __tzset_internal ();
476
477   if (! compute_change (&tz_rules[0], 1900 + tm->tm_year) ||
478       ! compute_change (&tz_rules[1], 1900 + tm->tm_year))
479     return 0;
480
481   __daylight = timer >= tz_rules[0].change && timer < tz_rules[1].change;
482   __timezone = tz_rules[__daylight ? 1 : 0].offset;
483   __tzname[0] = (char *) tz_rules[0].name;
484   __tzname[1] = (char *) tz_rules[1].name;
485
486   {
487     /* Keep __tzname_cur_max up to date.  */
488     size_t len0 = strlen (__tzname[0]);
489     size_t len1 = strlen (__tzname[1]);
490     if (len0 > __tzname_cur_max)
491       __tzname_cur_max = len0;
492     if (len1 > __tzname_cur_max)
493       __tzname_cur_max = len1;
494   }
495
496   return 1;
497 }
498 \f
499 #include <libc-lock.h>
500
501 /* This locks all the state variables in tzfile.c and this file.  */
502 __libc_lock_define (, __tzset_lock)
503
504 /* Reinterpret the TZ environment variable and set `tzname'.  */
505 #undef tzset
506
507 void
508 __tzset (void)
509 {
510   __libc_lock_lock (__tzset_lock);
511
512   __tzset_internal ();
513
514   if (!__use_tzfile)
515     {
516       /* Set `tzname'.  */
517       __tzname[0] = (char *) tz_rules[0].name;
518       __tzname[1] = (char *) tz_rules[1].name;
519     }
520
521   __libc_lock_unlock (__tzset_lock);
522 }
523 weak_alias (__tzset, tzset)