fix strftime handling of time zone data
[musl] / src / time / __tz.c
1 #include "time_impl.h"
2 #include <stdint.h>
3 #include <limits.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include "libc.h"
7
8 long  __timezone = 0;
9 int   __daylight = 0;
10 char *__tzname[2] = { 0, 0 };
11
12 weak_alias(__timezone, timezone);
13 weak_alias(__daylight, daylight);
14 weak_alias(__tzname, tzname);
15
16 static char std_name[TZNAME_MAX+1];
17 static char dst_name[TZNAME_MAX+1];
18 const char __gmt[] = "GMT";
19
20 static int dst_off;
21 static int r0[5], r1[5];
22
23 static const unsigned char *zi, *trans, *index, *types, *abbrevs, *abbrevs_end;
24 static size_t map_size;
25
26 static char old_tz_buf[32];
27 static char *old_tz = old_tz_buf;
28 static size_t old_tz_size = sizeof old_tz_buf;
29
30 static int lock[2];
31
32 static int getint(const char **p)
33 {
34         unsigned x;
35         for (x=0; **p-'0'<10U; (*p)++) x = **p-'0' + 10*x;
36         return x;
37 }
38
39 static int getsigned(const char **p)
40 {
41         if (**p == '-') {
42                 ++*p;
43                 return -getint(p);
44         }
45         if (**p == '+') ++*p;
46         return getint(p);
47 }
48
49 static int getoff(const char **p)
50 {
51         int off = 3600*getsigned(p);
52         if (**p == ':') {
53                 ++*p;
54                 off += 60*getint(p);
55                 if (**p == ':') {
56                         ++*p;
57                         off += getint(p);
58                 }
59         }
60         return off;
61 }
62
63 static void getrule(const char **p, int rule[5])
64 {
65         int r = rule[0] = **p;
66
67         if (r!='M') {
68                 if (r=='J') ++*p;
69                 else rule[0] = 0;
70                 rule[1] = getint(p);
71         } else {
72                 ++*p; rule[1] = getint(p);
73                 ++*p; rule[2] = getint(p);
74                 ++*p; rule[3] = getint(p);
75         }
76
77         if (**p=='/') {
78                 ++*p;
79                 rule[4] = getoff(p);
80         } else {
81                 rule[4] = 7200;
82         }
83 }
84
85 static void getname(char *d, const char **p)
86 {
87         int i;
88         if (**p == '<') {
89                 ++*p;
90                 for (i=0; **p!='>' && i<TZNAME_MAX; i++)
91                         d[i] = (*p)[i];
92                 ++*p;
93         } else {
94                 for (i=0; ((*p)[i]|32)-'a'<26U && i<TZNAME_MAX; i++)
95                         d[i] = (*p)[i];
96         }
97         *p += i;
98         d[i] = 0;
99 }
100
101 #define VEC(...) ((const unsigned char[]){__VA_ARGS__})
102
103 static uint32_t zi_read32(const unsigned char *z)
104 {
105         return (unsigned)z[0]<<24 | z[1]<<16 | z[2]<<8 | z[3];
106 }
107
108 static size_t zi_dotprod(const unsigned char *z, const unsigned char *v, size_t n)
109 {
110         size_t y;
111         uint32_t x;
112         for (y=0; n; n--, z+=4, v++) {
113                 x = zi_read32(z);
114                 y += x * *v;
115         }
116         return y;
117 }
118
119 int __munmap(void *, size_t);
120
121 static void do_tzset()
122 {
123         char buf[NAME_MAX+25], *pathname=buf+24;
124         const char *try, *s;
125         const unsigned char *map = 0;
126         size_t i;
127         static const char search[] =
128                 "/usr/share/zoneinfo/\0/share/zoneinfo/\0/etc/zoneinfo/\0";
129
130         s = getenv("TZ");
131         if (!s || !*s) s = __gmt;
132
133         if (old_tz && !strcmp(s, old_tz)) return;
134
135         if (zi) __munmap((void *)zi, map_size);
136
137         /* Cache the old value of TZ to check if it has changed. Avoid
138          * free so as not to pull it into static programs. Growth
139          * strategy makes it so free would have minimal benefit anyway. */
140         i = strlen(s);
141         if (i > PATH_MAX+1) s = "", i = 0;
142         if (i >= old_tz_size) {
143                 old_tz_size *= 2;
144                 if (i >= old_tz_size) old_tz_size = i+1;
145                 if (old_tz_size > PATH_MAX+2) old_tz_size = PATH_MAX+2;
146                 old_tz = malloc(old_tz_size);
147         }
148         if (old_tz) memcpy(old_tz, s, i+1);
149
150         if (*s == ':') s++;
151
152         /* Non-suid can use an absolute tzfile pathname or a relative
153          * pathame beginning with "."; in secure mode, only the
154          * standard path will be searched. */
155         if (*s == '/' || *s == '.') {
156                 if (!libc.secure) map = __map_file(s, &map_size);
157         } else {
158                 for (i=0; s[i] && s[i]!=','; i++) {
159                         if (s[i]=='/') {
160                                 size_t l = strlen(s);
161                                 if (l > NAME_MAX || strchr(s, '.'))
162                                         break;
163                                 memcpy(pathname, s, l+1);
164                                 pathname[l] = 0;
165                                 for (try=search; !map && *try; try+=l) {
166                                         l = strlen(try);
167                                         memcpy(pathname-l, try, l);
168                                         map = __map_file(pathname-l, &map_size);
169                                 }
170                                 break;
171                         }
172                 }
173         }
174
175         zi = map;
176         if (map) {
177                 int scale = 2;
178                 if (sizeof(time_t) > 4 && map[4]=='2') {
179                         size_t skip = zi_dotprod(zi, VEC(1,1,8,5,6,1), 6);
180                         trans = zi+skip+44+20;
181                         scale++;
182                 } else {
183                         trans = zi+44;
184                 }
185                 index = trans + (zi_read32(trans-12) << scale);
186                 types = index + zi_read32(trans-12);
187                 abbrevs = types + 6*zi_read32(trans-8);
188                 abbrevs_end = abbrevs + zi_read32(trans-4);
189                 if (zi[map_size-1] == '\n') {
190                         for (s = (const char *)zi+map_size-2; *s!='\n'; s--);
191                         s++;
192                 } else {
193                         s = 0;
194                 }
195         }
196
197         if (!s) s = __gmt;
198         getname(std_name, &s);
199         __tzname[0] = std_name;
200         __timezone = getoff(&s);
201         getname(dst_name, &s);
202         __tzname[1] = dst_name;
203         if (dst_name[0]) {
204                 __daylight = 1;
205                 if (*s == '+' || *s=='-' || *s-'0'<10U)
206                         dst_off = getoff(&s);
207                 else
208                         dst_off = __timezone - 3600;
209         } else {
210                 __daylight = 0;
211                 dst_off = 0;
212         }
213
214         if (*s == ',') s++, getrule(&s, r0);
215         if (*s == ',') s++, getrule(&s, r1);
216 }
217
218 /* Search zoneinfo rules to find the one that applies to the given time,
219  * and determine alternate opposite-DST-status rule that may be needed. */
220
221 static size_t scan_trans(long long t, int local, size_t *alt)
222 {
223         int scale = 3 - (trans == zi+44);
224         uint64_t x;
225         int off = 0;
226
227         size_t a = 0, n = (index-trans)>>scale, m;
228
229         if (!n) {
230                 if (alt) *alt = 0;
231                 return 0;
232         }
233
234         /* Binary search for 'most-recent rule before t'. */
235         while (n > 1) {
236                 m = a + n/2;
237                 x = zi_read32(trans + (m<<scale));
238                 if (scale == 3) x = x<<32 | zi_read32(trans + (m<<scale) + 4);
239                 else x = (int32_t)x;
240                 if (local) off = (int32_t)zi_read32(types + 6 * index[m-1]);
241                 if (t - off < (int64_t)x) {
242                         n /= 2;
243                 } else {
244                         a = m;
245                         n -= n/2;
246                 }
247         }
248
249         /* First and last entry are special. First means to use lowest-index
250          * non-DST type. Last means to apply POSIX-style rule if available. */
251         n = (index-trans)>>scale;
252         if (a == n-1) return -1;
253         if (a == 0) {
254                 x = zi_read32(trans + (a<<scale));
255                 if (scale == 3) x = x<<32 | zi_read32(trans + (a<<scale) + 4);
256                 else x = (int32_t)x;
257                 if (local) off = (int32_t)zi_read32(types + 6 * index[a-1]);
258                 if (t - off < (int64_t)x) {
259                         for (a=0; a<(abbrevs-types)/6; a++) {
260                                 if (types[6*a+4] != types[4]) break;
261                         }
262                         if (a == (abbrevs-types)/6) a = 0;
263                         if (types[6*a+4]) {
264                                 *alt = a;
265                                 return 0;
266                         } else {
267                                 *alt = 0;
268                                 return a;
269                         }
270                 }
271         }
272
273         /* Try to find a neighboring opposite-DST-status rule. */
274         if (alt) {
275                 if (a && types[6*index[a-1]+4] != types[6*index[a]+4])
276                         *alt = index[a-1];
277                 else if (a+1<n && types[6*index[a+1]+4] != types[6*index[a]+4])
278                         *alt = index[a+1];
279                 else
280                         *alt = index[a];
281         }
282
283         return index[a];
284 }
285
286 static int days_in_month(int m, int is_leap)
287 {
288         if (m==2) return 28+is_leap;
289         else return 30+((0xad5>>(m-1))&1);
290 }
291
292 /* Convert a POSIX DST rule plus year to seconds since epoch. */
293
294 static long long rule_to_secs(const int *rule, int year)
295 {
296         int is_leap;
297         long long t = __year_to_secs(year, &is_leap);
298         int x, m, n, d;
299         if (rule[0]!='M') {
300                 x = rule[1];
301                 if (rule[0]=='J' && (x < 60 || !is_leap)) x--;
302                 t += 86400 * x;
303         } else {
304                 m = rule[1];
305                 n = rule[2];
306                 d = rule[3];
307                 t += __month_to_secs(m-1, is_leap);
308                 int wday = (int)((t + 4*86400) % (7*86400)) / 86400;
309                 int days = d - wday;
310                 if (days < 0) days += 7;
311                 if (n == 5 && days+28 >= days_in_month(m, is_leap)) n = 4;
312                 t += 86400 * (days + 7*(n-1));
313         }
314         t += rule[4];
315         return t;
316 }
317
318 /* Determine the time zone in effect for a given time in seconds since the
319  * epoch. It can be given in local or universal time. The results will
320  * indicate whether DST is in effect at the queried time, and will give both
321  * the GMT offset for the active zone/DST rule and the opposite DST. This
322  * enables a caller to efficiently adjust for the case where an explicit
323  * DST specification mismatches what would be in effect at the time. */
324
325 void __secs_to_zone(long long t, int local, int *isdst, long *offset, long *oppoff, const char **zonename)
326 {
327         LOCK(lock);
328
329         do_tzset();
330
331         if (zi) {
332                 size_t alt, i = scan_trans(t, local, &alt);
333                 if (i != -1) {
334                         *isdst = types[6*i+4];
335                         *offset = -(int32_t)zi_read32(types+6*i);
336                         *zonename = (const char *)abbrevs + types[6*i+5];
337                         if (oppoff) *oppoff = -(int32_t)zi_read32(types+6*alt);
338                         UNLOCK(lock);
339                         return;
340                 }
341         }
342
343         if (!__daylight) goto std;
344
345         /* FIXME: may be broken if DST changes right at year boundary?
346          * Also, this could be more efficient.*/
347         long long y = t / 31556952 + 70;
348         while (__year_to_secs(y, 0) > t) y--;
349         while (__year_to_secs(y+1, 0) < t) y++;
350
351         long long t0 = rule_to_secs(r0, y);
352         long long t1 = rule_to_secs(r1, y);
353
354         if (t0 < t1) {
355                 if (!local) {
356                         t0 += __timezone;
357                         t1 += dst_off;
358                 }
359                 if (t >= t0 && t < t1) goto dst;
360                 goto std;
361         } else {
362                 if (!local) {
363                         t1 += __timezone;
364                         t0 += dst_off;
365                 }
366                 if (t >= t1 && t < t0) goto std;
367                 goto dst;
368         }
369 std:
370         *isdst = 0;
371         *offset = __timezone;
372         if (oppoff) *oppoff = dst_off;
373         *zonename = __tzname[0];
374         UNLOCK(lock);
375         return;
376 dst:
377         *isdst = 1;
378         *offset = dst_off;
379         if (oppoff) *oppoff = __timezone;
380         *zonename = __tzname[1];
381         UNLOCK(lock);
382 }
383
384 void __tzset()
385 {
386         LOCK(lock);
387         do_tzset();
388         UNLOCK(lock);
389 }
390
391 weak_alias(__tzset, tzset);
392
393 const char *__tm_to_tzname(const struct tm *tm)
394 {
395         const void *p = tm->__tm_zone;
396         LOCK(lock);
397         do_tzset();
398         if (p != __gmt && p != __tzname[0] && p != __tzname[1]
399             && (uintptr_t)p-(uintptr_t)abbrevs >= abbrevs_end - abbrevs)
400                 p = "";
401         UNLOCK(lock);
402         return p;
403 }