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