use default timezone from /etc/localtime if $TZ is unset/blank
[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, *p;
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 = "/etc/localtime";
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 = __gmt, i = 3;
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         /* Non-suid can use an absolute tzfile pathname or a relative
151          * pathame beginning with "."; in secure mode, only the
152          * standard path will be searched. */
153         if (*s == ':' || ((p=strchr(s, '/')) && !memchr(s, ',', p-s))) {
154                 if (*s == ':') s++;
155                 if (*s == '/' || *s == '.') {
156                         if (!libc.secure || !strcmp(s, "/etc/localtime"))
157                                 map = __map_file(s, &map_size);
158                 } else {
159                         size_t l = strlen(s);
160                         if (l <= NAME_MAX && !strchr(s, '.')) {
161                                 memcpy(pathname, s, l+1);
162                                 pathname[l] = 0;
163                                 for (try=search; !map && *try; try+=l+1) {
164                                         l = strlen(try);
165                                         memcpy(pathname-l, try, l);
166                                         map = __map_file(pathname-l, &map_size);
167                                 }
168                         }
169                 }
170                 if (!map) s = __gmt;
171         }
172         if (map && (map_size < 44 || memcmp(map, "TZif", 4))) {
173                 __munmap((void *)map, map_size);
174                 map = 0;
175                 s = __gmt;
176         }
177
178         zi = map;
179         if (map) {
180                 int scale = 2;
181                 if (sizeof(time_t) > 4 && map[4]=='2') {
182                         size_t skip = zi_dotprod(zi+20, VEC(1,1,8,5,6,1), 6);
183                         trans = zi+skip+44+44;
184                         scale++;
185                 } else {
186                         trans = zi+44;
187                 }
188                 index = trans + (zi_read32(trans-12) << scale);
189                 types = index + zi_read32(trans-12);
190                 abbrevs = types + 6*zi_read32(trans-8);
191                 abbrevs_end = abbrevs + zi_read32(trans-4);
192                 if (zi[map_size-1] == '\n') {
193                         for (s = (const char *)zi+map_size-2; *s!='\n'; s--);
194                         s++;
195                 } else {
196                         const unsigned char *p;
197                         __tzname[0] = __tzname[1] = 0;
198                         __daylight = __timezone = dst_off = 0;
199                         for (i=0; i<5; i++) r0[i] = r1[i] = 0;
200                         for (p=types; p<abbrevs; p+=6) {
201                                 if (!p[4] && !__tzname[0]) {
202                                         __tzname[0] = (char *)abbrevs + p[5];
203                                         __timezone = -zi_read32(p);
204                                 }
205                                 if (p[4] && !__tzname[1]) {
206                                         __tzname[1] = (char *)abbrevs + p[5];
207                                         dst_off = -zi_read32(p);
208                                         __daylight = 1;
209                                 }
210                         }
211                         if (!__tzname[0]) __tzname[0] = __tzname[1];
212                         if (!__tzname[0]) __tzname[0] = (char *)__gmt;
213                         if (!__daylight) {
214                                 __tzname[1] = __tzname[0];
215                                 dst_off = __timezone;
216                         }
217                         return;
218                 }
219         }
220
221         if (!s) s = __gmt;
222         getname(std_name, &s);
223         __tzname[0] = std_name;
224         __timezone = getoff(&s);
225         getname(dst_name, &s);
226         __tzname[1] = dst_name;
227         if (dst_name[0]) {
228                 __daylight = 1;
229                 if (*s == '+' || *s=='-' || *s-'0'<10U)
230                         dst_off = getoff(&s);
231                 else
232                         dst_off = __timezone - 3600;
233         } else {
234                 __daylight = 0;
235                 dst_off = 0;
236         }
237
238         if (*s == ',') s++, getrule(&s, r0);
239         if (*s == ',') s++, getrule(&s, r1);
240 }
241
242 /* Search zoneinfo rules to find the one that applies to the given time,
243  * and determine alternate opposite-DST-status rule that may be needed. */
244
245 static size_t scan_trans(long long t, int local, size_t *alt)
246 {
247         int scale = 3 - (trans == zi+44);
248         uint64_t x;
249         int off = 0;
250
251         size_t a = 0, n = (index-trans)>>scale, m;
252
253         if (!n) {
254                 if (alt) *alt = 0;
255                 return 0;
256         }
257
258         /* Binary search for 'most-recent rule before t'. */
259         while (n > 1) {
260                 m = a + n/2;
261                 x = zi_read32(trans + (m<<scale));
262                 if (scale == 3) x = x<<32 | zi_read32(trans + (m<<scale) + 4);
263                 else x = (int32_t)x;
264                 if (local) off = (int32_t)zi_read32(types + 6 * index[m-1]);
265                 if (t - off < (int64_t)x) {
266                         n /= 2;
267                 } else {
268                         a = m;
269                         n -= n/2;
270                 }
271         }
272
273         /* First and last entry are special. First means to use lowest-index
274          * non-DST type. Last means to apply POSIX-style rule if available. */
275         n = (index-trans)>>scale;
276         if (a == n-1) return -1;
277         if (a == 0) {
278                 x = zi_read32(trans + (a<<scale));
279                 if (scale == 3) x = x<<32 | zi_read32(trans + (a<<scale) + 4);
280                 else x = (int32_t)x;
281                 if (local) off = (int32_t)zi_read32(types + 6 * index[a-1]);
282                 if (t - off < (int64_t)x) {
283                         for (a=0; a<(abbrevs-types)/6; a++) {
284                                 if (types[6*a+4] != types[4]) break;
285                         }
286                         if (a == (abbrevs-types)/6) a = 0;
287                         if (types[6*a+4]) {
288                                 *alt = a;
289                                 return 0;
290                         } else {
291                                 *alt = 0;
292                                 return a;
293                         }
294                 }
295         }
296
297         /* Try to find a neighboring opposite-DST-status rule. */
298         if (alt) {
299                 if (a && types[6*index[a-1]+4] != types[6*index[a]+4])
300                         *alt = index[a-1];
301                 else if (a+1<n && types[6*index[a+1]+4] != types[6*index[a]+4])
302                         *alt = index[a+1];
303                 else
304                         *alt = index[a];
305         }
306
307         return index[a];
308 }
309
310 static int days_in_month(int m, int is_leap)
311 {
312         if (m==2) return 28+is_leap;
313         else return 30+((0xad5>>(m-1))&1);
314 }
315
316 /* Convert a POSIX DST rule plus year to seconds since epoch. */
317
318 static long long rule_to_secs(const int *rule, int year)
319 {
320         int is_leap;
321         long long t = __year_to_secs(year, &is_leap);
322         int x, m, n, d;
323         if (rule[0]!='M') {
324                 x = rule[1];
325                 if (rule[0]=='J' && (x < 60 || !is_leap)) x--;
326                 t += 86400 * x;
327         } else {
328                 m = rule[1];
329                 n = rule[2];
330                 d = rule[3];
331                 t += __month_to_secs(m-1, is_leap);
332                 int wday = (int)((t + 4*86400) % (7*86400)) / 86400;
333                 int days = d - wday;
334                 if (days < 0) days += 7;
335                 if (n == 5 && days+28 >= days_in_month(m, is_leap)) n = 4;
336                 t += 86400 * (days + 7*(n-1));
337         }
338         t += rule[4];
339         return t;
340 }
341
342 /* Determine the time zone in effect for a given time in seconds since the
343  * epoch. It can be given in local or universal time. The results will
344  * indicate whether DST is in effect at the queried time, and will give both
345  * the GMT offset for the active zone/DST rule and the opposite DST. This
346  * enables a caller to efficiently adjust for the case where an explicit
347  * DST specification mismatches what would be in effect at the time. */
348
349 void __secs_to_zone(long long t, int local, int *isdst, long *offset, long *oppoff, const char **zonename)
350 {
351         LOCK(lock);
352
353         do_tzset();
354
355         if (zi) {
356                 size_t alt, i = scan_trans(t, local, &alt);
357                 if (i != -1) {
358                         *isdst = types[6*i+4];
359                         *offset = -(int32_t)zi_read32(types+6*i);
360                         *zonename = (const char *)abbrevs + types[6*i+5];
361                         if (oppoff) *oppoff = -(int32_t)zi_read32(types+6*alt);
362                         UNLOCK(lock);
363                         return;
364                 }
365         }
366
367         if (!__daylight) goto std;
368
369         /* FIXME: may be broken if DST changes right at year boundary?
370          * Also, this could be more efficient.*/
371         long long y = t / 31556952 + 70;
372         while (__year_to_secs(y, 0) > t) y--;
373         while (__year_to_secs(y+1, 0) < t) y++;
374
375         long long t0 = rule_to_secs(r0, y);
376         long long t1 = rule_to_secs(r1, y);
377
378         if (t0 < t1) {
379                 if (!local) {
380                         t0 += __timezone;
381                         t1 += dst_off;
382                 }
383                 if (t >= t0 && t < t1) goto dst;
384                 goto std;
385         } else {
386                 if (!local) {
387                         t1 += __timezone;
388                         t0 += dst_off;
389                 }
390                 if (t >= t1 && t < t0) goto std;
391                 goto dst;
392         }
393 std:
394         *isdst = 0;
395         *offset = __timezone;
396         if (oppoff) *oppoff = dst_off;
397         *zonename = __tzname[0];
398         UNLOCK(lock);
399         return;
400 dst:
401         *isdst = 1;
402         *offset = dst_off;
403         if (oppoff) *oppoff = __timezone;
404         *zonename = __tzname[1];
405         UNLOCK(lock);
406 }
407
408 void __tzset()
409 {
410         LOCK(lock);
411         do_tzset();
412         UNLOCK(lock);
413 }
414
415 weak_alias(__tzset, tzset);
416
417 const char *__tm_to_tzname(const struct tm *tm)
418 {
419         const void *p = tm->__tm_zone;
420         LOCK(lock);
421         do_tzset();
422         if (p != __gmt && p != __tzname[0] && p != __tzname[1] &&
423             (!zi || (uintptr_t)p-(uintptr_t)abbrevs >= abbrevs_end - abbrevs))
424                 p = "";
425         UNLOCK(lock);
426         return p;
427 }