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