Add memchr tests for n == 0
[glibc.git] / time / tzset.c
blob8868e9aada0b2b114869baa6618842099c570481
1 /* Copyright (C) 1991-2017 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
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 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <http://www.gnu.org/licenses/>. */
18 #include <ctype.h>
19 #include <errno.h>
20 #include <libc-lock.h>
21 #include <stdbool.h>
22 #include <stddef.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <time.h>
28 #include <timezone/tzfile.h>
30 char *__tzname[2] = { (char *) "GMT", (char *) "GMT" };
31 int __daylight = 0;
32 long int __timezone = 0L;
34 weak_alias (__tzname, tzname)
35 weak_alias (__daylight, daylight)
36 weak_alias (__timezone, timezone)
38 /* This locks all the state variables in tzfile.c and this file. */
39 __libc_lock_define_initialized (static, tzset_lock)
41 /* This structure contains all the information about a
42 timezone given in the POSIX standard TZ envariable. */
43 typedef struct
45 const char *name;
47 /* When to change. */
48 enum { J0, J1, M } type; /* Interpretation of: */
49 unsigned short int m, n, d; /* Month, week, day. */
50 int secs; /* Time of day. */
52 long int offset; /* Seconds east of GMT (west if < 0). */
54 /* We cache the computed time of change for a
55 given year so we don't have to recompute it. */
56 time_t change; /* When to change to this zone. */
57 int computed_for; /* Year above is computed for. */
58 } tz_rule;
60 /* tz_rules[0] is standard, tz_rules[1] is daylight. */
61 static tz_rule tz_rules[2];
64 static void compute_change (tz_rule *rule, int year) __THROW internal_function;
65 static void tzset_internal (int always);
67 /* List of buffers containing time zone strings. */
68 struct tzstring_l
70 struct tzstring_l *next;
71 size_t len; /* strlen(data) - doesn't count terminating NUL! */
72 char data[0];
75 static struct tzstring_l *tzstring_list;
77 /* Allocate a permanent home for the first LEN characters of S. It
78 will never be moved or deallocated, but may share space with other
79 strings. Don't modify the returned string. */
80 static char *
81 __tzstring_len (const char *s, size_t len)
83 char *p;
84 struct tzstring_l *t, *u, *new;
86 /* Walk the list and look for a match. If this string is the same
87 as the end of an already-allocated string, it can share space. */
88 for (u = t = tzstring_list; t; u = t, t = t->next)
89 if (len <= t->len)
91 p = &t->data[t->len - len];
92 if (memcmp (s, p, len) == 0)
93 return p;
96 /* Not found; allocate a new buffer. */
97 new = malloc (sizeof (struct tzstring_l) + len + 1);
98 if (!new)
99 return NULL;
101 new->next = NULL;
102 new->len = len;
103 memcpy (new->data, s, len);
104 new->data[len] = '\0';
106 if (u)
107 u->next = new;
108 else
109 tzstring_list = new;
111 return new->data;
114 /* Allocate a permanent home for S. It will never be moved or
115 deallocated, but may share space with other strings. Don't modify
116 the returned string. */
117 char *
118 __tzstring (const char *s)
120 return __tzstring_len (s, strlen (s));
123 static char *old_tz;
125 static void
126 internal_function
127 update_vars (void)
129 __daylight = tz_rules[0].offset != tz_rules[1].offset;
130 __timezone = -tz_rules[0].offset;
131 __tzname[0] = (char *) tz_rules[0].name;
132 __tzname[1] = (char *) tz_rules[1].name;
136 static unsigned int
137 compute_offset (unsigned int ss, unsigned int mm, unsigned int hh)
139 if (ss > 59)
140 ss = 59;
141 if (mm > 59)
142 mm = 59;
143 if (hh > 24)
144 hh = 24;
145 return ss + mm * 60 + hh * 60 * 60;
148 /* Parses the time zone name at *TZP, and writes a pointer to an
149 interned string to tz_rules[WHICHRULE].name. On success, advances
150 *TZP, and returns true. Returns false otherwise. */
151 static bool
152 parse_tzname (const char **tzp, int whichrule)
154 const char *start = *tzp;
155 const char *p = start;
156 while (('a' <= *p && *p <= 'z')
157 || ('A' <= *p && *p <= 'Z'))
158 ++p;
159 size_t len = p - start;
160 if (len < 3)
162 p = *tzp;
163 if (__glibc_unlikely (*p++ != '<'))
164 return false;
165 start = p;
166 while (('a' <= *p && *p <= 'z')
167 || ('A' <= *p && *p <= 'Z')
168 || ('0' <= *p && *p <= '9')
169 || *p == '+' || *p == '-')
170 ++p;
171 len = p - start;
172 if (*p++ != '>' || len < 3)
173 return false;
176 const char *name = __tzstring_len (start, len);
177 if (name == NULL)
178 return false;
179 tz_rules[whichrule].name = name;
181 *tzp = p;
182 return true;
185 /* Parses the time zone offset at *TZP, and writes it to
186 tz_rules[WHICHRULE].offset. Returns true if the parse was
187 successful. */
188 static bool
189 parse_offset (const char **tzp, int whichrule)
191 const char *tz = *tzp;
192 if (whichrule == 0
193 && (*tz == '\0' || (*tz != '+' && *tz != '-' && !isdigit (*tz))))
194 return false;
196 long sign;
197 if (*tz == '-' || *tz == '+')
198 sign = *tz++ == '-' ? 1L : -1L;
199 else
200 sign = -1L;
201 *tzp = tz;
203 unsigned short int hh;
204 unsigned short mm = 0;
205 unsigned short ss = 0;
206 int consumed = 0;
207 if (sscanf (tz, "%hu%n:%hu%n:%hu%n",
208 &hh, &consumed, &mm, &consumed, &ss, &consumed) > 0)
209 tz_rules[whichrule].offset = sign * compute_offset (ss, mm, hh);
210 else
211 /* Nothing could be parsed. */
212 if (whichrule == 0)
214 /* Standard time defaults to offset zero. */
215 tz_rules[0].offset = 0;
216 return false;
218 else
219 /* DST defaults to one hour later than standard time. */
220 tz_rules[1].offset = tz_rules[0].offset + (60 * 60);
221 *tzp = tz + consumed;
222 return true;
225 /* Parses the standard <-> DST rules at *TZP. Updates
226 tz_rule[WHICHRULE]. On success, advances *TZP and returns true.
227 Otherwise, returns false. */
228 static bool
229 parse_rule (const char **tzp, int whichrule)
231 const char *tz = *tzp;
232 tz_rule *tzr = &tz_rules[whichrule];
234 /* Ignore comma to support string following the incorrect
235 specification in early POSIX.1 printings. */
236 tz += *tz == ',';
238 /* Get the date of the change. */
239 if (*tz == 'J' || isdigit (*tz))
241 char *end;
242 tzr->type = *tz == 'J' ? J1 : J0;
243 if (tzr->type == J1 && !isdigit (*++tz))
244 return false;
245 unsigned long int d = strtoul (tz, &end, 10);
246 if (end == tz || d > 365)
247 return false;
248 if (tzr->type == J1 && d == 0)
249 return false;
250 tzr->d = d;
251 tz = end;
253 else if (*tz == 'M')
255 tzr->type = M;
256 int consumed;
257 if (sscanf (tz, "M%hu.%hu.%hu%n",
258 &tzr->m, &tzr->n, &tzr->d, &consumed) != 3
259 || tzr->m < 1 || tzr->m > 12
260 || tzr->n < 1 || tzr->n > 5 || tzr->d > 6)
261 return false;
262 tz += consumed;
264 else if (*tz == '\0')
266 /* Daylight time rules in the U.S. are defined in the U.S. Code,
267 Title 15, Chapter 6, Subchapter IX - Standard Time. These
268 dates were established by Congress in the Energy Policy Act
269 of 2005 [Pub. L. no. 109-58, 119 Stat 594 (2005)].
270 Below is the equivalent of "M3.2.0,M11.1.0" [/2 not needed
271 since 2:00AM is the default]. */
272 tzr->type = M;
273 if (tzr == &tz_rules[0])
275 tzr->m = 3;
276 tzr->n = 2;
277 tzr->d = 0;
279 else
281 tzr->m = 11;
282 tzr->n = 1;
283 tzr->d = 0;
286 else
287 return false;
289 if (*tz != '\0' && *tz != '/' && *tz != ',')
290 return false;
291 else if (*tz == '/')
293 /* Get the time of day of the change. */
294 int negative;
295 ++tz;
296 if (*tz == '\0')
297 return false;
298 negative = *tz == '-';
299 tz += negative;
300 /* Default to 2:00 AM. */
301 unsigned short hh = 2;
302 unsigned short mm = 0;
303 unsigned short ss = 0;
304 int consumed = 0;
305 sscanf (tz, "%hu%n:%hu%n:%hu%n",
306 &hh, &consumed, &mm, &consumed, &ss, &consumed);;
307 tz += consumed;
308 tzr->secs = (negative ? -1 : 1) * ((hh * 60 * 60) + (mm * 60) + ss);
310 else
311 /* Default to 2:00 AM. */
312 tzr->secs = 2 * 60 * 60;
314 tzr->computed_for = -1;
315 *tzp = tz;
316 return true;
319 /* Parse the POSIX TZ-style string. */
320 void
321 __tzset_parse_tz (const char *tz)
323 /* Clear out old state and reset to unnamed UTC. */
324 memset (tz_rules, '\0', sizeof tz_rules);
325 tz_rules[0].name = tz_rules[1].name = "";
327 /* Get the standard timezone name. */
328 if (parse_tzname (&tz, 0) && parse_offset (&tz, 0))
330 /* Get the DST timezone name (if any). */
331 if (*tz != '\0')
333 if (parse_tzname (&tz, 1))
335 parse_offset (&tz, 1);
336 if (*tz == '\0' || (tz[0] == ',' && tz[1] == '\0'))
338 /* There is no rule. See if there is a default rule
339 file. */
340 __tzfile_default (tz_rules[0].name, tz_rules[1].name,
341 tz_rules[0].offset, tz_rules[1].offset);
342 if (__use_tzfile)
344 free (old_tz);
345 old_tz = NULL;
346 return;
350 /* Figure out the standard <-> DST rules. */
351 if (parse_rule (&tz, 0))
352 parse_rule (&tz, 1);
354 else
356 /* There is no DST. */
357 tz_rules[1].name = tz_rules[0].name;
358 tz_rules[1].offset = tz_rules[0].offset;
362 update_vars ();
365 /* Interpret the TZ envariable. */
366 static void
367 tzset_internal (int always)
369 static int is_initialized;
370 const char *tz;
372 if (is_initialized && !always)
373 return;
374 is_initialized = 1;
376 /* Examine the TZ environment variable. */
377 tz = getenv ("TZ");
378 if (tz && *tz == '\0')
379 /* User specified the empty string; use UTC explicitly. */
380 tz = "Universal";
382 /* A leading colon means "implementation defined syntax".
383 We ignore the colon and always use the same algorithm:
384 try a data file, and if none exists parse the 1003.1 syntax. */
385 if (tz && *tz == ':')
386 ++tz;
388 /* Check whether the value changed since the last run. */
389 if (old_tz != NULL && tz != NULL && strcmp (tz, old_tz) == 0)
390 /* No change, simply return. */
391 return;
393 if (tz == NULL)
394 /* No user specification; use the site-wide default. */
395 tz = TZDEFAULT;
397 tz_rules[0].name = NULL;
398 tz_rules[1].name = NULL;
400 /* Save the value of `tz'. */
401 free (old_tz);
402 old_tz = tz ? __strdup (tz) : NULL;
404 /* Try to read a data file. */
405 __tzfile_read (tz, 0, NULL);
406 if (__use_tzfile)
407 return;
409 /* No data file found. Default to UTC if nothing specified. */
411 if (tz == NULL || *tz == '\0'
412 || (TZDEFAULT != NULL && strcmp (tz, TZDEFAULT) == 0))
414 memset (tz_rules, '\0', sizeof tz_rules);
415 tz_rules[0].name = tz_rules[1].name = "UTC";
416 if (J0 != 0)
417 tz_rules[0].type = tz_rules[1].type = J0;
418 tz_rules[0].change = tz_rules[1].change = (time_t) -1;
419 update_vars ();
420 return;
423 __tzset_parse_tz (tz);
426 /* Figure out the exact time (as a time_t) in YEAR
427 when the change described by RULE will occur and
428 put it in RULE->change, saving YEAR in RULE->computed_for. */
429 static void
430 internal_function
431 compute_change (tz_rule *rule, int year)
433 time_t t;
435 if (year != -1 && rule->computed_for == year)
436 /* Operations on times in 2 BC will be slower. Oh well. */
437 return;
439 /* First set T to January 1st, 0:00:00 GMT in YEAR. */
440 if (year > 1970)
441 t = ((year - 1970) * 365
442 + /* Compute the number of leapdays between 1970 and YEAR
443 (exclusive). There is a leapday every 4th year ... */
444 + ((year - 1) / 4 - 1970 / 4)
445 /* ... except every 100th year ... */
446 - ((year - 1) / 100 - 1970 / 100)
447 /* ... but still every 400th year. */
448 + ((year - 1) / 400 - 1970 / 400)) * SECSPERDAY;
449 else
450 t = 0;
452 switch (rule->type)
454 case J1:
455 /* Jn - Julian day, 1 == January 1, 60 == March 1 even in leap years.
456 In non-leap years, or if the day number is 59 or less, just
457 add SECSPERDAY times the day number-1 to the time of
458 January 1, midnight, to get the day. */
459 t += (rule->d - 1) * SECSPERDAY;
460 if (rule->d >= 60 && __isleap (year))
461 t += SECSPERDAY;
462 break;
464 case J0:
465 /* n - Day of year.
466 Just add SECSPERDAY times the day number to the time of Jan 1st. */
467 t += rule->d * SECSPERDAY;
468 break;
470 case M:
471 /* Mm.n.d - Nth "Dth day" of month M. */
473 unsigned int i;
474 int d, m1, yy0, yy1, yy2, dow;
475 const unsigned short int *myday =
476 &__mon_yday[__isleap (year)][rule->m];
478 /* First add SECSPERDAY for each day in months before M. */
479 t += myday[-1] * SECSPERDAY;
481 /* Use Zeller's Congruence to get day-of-week of first day of month. */
482 m1 = (rule->m + 9) % 12 + 1;
483 yy0 = (rule->m <= 2) ? (year - 1) : year;
484 yy1 = yy0 / 100;
485 yy2 = yy0 % 100;
486 dow = ((26 * m1 - 2) / 10 + 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
487 if (dow < 0)
488 dow += 7;
490 /* DOW is the day-of-week of the first day of the month. Get the
491 day-of-month (zero-origin) of the first DOW day of the month. */
492 d = rule->d - dow;
493 if (d < 0)
494 d += 7;
495 for (i = 1; i < rule->n; ++i)
497 if (d + 7 >= (int) myday[0] - myday[-1])
498 break;
499 d += 7;
502 /* D is the day-of-month (zero-origin) of the day we want. */
503 t += d * SECSPERDAY;
505 break;
508 /* T is now the Epoch-relative time of 0:00:00 GMT on the day we want.
509 Just add the time of day and local offset from GMT, and we're done. */
511 rule->change = t - rule->offset + rule->secs;
512 rule->computed_for = year;
516 /* Figure out the correct timezone for TM and set `__tzname',
517 `__timezone', and `__daylight' accordingly. */
518 void
519 internal_function
520 __tz_compute (time_t timer, struct tm *tm, int use_localtime)
522 compute_change (&tz_rules[0], 1900 + tm->tm_year);
523 compute_change (&tz_rules[1], 1900 + tm->tm_year);
525 if (use_localtime)
527 int isdst;
529 /* We have to distinguish between northern and southern
530 hemisphere. For the latter the daylight saving time
531 ends in the next year. */
532 if (__builtin_expect (tz_rules[0].change
533 > tz_rules[1].change, 0))
534 isdst = (timer < tz_rules[1].change
535 || timer >= tz_rules[0].change);
536 else
537 isdst = (timer >= tz_rules[0].change
538 && timer < tz_rules[1].change);
539 tm->tm_isdst = isdst;
540 tm->tm_zone = __tzname[isdst];
541 tm->tm_gmtoff = tz_rules[isdst].offset;
545 /* Reinterpret the TZ environment variable and set `tzname'. */
546 #undef tzset
548 void
549 __tzset (void)
551 __libc_lock_lock (tzset_lock);
553 tzset_internal (1);
555 if (!__use_tzfile)
557 /* Set `tzname'. */
558 __tzname[0] = (char *) tz_rules[0].name;
559 __tzname[1] = (char *) tz_rules[1].name;
562 __libc_lock_unlock (tzset_lock);
564 weak_alias (__tzset, tzset)
566 /* Return the `struct tm' representation of *TIMER in the local timezone.
567 Use local time if USE_LOCALTIME is nonzero, UTC otherwise. */
568 struct tm *
569 __tz_convert (const time_t *timer, int use_localtime, struct tm *tp)
571 long int leap_correction;
572 int leap_extra_secs;
574 if (timer == NULL)
576 __set_errno (EINVAL);
577 return NULL;
580 __libc_lock_lock (tzset_lock);
582 /* Update internal database according to current TZ setting.
583 POSIX.1 8.3.7.2 says that localtime_r is not required to set tzname.
584 This is a good idea since this allows at least a bit more parallelism. */
585 tzset_internal (tp == &_tmbuf && use_localtime);
587 if (__use_tzfile)
588 __tzfile_compute (*timer, use_localtime, &leap_correction,
589 &leap_extra_secs, tp);
590 else
592 if (! __offtime (timer, 0, tp))
593 tp = NULL;
594 else
595 __tz_compute (*timer, tp, use_localtime);
596 leap_correction = 0L;
597 leap_extra_secs = 0;
600 __libc_lock_unlock (tzset_lock);
602 if (tp)
604 if (! use_localtime)
606 tp->tm_isdst = 0;
607 tp->tm_zone = "GMT";
608 tp->tm_gmtoff = 0L;
611 if (__offtime (timer, tp->tm_gmtoff - leap_correction, tp))
612 tp->tm_sec += leap_extra_secs;
613 else
614 tp = NULL;
617 return tp;
621 libc_freeres_fn (free_mem)
623 while (tzstring_list != NULL)
625 struct tzstring_l *old = tzstring_list;
627 tzstring_list = tzstring_list->next;
628 free (old);
630 free (old_tz);
631 old_tz = NULL;