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