1 From: Joe Orton <jorton@redhat.com>
2 Date: Thu, 20 Oct 2016 11:44:14 +0200
3 Subject: Add support for use of the system timezone database
5 Add support for use of the system timezone database, rather
6 than embedding a copy. Discussed upstream but was not desired.
9 r14: improve check for valid tz file
10 r13: adapt for upstream changes to use PHP allocator
11 r12: adapt for upstream changes for new zic
12 r11: use canonical names to avoid more case sensitivity issues
13 round lat/long from zone.tab towards zero per builtin db
14 r10: make timezone case insensitive
15 r9: fix another compile error without --with-system-tzdata configured (Michael Heimpold)
16 r8: fix compile error without --with-system-tzdata configured
17 r7: improve check for valid timezone id to exclude directories
18 r6: fix fd leak in r5, fix country code/BC flag use in
19 timezone_identifiers_list() using system db,
20 fix use of PECL timezonedb to override system db,
21 r5: reverts addition of "System/Localtime" fake tzname.
22 updated for 5.3.0, parses zone.tab to pick up mapping between
23 timezone name, country code and long/lat coords
24 r4: added "System/Localtime" tzname which uses /etc/localtime
25 r3: fix a crash if /usr/share/zoneinfo doesn't exist (Raphael Geissert)
26 r2: add filesystem trawl to set up name alias index
29 ext/date/lib/parse_tz.c | 560 +++++++++++++++++++++++++++++++++++++++++++++++-
30 ext/date/lib/timelib.m4 | 13 ++
31 2 files changed, 562 insertions(+), 11 deletions(-)
33 diff --git a/ext/date/lib/parse_tz.c b/ext/date/lib/parse_tz.c
34 index 20d7eea..ed7717e 100644
35 --- a/ext/date/lib/parse_tz.c
36 +++ b/ext/date/lib/parse_tz.c
41 +#ifdef HAVE_SYSTEM_TZDATA
42 +#include <sys/mman.h>
43 +#include <sys/stat.h>
48 +#include "php_scandir.h"
58 +#ifndef HAVE_SYSTEM_TZDATA
59 #define TIMELIB_SUPPORTS_V2DATA
60 #include "timezonedb.h"
65 #if (defined(__APPLE__) || defined(__APPLE_CC__)) && (defined(__BIG_ENDIAN__) || defined(__LITTLE_ENDIAN__))
66 # if defined(__LITTLE_ENDIAN__)
67 @@ -59,6 +73,11 @@ static int read_preamble(const unsigned char **tzf, timelib_tzinfo *tz)
71 + if (memcmp(*tzf, "TZif", 4) == 0) {
77 version = (*tzf)[3] - '0';
79 @@ -302,7 +321,429 @@ void timelib_dump_tzinfo(timelib_tzinfo *tz)
83 -static int seek_to_tz_position(const unsigned char **tzf, char *timezone, const timelib_tzdb *tzdb)
84 +#ifdef HAVE_SYSTEM_TZDATA
86 +#ifdef HAVE_SYSTEM_TZDATA_PREFIX
87 +#define ZONEINFO_PREFIX HAVE_SYSTEM_TZDATA_PREFIX
89 +#define ZONEINFO_PREFIX "/usr/share/zoneinfo"
92 +/* System timezone database pointer. */
93 +static const timelib_tzdb *timezonedb_system;
95 +/* Hash table entry for the cache of the zone.tab mapping table. */
96 +struct location_info {
98 + double latitude, longitude;
101 + struct location_info *next;
104 +/* Cache of zone.tab. */
105 +static struct location_info **system_location_table;
107 +/* Size of the zone.tab hash table; a random-ish prime big enough to
108 + * prevent too many collisions. */
109 +#define LOCINFO_HASH_SIZE (1021)
111 +/* Compute a case insensitive hash of str */
112 +static uint32_t tz_hash(const char *str)
114 + const unsigned char *p = (const unsigned char *)str;
115 + uint32_t hash = 5381;
118 + while ((c = tolower(*p++)) != '\0') {
119 + hash = (hash << 5) ^ hash ^ c;
122 + return hash % LOCINFO_HASH_SIZE;
125 +/* Parse an ISO-6709 date as used in zone.tab. Returns end of the
126 + * parsed string on success, or NULL on parse error. On success,
127 + * writes the parsed number to *result. */
128 +static char *parse_iso6709(char *p, double *result)
136 + else if (*p == '-')
142 + for (pend = p; *pend >= '0' && *pend <= '9'; pend++)
145 + /* Annoying encoding used by zone.tab has no decimal point, so use
146 + * the length to determine the format:
154 + if (len < 4 || len > 7) {
159 + v = (p[0] - '0') * 10.0 + (p[1] - '0');
161 + if (len == 5 || len == 7)
162 + v = v * 10.0 + (*p++ - '0');
164 + v += (10.0 * (p[0] - '0')
165 + + p[1] - '0') / 60.0;
169 + v += (10.0 * (p[0] - '0')
170 + + p[1] - '0') / 3600.0;
174 + /* Round to five decimal place, not because it's a good idea,
175 + * but, because the builtin data uses rounded data, so, match
177 + *result = trunc(v * sign * 100000.0) / 100000.0;
182 +/* This function parses the zone.tab file to build up the mapping of
183 + * timezone to country code and geographic location, and returns a
184 + * hash table. The hash table is indexed by the function:
186 + * tz_hash(timezone-name)
188 +static struct location_info **create_location_table(void)
190 + struct location_info **li, *i;
191 + char zone_tab[PATH_MAX];
195 + strncpy(zone_tab, ZONEINFO_PREFIX "/zone.tab", sizeof zone_tab);
197 + fp = fopen(zone_tab, "r");
202 + li = calloc(LOCINFO_HASH_SIZE, sizeof *li);
204 + while (fgets(line, sizeof line, fp)) {
205 + char *p = line, *code, *name, *comment;
207 + double latitude, longitude;
209 + while (isspace(*p))
212 + if (*p == '#' || *p == '\0' || *p == '\n')
215 + if (!isalpha(p[0]) || !isalpha(p[1]) || p[2] != '\t')
223 + /* coords => [+-][D]DDMM[SS][+-][D]DDMM[SS] */
224 + p = parse_iso6709(p, &latitude);
228 + p = parse_iso6709(p, &longitude);
233 + if (!p || *p != '\t') {
237 + /* name = string */
239 + while (*p != '\t' && *p && *p != '\n')
244 + /* comment = string */
246 + while (*p != '\t' && *p && *p != '\n')
249 + if (*p == '\n' || *p == '\t')
252 + hash = tz_hash(name);
253 + i = malloc(sizeof *i);
254 + memcpy(i->code, code, 2);
255 + strncpy(i->name, name, sizeof i->name);
256 + i->comment = strdup(comment);
257 + i->longitude = longitude;
258 + i->latitude = latitude;
259 + i->next = li[hash];
261 + /* printf("%s [%u, %f, %f]\n", name, hash, latitude, longitude); */
269 +/* Return location info from hash table, using given timezone name.
270 + * Returns NULL if the name could not be found. */
271 +const struct location_info *find_zone_info(struct location_info **li,
274 + uint32_t hash = tz_hash(name);
275 + const struct location_info *l;
281 + for (l = li[hash]; l; l = l->next) {
282 + if (strcasecmp(l->name, name) == 0)
289 +/* Filter out some non-tzdata files and the posix/right databases, if
291 +static int index_filter(const struct dirent *ent)
293 + return strcmp(ent->d_name, ".") != 0
294 + && strcmp(ent->d_name, "..") != 0
295 + && strcmp(ent->d_name, "posix") != 0
296 + && strcmp(ent->d_name, "posixrules") != 0
297 + && strcmp(ent->d_name, "right") != 0
298 + && strstr(ent->d_name, ".list") == NULL
299 + && strstr(ent->d_name, ".tab") == NULL;
302 +static int sysdbcmp(const void *first, const void *second)
304 + const timelib_tzdb_index_entry *alpha = first, *beta = second;
306 + return strcasecmp(alpha->id, beta->id);
310 +/* Create the zone identifier index by trawling the filesystem. */
311 +static void create_zone_index(timelib_tzdb *db)
313 + size_t dirstack_size, dirstack_top;
314 + size_t index_size, index_next;
315 + timelib_tzdb_index_entry *db_index;
318 + /* LIFO stack to hold directory entries to scan; each slot is a
319 + * directory name relative to the zoneinfo prefix. */
320 + dirstack_size = 32;
321 + dirstack = malloc(dirstack_size * sizeof *dirstack);
323 + dirstack[0] = strdup("");
327 + db_index = malloc(index_size * sizeof *db_index);
331 + struct dirent **ents;
332 + char name[PATH_MAX], *top;
335 + /* Pop the top stack entry, and iterate through its contents. */
336 + top = dirstack[--dirstack_top];
337 + snprintf(name, sizeof name, ZONEINFO_PREFIX "/%s", top);
339 + count = php_scandir(name, &ents, index_filter, php_alphasort);
341 + while (count > 0) {
343 + const char *leaf = ents[count - 1]->d_name;
345 + snprintf(name, sizeof name, ZONEINFO_PREFIX "/%s/%s",
348 + if (strlen(name) && stat(name, &st) == 0) {
349 + /* Name, relative to the zoneinfo prefix. */
350 + const char *root = top;
352 + if (root[0] == '/') root++;
354 + snprintf(name, sizeof name, "%s%s%s", root,
355 + *root ? "/": "", leaf);
357 + if (S_ISDIR(st.st_mode)) {
358 + if (dirstack_top == dirstack_size) {
359 + dirstack_size *= 2;
360 + dirstack = realloc(dirstack,
361 + dirstack_size * sizeof *dirstack);
363 + dirstack[dirstack_top++] = strdup(name);
366 + if (index_next == index_size) {
368 + db_index = realloc(db_index,
369 + index_size * sizeof *db_index);
372 + db_index[index_next++].id = strdup(name);
376 + free(ents[--count]);
379 + if (count != -1) free(ents);
381 + } while (dirstack_top);
383 + qsort(db_index, index_next, sizeof *db_index, sysdbcmp);
385 + db->index = db_index;
386 + db->index_size = index_next;
391 +#define FAKE_HEADER "1234\0??\1??"
392 +#define FAKE_UTC_POS (7 - 4)
394 +/* Create a fake data segment for database 'sysdb'. */
395 +static void fake_data_segment(timelib_tzdb *sysdb,
396 + struct location_info **info)
401 + data = malloc(3 * sysdb->index_size + 7);
403 + p = mempcpy(data, FAKE_HEADER, sizeof(FAKE_HEADER) - 1);
405 + for (n = 0; n < sysdb->index_size; n++) {
406 + const struct location_info *li;
407 + timelib_tzdb_index_entry *ent;
409 + ent = (timelib_tzdb_index_entry *)&sysdb->index[n];
411 + /* Lookup the timezone name in the hash table. */
412 + if (strcmp(ent->id, "UTC") == 0) {
413 + ent->pos = FAKE_UTC_POS;
417 + li = find_zone_info(info, ent->id);
419 + /* If found, append the BC byte and the
420 + * country code; set the position for this
421 + * section of timezone data. */
422 + ent->pos = (p - data) - 4;
424 + *p++ = li->code[0];
425 + *p++ = li->code[1];
428 + /* If not found, the timezone data can
429 + * point at the header. */
434 + sysdb->data = (unsigned char *)data;
437 +/* Returns true if the passed-in stat structure describes a
438 + * probably-valid timezone file. */
439 +static int is_valid_tzfile(const struct stat *st, int fd)
443 + if (read(fd, buf, 20)!=20) {
446 + lseek(fd, SEEK_SET, 0);
447 + if (memcmp(buf, "TZif", 4)) {
451 + return S_ISREG(st->st_mode) && st->st_size > 20;
454 +/* To allow timezone names to be used case-insensitively, find the
455 + * canonical name for this timezone, if possible. */
456 +static const char *canonical_tzname(const char *timezone)
458 + if (timezonedb_system) {
459 + timelib_tzdb_index_entry *ent, lookup;
461 + lookup.id = (char *)timezone;
463 + ent = bsearch(&lookup, timezonedb_system->index,
464 + timezonedb_system->index_size, sizeof lookup,
474 +/* Return the mmap()ed tzfile if found, else NULL. On success, the
475 + * length of the mapped data is placed in *length. */
476 +static char *map_tzfile(const char *timezone, size_t *length)
478 + char fname[PATH_MAX];
483 + if (timezone[0] == '\0' || strstr(timezone, "..") != NULL) {
487 + snprintf(fname, sizeof fname, ZONEINFO_PREFIX "/%s", canonical_tzname(timezone));
489 + fd = open(fname, O_RDONLY);
492 + } else if (fstat(fd, &st) != 0 || !is_valid_tzfile(&st, fd)) {
497 + *length = st.st_size;
498 + p = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
501 + return p != MAP_FAILED ? p : NULL;
506 +static int inmem_seek_to_tz_position(const unsigned char **tzf, char *timezone, const timelib_tzdb *tzdb)
508 int left = 0, right = tzdb->index_size - 1;
509 #ifdef HAVE_SETLOCALE
510 @@ -341,21 +782,88 @@ static int seek_to_tz_position(const unsigned char **tzf, char *timezone, const
514 +static int seek_to_tz_position(const unsigned char **tzf, char *timezone,
515 + char **map, size_t *maplen,
516 + const timelib_tzdb *tzdb)
518 +#ifdef HAVE_SYSTEM_TZDATA
519 + if (tzdb == timezonedb_system) {
522 + orig = map_tzfile(timezone, maplen);
523 + if (orig == NULL) {
527 + (*tzf) = (unsigned char *)orig;
534 + return inmem_seek_to_tz_position(tzf, timezone, tzdb);
538 const timelib_tzdb *timelib_builtin_db(void)
540 +#ifdef HAVE_SYSTEM_TZDATA
541 + if (timezonedb_system == NULL) {
542 + timelib_tzdb *tmp = malloc(sizeof *tmp);
544 + tmp->version = "0.system";
546 + create_zone_index(tmp);
547 + system_location_table = create_location_table();
548 + fake_data_segment(tmp, system_location_table);
549 + timezonedb_system = tmp;
552 + return timezonedb_system;
554 return &timezonedb_builtin;
558 const timelib_tzdb_index_entry *timelib_timezone_builtin_identifiers_list(int *count)
560 +#ifdef HAVE_SYSTEM_TZDATA
561 + *count = timezonedb_system->index_size;
562 + return timezonedb_system->index;
564 *count = sizeof(timezonedb_idx_builtin) / sizeof(*timezonedb_idx_builtin);
565 return timezonedb_idx_builtin;
569 int timelib_timezone_id_is_valid(char *timezone, const timelib_tzdb *tzdb)
571 const unsigned char *tzf;
572 - return (seek_to_tz_position(&tzf, timezone, tzdb));
574 +#ifdef HAVE_SYSTEM_TZDATA
575 + if (tzdb == timezonedb_system) {
576 + char fname[PATH_MAX];
579 + if (timezone[0] == '\0' || strstr(timezone, "..") != NULL) {
583 + if (system_location_table) {
584 + if (find_zone_info(system_location_table, timezone) != NULL) {
585 + /* found in cache */
590 + snprintf(fname, sizeof fname, ZONEINFO_PREFIX "/%s", canonical_tzname(timezone));
592 + return stat(fname, &st) == 0 && is_valid_tzfile(&st, 0);
596 + return (inmem_seek_to_tz_position(&tzf, timezone, tzdb));
599 static void skip_64bit_preamble(const unsigned char **tzf, timelib_tzinfo *tz)
600 @@ -380,24 +888,54 @@ static void read_64bit_header(const unsigned char **tzf, timelib_tzinfo *tz)
601 timelib_tzinfo *timelib_parse_tzfile(char *timezone, const timelib_tzdb *tzdb)
603 const unsigned char *tzf;
604 + char *memmap = NULL;
609 - if (seek_to_tz_position(&tzf, timezone, tzdb)) {
610 + if (seek_to_tz_position(&tzf, timezone, &memmap, &maplen, tzdb)) {
611 tmp = timelib_tzinfo_ctor(timezone);
613 version = read_preamble(&tzf, tmp);
614 read_header(&tzf, tmp);
615 read_transistions(&tzf, tmp);
616 read_types(&tzf, tmp);
617 - if (version == 2) {
618 - skip_64bit_preamble(&tzf, tmp);
619 - read_64bit_header(&tzf, tmp);
620 - skip_64bit_transistions(&tzf, tmp);
621 - skip_64bit_types(&tzf, tmp);
622 - skip_posix_string(&tzf, tmp);
624 - read_location(&tzf, tmp);
626 +#ifdef HAVE_SYSTEM_TZDATA
628 + const struct location_info *li;
630 + /* TZif-style - grok the location info from the system database,
633 + if ((li = find_zone_info(system_location_table, timezone)) != NULL) {
634 + tmp->location.comments = timelib_strdup(li->comment);
635 + strncpy(tmp->location.country_code, li->code, 2);
636 + tmp->location.longitude = li->longitude;
637 + tmp->location.latitude = li->latitude;
641 + strcpy(tmp->location.country_code, "??");
643 + tmp->location.comments = timelib_strdup("");
646 + /* Now done with the mmap segment - discard it. */
647 + munmap(memmap, maplen);
651 + /* PHP-style - use the embedded info. */
652 + if (version == 2) {
653 + skip_64bit_preamble(&tzf, tmp);
654 + read_64bit_header(&tzf, tmp);
655 + skip_64bit_transistions(&tzf, tmp);
656 + skip_64bit_types(&tzf, tmp);
657 + skip_posix_string(&tzf, tmp);
659 + read_location(&tzf, tmp);
664 diff --git a/ext/date/lib/timelib.m4 b/ext/date/lib/timelib.m4
665 index 99bf9fa..4bf7e46 100644
666 --- a/ext/date/lib/timelib.m4
667 +++ b/ext/date/lib/timelib.m4
668 @@ -78,3 +78,16 @@ stdlib.h
670 dnl Check for strtoll, atoll
671 AC_CHECK_FUNCS(strtoll atoll strftime gettimeofday)
673 +PHP_ARG_WITH(system-tzdata, for use of system timezone data,
674 +[ --with-system-tzdata[=DIR] to specify use of system timezone data],
677 +if test "$PHP_SYSTEM_TZDATA" != "no"; then
678 + AC_DEFINE(HAVE_SYSTEM_TZDATA, 1, [Define if system timezone data is used])
680 + if test "$PHP_SYSTEM_TZDATA" != "yes"; then
681 + AC_DEFINE_UNQUOTED(HAVE_SYSTEM_TZDATA_PREFIX, "$PHP_SYSTEM_TZDATA",
682 + [Define for location of system timezone data])