scorpiox-bot-plugin-time
←tz.cc
789 lines · 26 KBHEADBlameDownload
1/*
2 * tz.c - IANA timezone resolution over the embedded table (src/tzdata.h).
3 *
4 * The design mirrors what the OS does, in three steps:
5 *
6 * 1. Look the zone up in the exact-key table. Never a filesystem path, so
7 * `europe/warsaw` is refused on every platform instead of only on the
8 * case-sensitive ones.
9 * 2. Answer a UTC instant from the embedded transition list, falling back
10 * to the zone's own POSIX TZ footer string beyond the last embedded
11 * transition - exactly what zoneinfo itself does after it runs out of
12 * the compiled table.
13 * 3. For a wall-clock instant the caller supplies (the `convert_time`
14 * tool), find the UTC instants that map to it. A forward clock change
15 * makes a wall time that does not exist (0 candidates); a backward
16 * change repeats an hour (2 candidates). Guessing one silently is how a
17 * converter reports a time that never happened.
18 *
19 * Nothing here reads the clock: every function is a pure function of its
20 * arguments, so a test can pin a date in 2035 and get the same answer on
21 * Linux, macOS and Windows.
22 *
23 * MIT License. Copyright (c) 2026 SCORPIOX INC.
24 */
25#if defined(_WIN32) && !defined(_WIN32_WINNT)
26# define _WIN32_WINNT 0x0601
27#endif
28
29#if !defined(_WIN32)
30# define _POSIX_C_SOURCE 200809L
31# define _DEFAULT_SOURCE 1
32# if defined(__APPLE__)
33# define _DARWIN_C_SOURCE 1
34# endif
35#endif
36
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <time.h>
41#include <ctype.h>
42
43#if defined(_WIN32)
44# define WIN32_LEAN_AND_MEAN
45# include <windows.h>
46#else
47# include <unistd.h>
48# include <limits.h>
49#endif
50
51#include "tz.h"
52#include "tzdata.h"
53
54/* ------------------------------------------------------------------ */
55/* The zone record */
56/* */
57/* tz_zone is the generated struct plus the name pointer, so callers */
58/* never index the string pool themselves. */
59/* ------------------------------------------------------------------ */
60
61struct tz_zone {
62 const char *name;
63 const tz_zone_t *rec;
64 int index;
65};
66
67static tz_zone *g_zones = NULL;
68static int g_nzones = 0;
69
70static void zones_build(void)
71{
72 int i;
73 if (g_zones) return;
74 g_zones = (tz_zone *)calloc((size_t)TZ_ZONE_COUNT, sizeof *g_zones);
75 if (!g_zones) return;
76 for (i = 0; i < TZ_ZONE_COUNT; i++) {
77 g_zones[i].name = TZ_NAME_POOL + TZ_ZONES[i].name;
78 g_zones[i].rec = &TZ_ZONES[i];
79 g_zones[i].index = i;
80 }
81 g_nzones = TZ_ZONE_COUNT;
82}
83
84const char *tz_zone_name(const tz_zone *z)
85{
86 return z ? z->name : NULL;
87}
88
89int tz_count(void)
90{
91 zones_build();
92 return g_nzones;
93}
94
95const char *tz_name_at(int index)
96{
97 zones_build();
98 if (index < 0 || index >= g_nzones) return NULL;
99 return g_zones[index].name;
100}
101
102const tz_zone *tz_find(const char *name)
103{
104 int lo, hi;
105
106 if (!name || !*name) return NULL;
107 /* An IANA key can never contain these: refused before any search so a
108 * path, a traversal or a `..` cannot be mistaken for a zone. */
109 if (strstr(name, "..") || strchr(name, '\\') || strchr(name, '\n') ||
110 strchr(name, '\r') || strchr(name, '%'))
111 return NULL;
112 if (name[0] == '/' || name[0] == '.' || name[0] == ' ') return NULL;
113 if (strlen(name) > 96) return NULL;
114
115 zones_build();
116 if (!g_zones) return NULL;
117
118 /* The generated table is sorted by key, so this is a plain binary search
119 * with a case-sensitive compare - the whole point of the exact match. */
120 lo = 0;
121 hi = g_nzones - 1;
122 while (lo <= hi) {
123 int mid = lo + (hi - lo) / 2;
124 int cmp = strcmp(name, g_zones[mid].name);
125 if (cmp == 0) return &g_zones[mid];
126 if (cmp < 0) hi = mid - 1;
127 else lo = mid + 1;
128 }
129 return NULL;
130}
131
132const tz_zone *tz_find_windows(const char *win_id)
133{
134 int i;
135
136 if (!win_id || !*win_id) return NULL;
137 zones_build();
138 if (!g_zones) return NULL;
139 for (i = 0; i < TZ_WIN_COUNT; i++) {
140 if (strcmp(TZ_WIN_POOL + TZ_WIN_ZONES[i].win, win_id) != 0) continue;
141 {
142 const char *iana = TZ_NAME_POOL + TZ_WIN_ZONES[i].zone;
143 return tz_find(iana);
144 }
145 }
146 return NULL;
147}
148
149/* ------------------------------------------------------------------ */
150/* Civil date arithmetic (proleptic Gregorian, days since 1970-01-01) */
151/* ------------------------------------------------------------------ */
152
153int64_t tz_days_from_civil(int y, int m, int d)
154{
155 int64_t era, yoe, doy, doe;
156
157 y -= (m <= 2);
158 era = (y >= 0 ? y : y - 399) / 400;
159 yoe = y - era * 400; /* 0..399 */
160 doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; /* 0..365 */
161 doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; /* 0..146096 */
162 return era * 146097 + doe - 719468;
163}
164
165void tz_civil_from_days(int64_t days, int *y, int *m, int *d)
166{
167 int64_t z, era, doe, yoe, doy, mp;
168 int yy, mm, dd;
169
170 z = days + 719468;
171 era = (z >= 0 ? z : z - 146096) / 146097;
172 doe = z - era * 146097;
173 yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
174 yy = (int)(yoe + era * 400);
175 doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
176 mp = (5 * doy + 2) / 153;
177 dd = (int)(doy - (153 * mp + 2) / 5 + 1);
178 mm = (int)(mp + (mp < 10 ? 3 : -9));
179 if (y) *y = yy + (mm <= 2);
180 if (m) *m = mm;
181 if (d) *d = dd;
182}
183
184int tz_weekday(int64_t days)
185{
186 /* 1970-01-01 was a Thursday (4). */
187 int64_t w = (days + 4) % 7;
188 if (w < 0) w += 7;
189 return (int)w;
190}
191
192/* ------------------------------------------------------------------ */
193/* POSIX TZ footer strings */
194/* */
195/* Beyond the last embedded transition the tz database defers to the */
196/* zone's own rule string, e.g. */
197/* NZST-12NZDT,M9.5.0,M4.1.0/3 (Auckland) */
198/* EST5EDT,M3.2.0,M11.1.0 (New York) */
199/* <-02>2<-01>,M3.5.0/-1,M10.5.0/0 (Godthab) */
200/* <+00>0<+01>,0/0,J365/25 (Casablanca, Ramadan) */
201/* */
202/* Offsets in the string are WEST positive, so the east-of-UTC offset we */
203/* store everywhere else is the negation. */
204/* ------------------------------------------------------------------ */
205
206typedef struct {
207 int kind; /* 0 = Jn, 1 = n (zero-based), 2 = Mm.w.d */
208 int n; /* Jn / n value, or the day-of-week for rules kind 2 */
209 int week; /* kind 2: 1..5 (5 = last) */
210 int month; /* kind 2 */
211 int time; /* seconds after local midnight, may be <0 or >86400 */
212} rule_date;
213
214typedef struct {
215 int ok;
216 int std_off; /* east of UTC */
217 int dst_off; /* east of UTC */
218 int has_dst;
219 rule_date start, end;
220} posix_tz;
221
222static const char *pz_name(const char *s, char *out, size_t outsz)
223{
224 size_t n = 0;
225 if (*s == '<') {
226 s++;
227 while (*s && *s != '>') {
228 if (n + 1 < outsz) out[n++] = *s;
229 s++;
230 }
231 if (*s == '>') s++;
232 } else {
233 while (*s && isalpha((unsigned char)*s)) {
234 if (n + 1 < outsz) out[n++] = *s;
235 s++;
236 }
237 }
238 out[n] = '\0';
239 return s;
240}
241
242static const char *pz_offset(const char *s, int *out, int *found)
243{
244 int sign = 1, h = 0, m = 0, sec = 0;
245 *found = 0;
246 if (*s == '+' || *s == '-') {
247 if (*s == '-') sign = -1;
248 s++;
249 }
250 if (!isdigit((unsigned char)*s) && *s != ':') return s;
251 while (isdigit((unsigned char)*s)) { h = h * 10 + (*s - '0'); s++; }
252 if (*s == ':') {
253 s++;
254 while (isdigit((unsigned char)*s)) { m = m * 10 + (*s - '0'); s++; }
255 if (*s == ':') {
256 s++;
257 while (isdigit((unsigned char)*s)) { sec = sec * 10 + (*s - '0'); s++; }
258 }
259 }
260 *out = sign * (h * 3600 + m * 60 + sec);
261 *found = 1;
262 return s;
263}
264
265static const char *pz_time_of_day(const char *s, int *out)
266{
267 int sign = 1, h = 0, m = 0, sec = 0;
268 if (*s == '+' || *s == '-') {
269 if (*s == '-') sign = -1;
270 s++;
271 }
272 while (isdigit((unsigned char)*s)) { h = h * 10 + (*s - '0'); s++; }
273 if (*s == ':') {
274 s++;
275 while (isdigit((unsigned char)*s)) { m = m * 10 + (*s - '0'); s++; }
276 if (*s == ':') {
277 s++;
278 while (isdigit((unsigned char)*s)) { sec = sec * 10 + (*s - '0'); s++; }
279 }
280 }
281 *out = sign * (h * 3600 + m * 60 + sec);
282 return s;
283}
284
285static const char *pz_rule(const char *s, rule_date *r)
286{
287 memset(r, 0, sizeof *r);
288 r->time = 2 * 3600; /* POSIX default: 02:00 local */
289 if (*s == 'M') {
290 int m = 0, w = 0, d = 0;
291 s++;
292 while (isdigit((unsigned char)*s)) { m = m * 10 + (*s - '0'); s++; }
293 if (*s == '.') s++;
294 while (isdigit((unsigned char)*s)) { w = w * 10 + (*s - '0'); s++; }
295 if (*s == '.') s++;
296 while (isdigit((unsigned char)*s)) { d = d * 10 + (*s - '0'); s++; }
297 r->kind = 2; r->month = m; r->week = w; r->n = d;
298 } else if (*s == 'J') {
299 int n = 0;
300 s++;
301 while (isdigit((unsigned char)*s)) { n = n * 10 + (*s - '0'); s++; }
302 r->kind = 0; r->n = n;
303 } else {
304 int n = 0;
305 while (isdigit((unsigned char)*s)) { n = n * 10 + (*s - '0'); s++; }
306 r->kind = 1; r->n = n;
307 }
308 if (*s == '/') s = pz_time_of_day(s + 1, &r->time);
309 return s;
310}
311
312static int posix_parse(const char *s, posix_tz *p)
313{
314 int found = 0;
315 char nm[24];
316
317 memset(p, 0, sizeof *p);
318 if (!s || !*s || *s == '\n') return -1;
319
320 s = pz_name(s, nm, sizeof nm);
321 if (!nm[0]) return -1;
322 s = pz_offset(s, &p->std_off, &found);
323 if (!found) return -1;
324 p->std_off = -p->std_off; /* west -> east */
325
326 if (*s && *s != ',' && *s != '\n') {
327 s = pz_name(s, nm, sizeof nm);
328 if (!nm[0]) return -1;
329 p->has_dst = 1;
330 if (*s == '+' || *s == '-' || isdigit((unsigned char)*s)) {
331 int v = 0;
332 s = pz_offset(s, &v, &found);
333 if (!found) return -1;
334 p->dst_off = -v;
335 } else {
336 p->dst_off = p->std_off + 3600; /* POSIX default +1h */
337 }
338 }
339 if (p->has_dst) {
340 if (*s != ',') return -1; /* a DST zone without rules
341 * is not in the shipped
342 * database; refuse rather
343 * than guess */
344 s = pz_rule(s + 1, &p->start);
345 if (*s != ',') return -1;
346 s = pz_rule(s + 1, &p->end);
347 }
348 p->ok = 1;
349 return 0;
350}
351
352/* The date a rule names in `year`, as days since the epoch. */
353static int64_t rule_day(const rule_date *r, int year)
354{
355 int64_t jan1 = tz_days_from_civil(year, 1, 1);
356
357 if (r->kind == 0) { /* Jn: 1..365, no Feb 29 */
358 int leap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
359 int doy = r->n - 1;
360 if (leap && r->n >= 60) doy += 1;
361 return jan1 + doy;
362 }
363 if (r->kind == 1) { /* n: 0..365, Feb 29 counts */
364 return jan1 + r->n;
365 }
366 {
367 /* Mm.w.d: day d (0=Sunday) of week w of month m; w=5 means last. */
368 int64_t first = tz_days_from_civil(year, r->month, 1);
369 int wd = tz_weekday(first);
370 int delta = (r->n - wd + 7) % 7;
371 int64_t day = first + delta + (int64_t)(r->week - 1) * 7;
372 int y2, m2, d2;
373 tz_civil_from_days(day, &y2, &m2, &d2);
374 while (m2 != r->month) { /* week 5 spilled over */
375 day -= 7;
376 tz_civil_from_days(day, &y2, &m2, &d2);
377 }
378 return day;
379 }
380}
381
382/* The UTC instant `year`'s rule fires at, given the offset in force before it. */
383static int64_t rule_utc(const rule_date *r, int year, int before_east)
384{
385 return rule_day(r, year) * 86400 + r->time - before_east;
386}
387
388static int posix_is_dst(const posix_tz *p, int64_t utc)
389{
390 /* The rule names two instants per year; DST is in force after a start
391 * event and before the next end event. Sorting the events of the
392 * surrounding years and taking the last one at or before `utc` handles a
393 * northern rule, a southern rule (start after end within a year) and a
394 * rule whose changeovers sit at 24:00 or -01:00 without a special case
395 * for any of them. The earlier "does the window contain utc" form
396 * answered DST forever after a southern zone's start date, because
397 * "utc >= start of last season" stays true for the rest of the year. */
398 struct { int64_t t; int on; } ev[9];
399 int n = 0, i, j, k;
400 int year, month, day;
401
402 if (!p->has_dst) return 0;
403 tz_civil_from_days((utc + p->std_off) / 86400, &year, &month, &day);
404
405 for (k = -1; k <= 1; k++) {
406 int y = year + k;
407 if (n < 8) { ev[n].t = rule_utc(&p->start, y, p->std_off); ev[n++].on = 1; }
408 if (n < 8) { ev[n].t = rule_utc(&p->end, y, p->dst_off); ev[n++].on = 0; }
409 }
410 for (i = 1; i < n; i++) { /* insertion sort, n <= 9 */
411 for (j = i; j > 0 && ev[j - 1].t > ev[j].t; j--) {
412 int64_t t = ev[j].t;
413 int on = ev[j].on;
414 ev[j].t = ev[j - 1].t;
415 ev[j].on = ev[j - 1].on;
416 ev[j - 1].t = t;
417 ev[j - 1].on = on;
418 }
419 }
420 for (i = n - 1; i >= 0; i--) if (ev[i].t <= utc) return ev[i].on;
421 return 0;
422}
423/* ------------------------------------------------------------------ */
424/* Offset lookup */
425/* ------------------------------------------------------------------ */
426
427static int zone_abbr(const tz_zone *z, uint16_t off, char *abbr, size_t sz)
428{
429 const char *a = TZ_ABBR_POOL + off;
430 if (abbr && sz) {
431 size_t n = strlen(a);
432 if (n >= sz) n = sz - 1;
433 memcpy(abbr, a, n);
434 abbr[n] = '\0';
435 }
436 (void)z;
437 return 0;
438}
439
440int tz_offset(const tz_zone *z, int64_t utc, int *is_dst,
441 char *abbr, size_t abbrsz)
442{
443 const tz_zone_t *r;
444 int64_t rel;
445 int lo, hi, hit;
446 posix_tz pz;
447
448 if (!z) return 0;
449 r = z->rec;
450
451 if (utc < TZ_WINDOW_EPOCH) {
452 if (is_dst) *is_dst = r->base_dst;
453 zone_abbr(z, r->base_abbr, abbr, abbrsz);
454 return r->base_off;
455 }
456 rel = utc - TZ_WINDOW_EPOCH;
457
458 /* Last transition at or before `rel` inside this zone's slice. */
459 lo = 0;
460 hi = (int)r->count - 1;
461 hit = -1;
462 while (lo <= hi) {
463 int mid = lo + (hi - lo) / 2;
464 uint32_t t = TZ_TR_T[r->first + (uint32_t)mid];
465 if ((int64_t)t <= rel) { hit = mid; lo = mid + 1; }
466 else { hi = mid - 1; }
467 }
468 if (hit >= 0) {
469 uint32_t i = r->first + (uint32_t)hit;
470 /* A query PAST this zone's last embedded transition must go to the
471 * POSIX rule below, not to the last row: the last row is whatever
472 * state the tz database stopped generating transitions in, and for
473 * most zones that is standard time in 2037. Returning it made every
474 * zone answer "no DST" from 2038 on - valid JSON, wrong answer,
475 * forever. */
476 int past_last = (r->count > 0 &&
477 (int64_t)TZ_TR_T[r->first + r->count - 1] < rel);
478 if (!(r->has_rule && past_last)) {
479 if (is_dst) *is_dst = TZ_TR_DST[i] ? 1 : 0;
480 zone_abbr(z, TZ_TR_ABBR[i], abbr, abbrsz);
481 return TZ_TR_OFF[i];
482 }
483 }
484
485 /* Before this zone's first embedded transition but after the window
486 * start: the base state still holds. */
487 if (r->count == 0 || rel < (int64_t)TZ_TR_T[r->first]) {
488 /* Only fall through to the POSIX rule when we are past the zone's
489 * last transition (a zone whose slice is empty uses base forever). */
490 if (r->count == 0) {
491 if (is_dst) *is_dst = r->base_dst;
492 zone_abbr(z, r->base_abbr, abbr, abbrsz);
493 return r->base_off;
494 }
495 }
496
497 /* Past the last embedded transition: the zone's own POSIX rule decides,
498 * which is exactly how a host with less tzdata behaves. */
499 if (r->has_rule && posix_parse(TZ_RULE_POOL + r->rule, &pz) == 0) {
500 int dst = posix_is_dst(&pz, utc);
501 if (is_dst) *is_dst = dst;
502 if (abbr && abbrsz) {
503 /* Reuse the abbreviation of the most recent embedded transition
504 * that had the same DST state; that is the name the zone uses. */
505 int i;
506 const char *best = NULL;
507 for (i = (int)r->count - 1; i >= 0; i--) {
508 uint32_t j = r->first + (uint32_t)i;
509 if ((TZ_TR_DST[j] ? 1 : 0) == dst) {
510 best = TZ_ABBR_POOL + TZ_TR_ABBR[j];
511 break;
512 }
513 }
514 if (!best) best = TZ_ABBR_POOL + r->base_abbr;
515 {
516 size_t n = strlen(best);
517 if (n >= abbrsz) n = abbrsz - 1;
518 memcpy(abbr, best, n);
519 abbr[n] = '\0';
520 }
521 }
522 return dst ? pz.dst_off : pz.std_off;
523 }
524
525 if (is_dst) *is_dst = r->base_dst;
526 zone_abbr(z, r->base_abbr, abbr, abbrsz);
527 return r->base_off;
528}
529
530/* ------------------------------------------------------------------ */
531/* Wall clock -> UTC */
532/* */
533/* Every distinct offset in force anywhere near `wall` is a candidate; */
534/* an offset is valid only if applying it lands on an instant whose */
535/* offset is that same value. That test is what distinguishes the two */
536/* readings of a repeated hour from a time that never happened. */
537/* ------------------------------------------------------------------ */
538
539static int cand_push(tz_cand_t *out, int n, int max,
540 int64_t utc, int off, int dst)
541{
542 int i;
543 for (i = 0; i < n; i++) if (out[i].utc == utc) return n;
544 if (n >= max) return n;
545 out[n].utc = utc;
546 out[n].offset = off;
547 out[n].is_dst = dst;
548 return n + 1;
549}
550
551static int cand_cmp(const void *a, const void *b)
552{
553 int64_t x = ((const tz_cand_t *)a)->utc;
554 int64_t y = ((const tz_cand_t *)b)->utc;
555 return (x < y) ? -1 : (x > y) ? 1 : 0;
556}
557
558int tz_resolve_wall(const tz_zone *z, int64_t wall, tz_cand_t *out, int outmax)
559{
560 const tz_zone_t *r;
561 int offs[TZ_MAX_CANDIDATES * 4];
562 int noffs = 0;
563 int n = 0, i;
564 int64_t probes[7];
565 int p;
566
567 if (!z || !out || outmax <= 0) return 0;
568 r = z->rec;
569
570 /* Offsets in force just before and just after the wall time, plus every
571 * transition within a two-day margin of it (a shift can be more than an
572 * hour, and a rule can move the change across midnight). */
573 probes[0] = wall - 3 * 86400;
574 probes[1] = wall - 86400;
575 probes[2] = wall - 3600;
576 probes[3] = wall;
577 probes[4] = wall + 3600;
578 probes[5] = wall + 86400;
579 probes[6] = wall + 3 * 86400;
580 for (p = 0; p < 7; p++) {
581 int dst = 0;
582 int o = tz_offset(z, probes[p], &dst, NULL, 0);
583 int dup = 0;
584 for (i = 0; i < noffs; i++) if (offs[i] == o) { dup = 1; break; }
585 if (!dup && noffs < (int)(sizeof offs / sizeof offs[0])) offs[noffs++] = o;
586 }
587 {
588 int64_t lo = wall - 3 * 86400, hi = wall + 3 * 86400;
589 int64_t rel_lo = lo - TZ_WINDOW_EPOCH, rel_hi = hi - TZ_WINDOW_EPOCH;
590 int j;
591 for (j = 0; j < (int)r->count; j++) {
592 uint32_t k = r->first + (uint32_t)j;
593 int64_t t = (int64_t)TZ_TR_T[k];
594 if (t < rel_lo) continue;
595 if (t > rel_hi) break;
596 {
597 int o = TZ_TR_OFF[k];
598 int dup = 0;
599 for (i = 0; i < noffs; i++) if (offs[i] == o) { dup = 1; break; }
600 if (!dup && noffs < (int)(sizeof offs / sizeof offs[0]))
601 offs[noffs++] = o;
602 }
603 }
604 }
605
606 for (i = 0; i < noffs; i++) {
607 int64_t utc = wall - offs[i];
608 int dst = 0;
609 int o = tz_offset(z, utc, &dst, NULL, 0);
610 if (o == offs[i]) n = cand_push(out, n, outmax, utc, o, dst);
611 }
612 qsort(out, (size_t)n, sizeof *out, cand_cmp);
613 return n;
614}
615
616/* ------------------------------------------------------------------ */
617/* The node's own zone */
618/* ------------------------------------------------------------------ */
619
620static char g_local_name[128];
621static int g_local_done = 0;
622
623static int name_ok(const char *s)
624{
625 return s && *s && tz_find(s) != NULL;
626}
627
628#if !defined(_WIN32)
629/* /etc/localtime is a symlink into the zoneinfo tree on most Linux hosts and
630 * on macOS; the key is the tail of the link target after "zoneinfo/". */
631static int name_from_localtime_link(void)
632{
633 static const char *paths[2] = { "/etc/localtime",
634 "/var/db/timezone/localtime" };
635 int i;
636 for (i = 0; i < 2; i++) {
637 char buf[PATH_MAX];
638 ssize_t n = readlink(paths[i], buf, sizeof buf - 1);
639 const char *p;
640 if (n <= 0) continue;
641 buf[n] = '\0';
642 p = strstr(buf, "zoneinfo/");
643 if (p && name_ok(p + 9)) {
644 snprintf(g_local_name, sizeof g_local_name, "%s", p + 9);
645 return 1;
646 }
647 p = strstr(buf, "zoneinfo.default/");
648 if (p && name_ok(p + 16)) {
649 snprintf(g_local_name, sizeof g_local_name, "%s", p + 16);
650 return 1;
651 }
652 }
653 return 0;
654}
655
656/* Debian/Ubuntu keep the key in /etc/timezone as plain text. */
657static int name_from_etc_timezone(void)
658{
659 char buf[128];
660 FILE *f = fopen("/etc/timezone", "r");
661 size_t n;
662
663 if (!f) return 0;
664 n = fread(buf, 1, sizeof buf - 1, f);
665 fclose(f);
666 if (n == 0) return 0;
667 buf[n] = '\0';
668 while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r' ||
669 buf[n - 1] == ' ' || buf[n - 1] == '\t')) buf[--n] = '\0';
670 if (!name_ok(buf)) return 0;
671 snprintf(g_local_name, sizeof g_local_name, "%s", buf);
672 return 1;
673}
674#endif
675
676/* Offset-only fallback: the current local offset, DST state and - on POSIX -
677 * the abbreviation, matched against the embedded table. An offset alone cannot
678 * distinguish Europe/Paris (CET) from Africa/Lagos (WAT) in winter, so the
679 * abbreviation is the discriminator where the platform reports one. A
680 * "Region/City" key beats a bare legacy key (UTC, GMT, EST) so the answer is
681 * stable and useful; the table is sorted, so it is deterministic. */
682static int name_from_offset(void)
683{
684 int64_t now = (int64_t)time(NULL);
685 int off;
686 int dst;
687 int i;
688 int fallback = -1;
689 char abbr[24];
690
691 abbr[0] = '\0';
692
693#if defined(_WIN32)
694 {
695 /* GetDynamicTimeZoneInformation, not GetTimeZoneInformation: the
696 * latter's StandardName is LOCALISED ("Neuseeland Normalzeit" on a
697 * German Windows), while TimeZoneKeyName is always the invariant
698 * registry id every CLDR row is keyed on. Falling back to the old call
699 * keeps a pre-Vista build working. */
700 DYNAMIC_TIME_ZONE_INFORMATION tz;
701 DWORD kind = GetDynamicTimeZoneInformation(&tz);
702 long bias;
703 char id[128];
704
705 bias = tz.Bias + ((kind == TIME_ZONE_ID_DAYLIGHT)
706 ? tz.DaylightBias : tz.StandardBias);
707 if (kind == TIME_ZONE_ID_INVALID) { off = 0; dst = 0; }
708 off = (int)(-bias * 60);
709 dst = (kind == TIME_ZONE_ID_DAYLIGHT);
710 /* The registry name is the authoritative answer: it names a region,
711 * where an offset names a band shared by a dozen of them. CLDR's map
712 * turns it into the same IANA key every other platform reports.
713 * StandardName is the key CLDR carries ("New Zealand Standard Time"),
714 * so it is tried first; DaylightName ("... Daylight Time") is only a
715 * fallback for a map that happens to carry one. */
716 WideCharToMultiByte(CP_UTF8, 0, tz.TimeZoneKeyName, -1, id, sizeof id,
717 NULL, NULL);
718 if (tz_find_windows(id)) {
719 snprintf(g_local_name, sizeof g_local_name, "%s",
720 tz_zone_name(tz_find_windows(id)));
721 return 1;
722 }
723 WideCharToMultiByte(CP_UTF8, 0, tz.StandardName, -1, id, sizeof id,
724 NULL, NULL);
725 if (tz_find_windows(id)) {
726 snprintf(g_local_name, sizeof g_local_name, "%s",
727 tz_zone_name(tz_find_windows(id)));
728 return 1;
729 }
730 }
731#else
732 {
733 time_t t = (time_t)now;
734 struct tm lt;
735 if (!localtime_r(&t, &lt)) return 0;
736 off = (int)lt.tm_gmtoff;
737 dst = lt.tm_isdst > 0;
738 if (lt.tm_zone) snprintf(abbr, sizeof abbr, "%s", lt.tm_zone);
739 }
740#endif
741 for (i = 0; i < tz_count(); i++) {
742 const tz_zone *z = tz_find(tz_name_at(i));
743 const char *nm = tz_name_at(i);
744 char za[24];
745 int d = 0;
746 int o;
747
748 if (!z) continue;
749 o = tz_offset(z, now, &d, za, sizeof za);
750 if (o != off || d != dst) continue;
751 if (abbr[0] && strcmp(za, abbr) != 0) continue;
752 if (!strchr(nm, '/')) {
753 if (fallback < 0) fallback = i;
754 continue;
755 }
756 fallback = i;
757 break;
758 }
759 if (fallback >= 0) {
760 snprintf(g_local_name, sizeof g_local_name, "%s", tz_name_at(fallback));
761 return 1;
762 }
763 return 0;
764}
765
766const char *tz_local_name(void)
767{
768 const char *env;
769
770 if (g_local_done) return g_local_name;
771 g_local_done = 1;
772
773 env = getenv("TZ");
774 if (env && *env) {
775 if (env[0] == ':') env++;
776 if (name_ok(env)) {
777 snprintf(g_local_name, sizeof g_local_name, "%s", env);
778 return g_local_name;
779 }
780 }
781#if !defined(_WIN32)
782 if (name_from_localtime_link()) return g_local_name;
783 if (name_from_etc_timezone()) return g_local_name;
784#endif
785 if (name_from_offset()) return g_local_name;
786
787 snprintf(g_local_name, sizeof g_local_name, "UTC");
788 return g_local_name;
789}