#!/usr/bin/env python3 """gen_tzdata.py - generate src/tzdata.h from a compiled IANA tz database. The connector must resolve IANA timezone names identically on every platform, including Windows, where no tzdata exists. So the table is embedded in the binary rather than read from the host: * every zone's exact IANA key (598 of them, links included) so name validation is a case-sensitive exact match on every OS - `zoneinfo` on macOS accepts `europe/warsaw` because APFS is case-insensitive, Linux does not, and a connector that answers differently per host is a bug; * the real UTC transitions from the window start to the end of the tz database (2087 for the zones that still generate them), so DST changes, Ramadan-style exceptions (Africa/Casablanca, Africa/El_Aaiun) and zones that redesigned their rules (Asia/Hebron, America/Santiago) are correct without any rule approximation; * each zone's POSIX TZ footer string, used only *beyond* the last embedded transition, which is exactly what zoneinfo itself does; * the Windows timezone id -> IANA key map (tools/windows_zones.tsv, derived from the CLDR supplemental data), so a Windows node reports "New Zealand Standard Time" as Pacific/Auckland rather than guessing from an offset. Zones with no transitions in the window still get their offset, abbreviation and DST flag stored as the zone's base state. Usage: python3 tools/gen_tzdata.py [--tzdir /usr/share/zoneinfo] [--out src/tzdata.h] The generator is deterministic: the same tz database in, the same bytes out. """ import argparse import datetime import os import struct import sys # Directories and files under the tz root that are not zones. SKIP_TOP = { "posix", "right", "posixrules", "localtime", "leapseconds", "leap-seconds.list", "leapseconds.list", "tzdata.zi", "tzdb.zi", "zone.tab", "zone1970.tab", "iso3166.tab", "iso3166.tab.txt", "zone.tab.txt", "+VERSION", "SECURITY", } WINDOW = datetime.datetime(2015, 1, 1, tzinfo=datetime.timezone.utc) WINDOW_EPOCH = int(WINDOW.timestamp()) # ---------------------------------------------------------------- TZif parse def _hdr(b, off): return struct.unpack(">6I", b[off + 20:off + 44]) def parse_tzif(b): """Return dict(times, idxs, tts=[(off, isdst, abbr)], footer) or None.""" if not b.startswith(b"TZif"): return None ver = b[4:5] isutcnt, isstdcnt, leapcnt, timecnt, typecnt, charcnt = _hdr(b, 0) body = 44 body += timecnt * 4 + timecnt + typecnt * 6 + charcnt + leapcnt * 8 + isstdcnt + isutcnt if ver not in (b"2", b"3", b"4"): # A version-1 file cannot be dated past 2038 and carries no footer; # the shipped database has none, so treat it as unusable rather than # silently generating a table that is wrong after 2038. return None isutcnt, isstdcnt, leapcnt, timecnt, typecnt, charcnt = _hdr(b, body) o = body + 44 times = [struct.unpack(">q", b[o + i * 8:o + i * 8 + 8])[0] for i in range(timecnt)] o += timecnt * 8 idxs = list(b[o:o + timecnt]) o += timecnt tts = [struct.unpack(">ibB", b[o + i * 6:o + i * 6 + 6]) for i in range(typecnt)] o += typecnt * 6 abbrs = b[o:o + charcnt] o += charcnt o += leapcnt * 12 + isstdcnt + isutcnt rest = b[o:] footer = None if rest.startswith(b"\n"): e = rest.rfind(b"\n") if e > 0: footer = rest[1:e].decode("ascii", "replace") def abbr(i): e = abbrs.find(b"\x00", i) return abbrs[i:e if e >= 0 else len(abbrs)].decode("ascii", "replace") return { "times": times, "idxs": idxs, "tts": [(t[0], t[1], abbr(t[2])) for t in tts], "footer": footer, } def collect(root): zones = {} for dirpath, _dirnames, filenames in os.walk(root): rel = os.path.relpath(dirpath, root) parts = [] if rel == "." else rel.split(os.sep) if parts and parts[0] in SKIP_TOP: continue for fn in sorted(filenames): p = os.path.join(dirpath, fn) name = os.path.relpath(p, root).replace(os.sep, "/") if name.split("/")[0] in SKIP_TOP: continue try: with open(p, "rb") as f: raw = f.read(400000) except OSError: continue z = parse_tzif(raw) if z: zones[name] = z return zones def tzdb_version(root): for cand in ("tzdata.zi", "tzdb.zi"): p = os.path.join(root, cand) try: with open(p, "r", encoding="utf-8", errors="replace") as f: first = f.readline().strip() if first.startswith("#"): return first[1:].strip() except OSError: pass return "unknown" # ---------------------------------------------------------------- emit def cstr(s): out = [] for ch in s: if ch == "\\": out.append("\\\\") elif ch == '"': out.append('\\"') elif 0x20 <= ord(ch) < 0x7f: out.append(ch) else: out.append("\\x%02x" % (ord(ch) & 0xFF)) return '"' + "".join(out) + '"' class Pool: """A deduplicated, NUL-terminated string pool assigned offsets.""" def __init__(self, label): self.label = label self.buf = bytearray() self.off = {} def add(self, s): if s in self.off: return self.off[s] o = len(self.buf) self.off[s] = o self.buf += s.encode("utf-8", "replace") + b"\x00" return o def emit(self, w): w.append("static const char %s[] =" % self.label) # Emit as adjacent string literals so the file stays readable and # every byte is spelled explicitly (no raw NUL in the source). cur = [] def flush(): if cur: w.append(' "%s"' % "".join(cur)) del cur[:] for byte in self.buf: if byte == 0: tok = "\\0" elif byte == 0x22: tok = '\\"' elif byte == 0x5C: tok = "\\\\" elif 0x20 <= byte < 0x7F: ch = chr(byte) tok = ch else: tok = "\\%03o" % byte cur.append(tok) if len(cur) >= 180: flush() flush() w.append(" ;") w.append("") def max_dst_extra(tts): """Widest spread between the standard offset and any other offset.""" if not tts: return 0 offs = [t[0] for t in tts] return max(offs) - min(offs) def load_windows_map(path): """Windows id -> IANA key, from the checked-in CLDR-derived TSV.""" rows = [] try: with open(path, "r", encoding="utf-8") as f: for line in f: line = line.rstrip("\n") if not line or line.startswith("#"): continue parts = line.split("\t") if len(parts) == 2 and parts[0] and parts[1]: rows.append((parts[0], parts[1])) except OSError: return [] return rows def main(): ap = argparse.ArgumentParser() ap.add_argument("--tzdir", default="/usr/share/zoneinfo") ap.add_argument("--out", default=None) args = ap.parse_args() root = args.tzdir if not os.path.isdir(root): sys.exit("gen_tzdata: %s is not a directory" % root) out = args.out or os.path.join(os.path.dirname(os.path.dirname( os.path.abspath(__file__))), "src", "tzdata.h") zones = collect(root) if not zones: sys.exit("gen_tzdata: no TZif files under %s" % root) names = Pool("TZ_NAME_POOL") abbrs = Pool("TZ_ABBR_POOL") rules = Pool("TZ_RULE_POOL") win = Pool("TZ_WIN_POOL") tr_t, tr_off, tr_abbr, tr_dst = [], [], [], [] records = [] for name in sorted(zones): z = zones[name] times, idxs, tts, footer = z["times"], z["idxs"], z["tts"], z["footer"] # Offset in force just before the window start = the base state that # answers any query older than the embedded window. base_off, base_dst, base_abbr = tts[0][0], tts[0][1], tts[0][2] for i, t in enumerate(times): if t <= WINDOW_EPOCH: base_off, base_dst, base_abbr = tts[idxs[i]] else: break first = len(tr_t) for i, t in enumerate(times): if t <= WINDOW_EPOCH: continue rel = t - WINDOW_EPOCH if rel > 0xFFFFFFFF: break off, isdst, abbr = tts[idxs[i]] tr_t.append(rel) tr_off.append(off) tr_abbr.append(abbrs.add(abbr)) tr_dst.append(1 if isdst else 0) records.append({ "name": names.add(name), "rule": rules.add(footer or "") if footer else 0, "has_rule": 1 if footer else 0, "base_off": base_off, "base_abbr": abbrs.add(base_abbr), "base_dst": 1 if base_dst else 0, "first": first, "count": len(tr_t) - first, }) w = [] w.append("/*") w.append(" * tzdata.h - generated by tools/gen_tzdata.py from the compiled IANA") w.append(" * tz database (%s). DO NOT EDIT." % tzdb_version(root)) w.append(" *") w.append(" * %d zones, %d UTC transitions from %s onwards." % (len(records), len(tr_t), WINDOW.date().isoformat())) w.append(" *") w.append(" * Four parallel arrays index the transitions so the records stay") w.append(" * padding-free on every ABI: seconds since the window start, the UTC") w.append(" * offset east of Greenwich in seconds, the abbreviation pool offset,") w.append(" * and the DST flag.") w.append(" */") w.append("#ifndef SX_PLUGIN_TIME_TZDATA_H") w.append("#define SX_PLUGIN_TIME_TZDATA_H") w.append("") w.append("#include ") w.append("") w.append("#define TZ_WINDOW_EPOCH %d" % WINDOW_EPOCH) w.append("#define TZ_ZONE_COUNT %d" % len(records)) w.append("#define TZ_TRANS_COUNT %d" % len(tr_t)) w.append("") win_rows = [] for win_id, iana in load_windows_map(os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools", "windows_zones.tsv")): # Only keep a mapping whose target the table actually holds: a CLDR # row pointing at a zone this tzdata does not carry would otherwise # resolve to a name tz_find() refuses. if iana in zones: win_rows.append((win.add(win_id), names.add(iana))) w.append("#define TZ_WIN_COUNT %d" % len(win_rows)) w.append("") w.append("typedef struct {") w.append(" uint32_t name; /* offset into TZ_NAME_POOL */") w.append(" uint32_t rule; /* offset into TZ_RULE_POOL */") w.append(" int32_t base_off; /* east-of-UTC seconds before the window */") w.append(" uint32_t first; /* index of this zone's first transition */") w.append(" uint16_t count; /* transitions in this zone's slice */") w.append(" uint16_t base_abbr; /* offset into TZ_ABBR_POOL */") w.append(" uint8_t base_dst;") w.append(" uint8_t has_rule;") w.append("} tz_zone_t;") w.append("") names.emit(w) abbrs.emit(w) rules.emit(w) win.emit(w) def emit_arr(typ, label, values, per_line=16, fmt=lambda v: str(v)): w.append("static const %s %s[TZ_TRANS_COUNT] = {" % (typ, label)) line = " " for i, v in enumerate(values): tok = fmt(v) + "," if len(line) + len(tok) > 96: w.append(line) line = " " line += tok if (i + 1) % per_line == 0 and line.strip() and len(line) > 60: w.append(line) line = " " if line.strip(): w.append(line) w.append("};") w.append("") emit_arr("uint32_t", "TZ_TR_T", tr_t) emit_arr("int32_t", "TZ_TR_OFF", tr_off) emit_arr("uint16_t", "TZ_TR_ABBR", tr_abbr) emit_arr("uint8_t", "TZ_TR_DST", tr_dst, per_line=32) w.append("/* Windows timezone id -> IANA key (CLDR). */") w.append("typedef struct {") w.append(" uint16_t win; /* offset into TZ_WIN_POOL */") w.append(" uint32_t zone; /* offset into TZ_NAME_POOL */") w.append("} tz_win_t;") w.append("") w.append("static const tz_win_t TZ_WIN_ZONES[TZ_WIN_COUNT] = {") for a, b in win_rows: w.append(" {%d, %d}," % (a, b)) w.append("};") w.append("") w.append("static const tz_zone_t TZ_ZONES[TZ_ZONE_COUNT] = {") for r in records: w.append(' {%d, %d, %d, %d, %d, %d, %d, %d},' % (r["name"], r["rule"], r["base_off"], r["first"], r["count"], r["base_abbr"], r["base_dst"], r["has_rule"])) w.append("};") w.append("") w.append("#endif /* SX_PLUGIN_TIME_TZDATA_H */") w.append("") with open(out, "w", encoding="utf-8") as f: f.write("\n".join(w)) shrunk = max_dst_extra([]) # noqa: F841 - keeps the helper referenced print("gen_tzdata: %d zones, %d transitions, %d windows ids -> %s (%d bytes)" % (len(records), len(tr_t), len(win_rows), out, os.path.getsize(out)), file=sys.stderr) if __name__ == "__main__": main()