1ceb81
# License: MIT
1ceb81
# http://opensource.org/licenses/MIT
1ceb81
1ceb81
Add support for use of the system timezone database, rather
1ceb81
than embedding a copy.  Discussed upstream but was not desired.
1ceb81
1ceb81
History:
456590
r21: retrieve tzdata version from /usr/share/zoneinfo/tzdata.zi
1ceb81
r20: adapt for timelib 2020.03 (in 8.0.10RC1)
1ceb81
r19: adapt for timelib 2020.02 (in 8.0.0beta2)
1ceb81
r18: adapt for autotool change in 7.3.3RC1
1ceb81
r17: adapt for timelib 2018.01 (in 7.3.2RC1)
1ceb81
r16: adapt for timelib 2017.06 (in 7.2.3RC1)
1ceb81
r15: adapt for timelib 2017.05beta7 (in 7.2.0RC1)
1ceb81
r14: improve check for valid tz file
1ceb81
r13: adapt for upstream changes to use PHP allocator
1ceb81
r12: adapt for upstream changes for new zic
1ceb81
r11: use canonical names to avoid more case sensitivity issues
1ceb81
     round lat/long from zone.tab towards zero per builtin db
1ceb81
r10: make timezone case insensitive
1ceb81
r9: fix another compile error without --with-system-tzdata configured (Michael Heimpold)
1ceb81
r8: fix compile error without --with-system-tzdata configured
1ceb81
r7: improve check for valid timezone id to exclude directories
1ceb81
r6: fix fd leak in r5, fix country code/BC flag use in
1ceb81
    timezone_identifiers_list() using system db,
1ceb81
    fix use of PECL timezonedb to override system db,
1ceb81
r5: reverts addition of "System/Localtime" fake tzname.
1ceb81
    updated for 5.3.0, parses zone.tab to pick up mapping between
1ceb81
    timezone name, country code and long/lat coords
1ceb81
r4: added "System/Localtime" tzname which uses /etc/localtime
1ceb81
r3: fix a crash if /usr/share/zoneinfo doesn't exist (Raphael Geissert)
1ceb81
r2: add filesystem trawl to set up name alias index
1ceb81
r1: initial revision
1ceb81
456590
diff --git a/ext/date/config0.m4 b/ext/date/config0.m4
456590
index 20e4164aaa..a61243646d 100644
456590
--- a/ext/date/config0.m4
456590
+++ b/ext/date/config0.m4
1ceb81
@@ -4,6 +4,19 @@ AC_CHECK_HEADERS([io.h])
1ceb81
 dnl Check for strtoll, atoll
1ceb81
 AC_CHECK_FUNCS(strtoll atoll)
1ceb81
 
1ceb81
+PHP_ARG_WITH(system-tzdata, for use of system timezone data,
1ceb81
+[  --with-system-tzdata[=DIR]      to specify use of system timezone data],
1ceb81
+no, no)
1ceb81
+
1ceb81
+if test "$PHP_SYSTEM_TZDATA" != "no"; then
1ceb81
+   AC_DEFINE(HAVE_SYSTEM_TZDATA, 1, [Define if system timezone data is used])
1ceb81
+
1ceb81
+   if test "$PHP_SYSTEM_TZDATA" != "yes"; then
1ceb81
+      AC_DEFINE_UNQUOTED(HAVE_SYSTEM_TZDATA_PREFIX, "$PHP_SYSTEM_TZDATA",
1ceb81
+                         [Define for location of system timezone data])
1ceb81
+   fi
1ceb81
+fi
1ceb81
+
1ceb81
 PHP_DATE_CFLAGS="-I@ext_builddir@/lib -DZEND_ENABLE_STATIC_TSRMLS_CACHE=1 -DHAVE_TIMELIB_CONFIG_H=1"
1ceb81
 timelib_sources="lib/astro.c lib/dow.c lib/parse_date.c lib/parse_tz.c
1ceb81
                  lib/timelib.c lib/tm2unixtime.c lib/unixtime2tm.c lib/parse_iso_intervals.c lib/interval.c"
456590
diff --git a/ext/date/lib/parse_tz.c b/ext/date/lib/parse_tz.c
456590
index e9bd0f136d..c04ff01adc 100644
456590
--- a/ext/date/lib/parse_tz.c
456590
+++ b/ext/date/lib/parse_tz.c
1ceb81
@@ -26,8 +26,21 @@
1ceb81
 #include "timelib.h"
1ceb81
 #include "timelib_private.h"
1ceb81
 
1ceb81
+#ifdef HAVE_SYSTEM_TZDATA
1ceb81
+#include <sys/mman.h>
1ceb81
+#include <sys/stat.h>
1ceb81
+#include <limits.h>
1ceb81
+#include <fcntl.h>
1ceb81
+#include <unistd.h>
1ceb81
+
1ceb81
+#include "php_scandir.h"
1ceb81
+
1ceb81
+#else
1ceb81
 #define TIMELIB_SUPPORTS_V2DATA
1ceb81
 #include "timezonedb.h"
1ceb81
+#endif
1ceb81
+
1ceb81
+#include <ctype.h>
1ceb81
 
1ceb81
 #if (defined(__APPLE__) || defined(__APPLE_CC__)) && (defined(__BIG_ENDIAN__) || defined(__LITTLE_ENDIAN__))
1ceb81
 # if defined(__LITTLE_ENDIAN__)
456590
@@ -94,6 +107,11 @@ static int read_php_preamble(const unsigned char **tzf, timelib_tzinfo *tz)
1ceb81
 {
1ceb81
 	uint32_t version;
1ceb81
 
1ceb81
+	if (memcmp(*tzf, "TZif", 4) == 0) {
1ceb81
+		*tzf += 20;
1ceb81
+		return 0;
1ceb81
+	}
1ceb81
+
1ceb81
 	/* read ID */
1ceb81
 	version = (*tzf)[3] - '0';
1ceb81
 	*tzf += 4;
456590
@@ -435,7 +453,467 @@ void timelib_dump_tzinfo(timelib_tzinfo *tz)
1ceb81
 	}
1ceb81
 }
1ceb81
 
1ceb81
-static int seek_to_tz_position(const unsigned char **tzf, const char *timezone, const timelib_tzdb *tzdb)
1ceb81
+#ifdef HAVE_SYSTEM_TZDATA
1ceb81
+
1ceb81
+#ifdef HAVE_SYSTEM_TZDATA_PREFIX
1ceb81
+#define ZONEINFO_PREFIX HAVE_SYSTEM_TZDATA_PREFIX
1ceb81
+#else
1ceb81
+#define ZONEINFO_PREFIX "/usr/share/zoneinfo"
1ceb81
+#endif
1ceb81
+
1ceb81
+/* System timezone database pointer. */
1ceb81
+static const timelib_tzdb *timezonedb_system;
1ceb81
+
1ceb81
+/* Hash table entry for the cache of the zone.tab mapping table. */
1ceb81
+struct location_info {
1ceb81
+        char code[2];
1ceb81
+        double latitude, longitude;
1ceb81
+        char name[64];
1ceb81
+        char *comment;
1ceb81
+        struct location_info *next;
1ceb81
+};
1ceb81
+
1ceb81
+/* Cache of zone.tab. */
1ceb81
+static struct location_info **system_location_table;
1ceb81
+
1ceb81
+/* Size of the zone.tab hash table; a random-ish prime big enough to
1ceb81
+ * prevent too many collisions. */
1ceb81
+#define LOCINFO_HASH_SIZE (1021)
1ceb81
+
1ceb81
+/* Compute a case insensitive hash of str */
1ceb81
+static uint32_t tz_hash(const char *str)
1ceb81
+{
1ceb81
+    const unsigned char *p = (const unsigned char *)str;
1ceb81
+    uint32_t hash = 5381;
1ceb81
+    int c;
1ceb81
+
1ceb81
+    while ((c = tolower(*p++)) != '\0') {
1ceb81
+        hash = (hash << 5) ^ hash ^ c;
1ceb81
+    }
1ceb81
+
1ceb81
+    return hash % LOCINFO_HASH_SIZE;
1ceb81
+}
1ceb81
+
1ceb81
+/* Parse an ISO-6709 date as used in zone.tab. Returns end of the
1ceb81
+ * parsed string on success, or NULL on parse error.  On success,
1ceb81
+ * writes the parsed number to *result. */
1ceb81
+static char *parse_iso6709(char *p, double *result)
1ceb81
+{
1ceb81
+    double v, sign;
1ceb81
+    char *pend;
1ceb81
+    size_t len;
1ceb81
+
1ceb81
+    if (*p == '+')
1ceb81
+        sign = 1.0;
1ceb81
+    else if (*p == '-')
1ceb81
+        sign = -1.0;
1ceb81
+    else
1ceb81
+        return NULL;
1ceb81
+
1ceb81
+    p++;
1ceb81
+    for (pend = p; *pend >= '0' && *pend <= '9'; pend++)
1ceb81
+        ;;
1ceb81
+
1ceb81
+    /* Annoying encoding used by zone.tab has no decimal point, so use
1ceb81
+     * the length to determine the format:
1ceb81
+     * 
1ceb81
+     * 4 = DDMM
1ceb81
+     * 5 = DDDMM
1ceb81
+     * 6 = DDMMSS
1ceb81
+     * 7 = DDDMMSS
1ceb81
+     */
1ceb81
+    len = pend - p;
1ceb81
+    if (len < 4 || len > 7) {
1ceb81
+        return NULL;
1ceb81
+    }
1ceb81
+
1ceb81
+    /* p => [D]DD */
1ceb81
+    v = (p[0] - '0') * 10.0 + (p[1] - '0');
1ceb81
+    p += 2;
1ceb81
+    if (len == 5 || len == 7)
1ceb81
+        v = v * 10.0 + (*p++ - '0');
1ceb81
+    /* p => MM[SS] */
1ceb81
+    v += (10.0 * (p[0] - '0')
1ceb81
+          + p[1] - '0') / 60.0;
1ceb81
+    p += 2;
1ceb81
+    /* p => [SS] */
1ceb81
+    if (len > 5) {
1ceb81
+        v += (10.0 * (p[0] - '0')
1ceb81
+              + p[1] - '0') / 3600.0;
1ceb81
+        p += 2;
1ceb81
+    }
1ceb81
+
1ceb81
+    /* Round to five decimal place, not because it's a good idea,
1ceb81
+     * but, because the builtin data uses rounded data, so, match
1ceb81
+     * that. */
1ceb81
+    *result = trunc(v * sign * 100000.0) / 100000.0;
1ceb81
+
1ceb81
+    return p;
1ceb81
+}
1ceb81
+
1ceb81
+/* This function parses the zone.tab file to build up the mapping of
1ceb81
+ * timezone to country code and geographic location, and returns a
1ceb81
+ * hash table.  The hash table is indexed by the function:
1ceb81
+ *
1ceb81
+ *   tz_hash(timezone-name)
1ceb81
+ */
1ceb81
+static struct location_info **create_location_table(void)
1ceb81
+{
1ceb81
+    struct location_info **li, *i;
1ceb81
+    char zone_tab[PATH_MAX];
1ceb81
+    char line[512];
1ceb81
+    FILE *fp;
1ceb81
+
1ceb81
+    strncpy(zone_tab, ZONEINFO_PREFIX "/zone.tab", sizeof zone_tab);
1ceb81
+
1ceb81
+    fp = fopen(zone_tab, "r");
1ceb81
+    if (!fp) {
1ceb81
+        return NULL;
1ceb81
+    }
1ceb81
+
1ceb81
+    li = calloc(LOCINFO_HASH_SIZE, sizeof *li);
1ceb81
+
1ceb81
+    while (fgets(line, sizeof line, fp)) {
1ceb81
+        char *p = line, *code, *name, *comment;
1ceb81
+        uint32_t hash;
1ceb81
+        double latitude, longitude;
1ceb81
+
1ceb81
+        while (isspace(*p))
1ceb81
+            p++;
1ceb81
+
1ceb81
+        if (*p == '#' || *p == '\0' || *p == '\n')
1ceb81
+            continue;
1ceb81
+        
1ceb81
+        if (!isalpha(p[0]) || !isalpha(p[1]) || p[2] != '\t')
1ceb81
+            continue;
1ceb81
+        
1ceb81
+        /* code => AA */
1ceb81
+        code = p;
1ceb81
+        p[2] = 0;
1ceb81
+        p += 3;
1ceb81
+
1ceb81
+        /* coords => [+-][D]DDMM[SS][+-][D]DDMM[SS] */
1ceb81
+        p = parse_iso6709(p, &latitude);
1ceb81
+        if (!p) {
1ceb81
+            continue;
1ceb81
+        }
1ceb81
+        p = parse_iso6709(p, &longitude);
1ceb81
+        if (!p) {
1ceb81
+            continue;
1ceb81
+        }
1ceb81
+
1ceb81
+        if (!p || *p != '\t') {
1ceb81
+            continue;
1ceb81
+        }
1ceb81
+
1ceb81
+        /* name = string */
1ceb81
+        name = ++p;
1ceb81
+        while (*p != '\t' && *p && *p != '\n')
1ceb81
+            p++;
1ceb81
+
1ceb81
+        *p++ = '\0';
1ceb81
+
1ceb81
+        /* comment = string */
1ceb81
+        comment = p;
1ceb81
+        while (*p != '\t' && *p && *p != '\n')
1ceb81
+            p++;
1ceb81
+
1ceb81
+        if (*p == '\n' || *p == '\t')
1ceb81
+            *p = '\0';
1ceb81
+        
1ceb81
+        hash = tz_hash(name);
1ceb81
+        i = malloc(sizeof *i);
1ceb81
+        memcpy(i->code, code, 2);
1ceb81
+        strncpy(i->name, name, sizeof i->name);
1ceb81
+        i->comment = strdup(comment);
1ceb81
+        i->longitude = longitude;
1ceb81
+        i->latitude = latitude;
1ceb81
+        i->next = li[hash];
1ceb81
+        li[hash] = i;
1ceb81
+        /* printf("%s [%u, %f, %f]\n", name, hash, latitude, longitude); */
1ceb81
+    }
1ceb81
+
1ceb81
+    fclose(fp);
1ceb81
+
1ceb81
+    return li;
1ceb81
+}
1ceb81
+
1ceb81
+/* Return location info from hash table, using given timezone name.
1ceb81
+ * Returns NULL if the name could not be found. */
1ceb81
+const struct location_info *find_zone_info(struct location_info **li, 
1ceb81
+                                           const char *name)
1ceb81
+{
1ceb81
+    uint32_t hash = tz_hash(name);
1ceb81
+    const struct location_info *l;
1ceb81
+
1ceb81
+    if (!li) {
1ceb81
+        return NULL;
1ceb81
+    }
1ceb81
+
1ceb81
+    for (l = li[hash]; l; l = l->next) {
1ceb81
+        if (timelib_strcasecmp(l->name, name) == 0)
1ceb81
+            return l;
1ceb81
+    }
1ceb81
+
1ceb81
+    return NULL;
1ceb81
+}    
1ceb81
+
1ceb81
+/* Filter out some non-tzdata files and the posix/right databases, if
1ceb81
+ * present. */
1ceb81
+static int index_filter(const struct dirent *ent)
1ceb81
+{
1ceb81
+	return strcmp(ent->d_name, ".") != 0
1ceb81
+		&& strcmp(ent->d_name, "..") != 0
1ceb81
+		&& strcmp(ent->d_name, "posix") != 0
1ceb81
+		&& strcmp(ent->d_name, "posixrules") != 0
1ceb81
+		&& strcmp(ent->d_name, "right") != 0
1ceb81
+		&& strstr(ent->d_name, ".list") == NULL
1ceb81
+		&& strstr(ent->d_name, ".tab") == NULL;
1ceb81
+}
1ceb81
+
1ceb81
+static int sysdbcmp(const void *first, const void *second)
1ceb81
+{
1ceb81
+        const timelib_tzdb_index_entry *alpha = first, *beta = second;
1ceb81
+
1ceb81
+        return timelib_strcasecmp(alpha->id, beta->id);
1ceb81
+}
1ceb81
+
1ceb81
+
456590
+/* Retrieve tzdata version. */
456590
+static void retrieve_zone_version(timelib_tzdb *db)
456590
+{
456590
+    static char buf[30];
456590
+    char path[PATH_MAX];
456590
+    FILE *fp;
456590
+
456590
+    strncpy(path, ZONEINFO_PREFIX "/tzdata.zi", sizeof(path));
456590
+
456590
+    fp = fopen(path, "r");
456590
+    if (fp) {
456590
+		if (fgets(buf, sizeof(buf), fp)) {
456590
+			if (!memcmp(buf, "# version ", 10) &&
456590
+				isdigit(buf[10]) &&
456590
+				isdigit(buf[11]) &&
456590
+				isdigit(buf[12]) &&
456590
+				isdigit(buf[13]) &&
456590
+				islower(buf[14])) {
456590
+				if (buf[14] >= 't') {        /* 2022t = 2022.20 */
456590
+					buf[17] = 0;
456590
+					buf[16] = buf[14] - 't' + '0';
456590
+					buf[15] = '2';
456590
+				} else if (buf[14] >= 'j') { /* 2022j = 2022.10 */
456590
+					buf[17] = 0;
456590
+					buf[16] = buf[14] - 'j' + '0';
456590
+					buf[15] = '1';
456590
+				} else {                     /* 2022a = 2022.1  */
456590
+					buf[16] = 0;
456590
+					buf[15] = buf[14] - 'a' + '1';
456590
+				}
456590
+				buf[14] = '.';
456590
+				db->version = buf+10;
456590
+			}
456590
+		}
456590
+		fclose(fp);
456590
+    }
456590
+}
456590
+
1ceb81
+/* Create the zone identifier index by trawling the filesystem. */
1ceb81
+static void create_zone_index(timelib_tzdb *db)
1ceb81
+{
1ceb81
+	size_t dirstack_size,  dirstack_top;
1ceb81
+	size_t index_size, index_next;
1ceb81
+	timelib_tzdb_index_entry *db_index;
1ceb81
+	char **dirstack;
1ceb81
+
1ceb81
+	/* LIFO stack to hold directory entries to scan; each slot is a
1ceb81
+	 * directory name relative to the zoneinfo prefix. */
1ceb81
+	dirstack_size = 32;
1ceb81
+	dirstack = malloc(dirstack_size * sizeof *dirstack);
1ceb81
+	dirstack_top = 1;
1ceb81
+	dirstack[0] = strdup("");
1ceb81
+	
1ceb81
+	/* Index array. */
1ceb81
+	index_size = 64;
1ceb81
+	db_index = malloc(index_size * sizeof *db_index);
1ceb81
+	index_next = 0;
1ceb81
+
1ceb81
+	do {
1ceb81
+		struct dirent **ents;
1ceb81
+		char name[PATH_MAX], *top;
1ceb81
+		int count;
1ceb81
+
1ceb81
+		/* Pop the top stack entry, and iterate through its contents. */
1ceb81
+		top = dirstack[--dirstack_top];
1ceb81
+		snprintf(name, sizeof name, ZONEINFO_PREFIX "/%s", top);
1ceb81
+
1ceb81
+		count = php_scandir(name, &ents, index_filter, php_alphasort);
1ceb81
+
1ceb81
+		while (count > 0) {
1ceb81
+			struct stat st;
1ceb81
+			const char *leaf = ents[count - 1]->d_name;
1ceb81
+
1ceb81
+			snprintf(name, sizeof name, ZONEINFO_PREFIX "/%s/%s", 
1ceb81
+				 top, leaf);
1ceb81
+			
1ceb81
+			if (strlen(name) && stat(name, &st) == 0) {
1ceb81
+				/* Name, relative to the zoneinfo prefix. */
1ceb81
+				const char *root = top;
1ceb81
+
1ceb81
+				if (root[0] == '/') root++;
1ceb81
+
1ceb81
+				snprintf(name, sizeof name, "%s%s%s", root, 
1ceb81
+					 *root ? "/": "", leaf);
1ceb81
+
1ceb81
+				if (S_ISDIR(st.st_mode)) {
1ceb81
+					if (dirstack_top == dirstack_size) {
1ceb81
+						dirstack_size *= 2;
1ceb81
+						dirstack = realloc(dirstack, 
1ceb81
+								   dirstack_size * sizeof *dirstack);
1ceb81
+					}
1ceb81
+					dirstack[dirstack_top++] = strdup(name);
1ceb81
+				}
1ceb81
+				else {
1ceb81
+					if (index_next == index_size) {
1ceb81
+						index_size *= 2;
1ceb81
+						db_index = realloc(db_index,
1ceb81
+								   index_size * sizeof *db_index);
1ceb81
+					}
1ceb81
+
1ceb81
+					db_index[index_next++].id = strdup(name);
1ceb81
+				}
1ceb81
+			}
1ceb81
+
1ceb81
+			free(ents[--count]);
1ceb81
+		}
1ceb81
+		
1ceb81
+		if (count != -1) free(ents);
1ceb81
+		free(top);
1ceb81
+	} while (dirstack_top);
1ceb81
+
1ceb81
+        qsort(db_index, index_next, sizeof *db_index, sysdbcmp);
1ceb81
+
1ceb81
+	db->index = db_index;
1ceb81
+	db->index_size = index_next;
1ceb81
+
1ceb81
+	free(dirstack);
1ceb81
+}
1ceb81
+
1ceb81
+#define FAKE_HEADER "1234\0??\1??"
1ceb81
+#define FAKE_UTC_POS (7 - 4)
1ceb81
+
1ceb81
+/* Create a fake data segment for database 'sysdb'. */
1ceb81
+static void fake_data_segment(timelib_tzdb *sysdb,
1ceb81
+                              struct location_info **info)
1ceb81
+{
1ceb81
+        size_t n;
1ceb81
+        char *data, *p;
1ceb81
+        
1ceb81
+        data = malloc(3 * sysdb->index_size + 7);
1ceb81
+
1ceb81
+        p = mempcpy(data, FAKE_HEADER, sizeof(FAKE_HEADER) - 1);
1ceb81
+
1ceb81
+        for (n = 0; n < sysdb->index_size; n++) {
1ceb81
+                const struct location_info *li;
1ceb81
+                timelib_tzdb_index_entry *ent;
1ceb81
+
1ceb81
+                ent = (timelib_tzdb_index_entry *)&sysdb->index[n];
1ceb81
+
1ceb81
+                /* Lookup the timezone name in the hash table. */
1ceb81
+                if (strcmp(ent->id, "UTC") == 0) {
1ceb81
+                        ent->pos = FAKE_UTC_POS;
1ceb81
+                        continue;
1ceb81
+                }
1ceb81
+
1ceb81
+                li = find_zone_info(info, ent->id);
1ceb81
+                if (li) {
1ceb81
+                        /* If found, append the BC byte and the
1ceb81
+                         * country code; set the position for this
1ceb81
+                         * section of timezone data.  */
1ceb81
+                        ent->pos = (p - data) - 4;
1ceb81
+                        *p++ = '\1';
1ceb81
+                        *p++ = li->code[0];
1ceb81
+                        *p++ = li->code[1];
1ceb81
+                }
1ceb81
+                else {
1ceb81
+                        /* If not found, the timezone data can
1ceb81
+                         * point at the header. */
1ceb81
+                        ent->pos = 0;
1ceb81
+                }
1ceb81
+        }
1ceb81
+        
1ceb81
+        sysdb->data = (unsigned char *)data;
1ceb81
+}
1ceb81
+
1ceb81
+/* Returns true if the passed-in stat structure describes a
1ceb81
+ * probably-valid timezone file. */
1ceb81
+static int is_valid_tzfile(const struct stat *st, int fd)
1ceb81
+{
1ceb81
+	if (fd) {
1ceb81
+		char buf[20];
1ceb81
+		if (read(fd, buf, 20)!=20) {
1ceb81
+			return 0;
1ceb81
+		}
1ceb81
+		lseek(fd, SEEK_SET, 0);
1ceb81
+		if (memcmp(buf, "TZif", 4)) {
1ceb81
+			return 0;
1ceb81
+		}
1ceb81
+	}
1ceb81
+	return S_ISREG(st->st_mode) && st->st_size > 20;
1ceb81
+}
1ceb81
+
1ceb81
+/* To allow timezone names to be used case-insensitively, find the
1ceb81
+ * canonical name for this timezone, if possible. */
1ceb81
+static const char *canonical_tzname(const char *timezone)
1ceb81
+{
1ceb81
+    if (timezonedb_system) {
1ceb81
+        timelib_tzdb_index_entry *ent, lookup;
1ceb81
+
1ceb81
+        lookup.id = (char *)timezone;
1ceb81
+
1ceb81
+        ent = bsearch(&lookup, timezonedb_system->index,
1ceb81
+                      timezonedb_system->index_size, sizeof lookup,
1ceb81
+                      sysdbcmp);
1ceb81
+        if (ent) {
1ceb81
+            return ent->id;
1ceb81
+        }
1ceb81
+    }
1ceb81
+
1ceb81
+    return timezone;
1ceb81
+}
1ceb81
+
1ceb81
+/* Return the mmap()ed tzfile if found, else NULL.  On success, the
1ceb81
+ * length of the mapped data is placed in *length. */
1ceb81
+static char *map_tzfile(const char *timezone, size_t *length)
1ceb81
+{
1ceb81
+	char fname[PATH_MAX];
1ceb81
+	struct stat st;
1ceb81
+	char *p;
1ceb81
+	int fd;
1ceb81
+	
1ceb81
+	if (timezone[0] == '\0' || strstr(timezone, "..") != NULL) {
1ceb81
+		return NULL;
1ceb81
+	}
1ceb81
+
1ceb81
+	snprintf(fname, sizeof fname, ZONEINFO_PREFIX "/%s", canonical_tzname(timezone));
1ceb81
+
1ceb81
+	fd = open(fname, O_RDONLY);
1ceb81
+	if (fd == -1) {
1ceb81
+		return NULL;
1ceb81
+	} else if (fstat(fd, &st) != 0 || !is_valid_tzfile(&st, fd)) {
1ceb81
+		close(fd);
1ceb81
+		return NULL;
1ceb81
+	}
1ceb81
+
1ceb81
+	*length = st.st_size;
1ceb81
+	p = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
1ceb81
+	close(fd);
1ceb81
+	
1ceb81
+	return p != MAP_FAILED ? p : NULL;
1ceb81
+}
1ceb81
+
1ceb81
+#endif
1ceb81
+
1ceb81
+static int inmem_seek_to_tz_position(const unsigned char **tzf, const char *timezone, const timelib_tzdb *tzdb)
1ceb81
 {
1ceb81
 	int left = 0, right = tzdb->index_size - 1;
1ceb81
 
456590
@@ -461,9 +939,49 @@ static int seek_to_tz_position(const unsigned char **tzf, const char *timezone,
1ceb81
 	return 0;
1ceb81
 }
1ceb81
 
1ceb81
+static int seek_to_tz_position(const unsigned char **tzf, const char *timezone,
1ceb81
+			       char **map, size_t *maplen,
1ceb81
+			       const timelib_tzdb *tzdb)
1ceb81
+{
1ceb81
+#ifdef HAVE_SYSTEM_TZDATA
1ceb81
+	if (tzdb == timezonedb_system) {
1ceb81
+		char *orig;
1ceb81
+
1ceb81
+		orig = map_tzfile(timezone, maplen);
1ceb81
+		if (orig == NULL) {
1ceb81
+			return 0;
1ceb81
+		}
1ceb81
+
1ceb81
+		(*tzf) = (unsigned char *)orig;
1ceb81
+		*map = orig;
1ceb81
+        return 1;
1ceb81
+	}
1ceb81
+	else
1ceb81
+#endif
1ceb81
+	{
1ceb81
+		return inmem_seek_to_tz_position(tzf, timezone, tzdb);
1ceb81
+	}
1ceb81
+}
1ceb81
+
1ceb81
 const timelib_tzdb *timelib_builtin_db(void)
1ceb81
 {
1ceb81
+#ifdef HAVE_SYSTEM_TZDATA
1ceb81
+	if (timezonedb_system == NULL) {
1ceb81
+		timelib_tzdb *tmp = malloc(sizeof *tmp);
1ceb81
+
1ceb81
+		tmp->version = "0.system";
1ceb81
+		tmp->data = NULL;
1ceb81
+		create_zone_index(tmp);
456590
+		retrieve_zone_version(tmp);
1ceb81
+		system_location_table = create_location_table();
1ceb81
+		fake_data_segment(tmp, system_location_table);
1ceb81
+		timezonedb_system = tmp;
1ceb81
+	}
1ceb81
+
1ceb81
+	return timezonedb_system;
1ceb81
+#else
1ceb81
 	return &timezonedb_builtin;
1ceb81
+#endif
1ceb81
 }
1ceb81
 
1ceb81
 const timelib_tzdb_index_entry *timelib_timezone_identifiers_list(const timelib_tzdb *tzdb, int *count)
456590
@@ -475,7 +993,30 @@ const timelib_tzdb_index_entry *timelib_timezone_identifiers_list(const timelib_
1ceb81
 int timelib_timezone_id_is_valid(const char *timezone, const timelib_tzdb *tzdb)
1ceb81
 {
1ceb81
 	const unsigned char *tzf;
1ceb81
-	return (seek_to_tz_position(&tzf, timezone, tzdb));
1ceb81
+
1ceb81
+#ifdef HAVE_SYSTEM_TZDATA
1ceb81
+	if (tzdb == timezonedb_system) {
1ceb81
+		char fname[PATH_MAX];
1ceb81
+		struct stat st;
1ceb81
+
1ceb81
+		if (timezone[0] == '\0' || strstr(timezone, "..") != NULL) {
1ceb81
+			return 0;
1ceb81
+		}
1ceb81
+
1ceb81
+		if (system_location_table) {
1ceb81
+			if (find_zone_info(system_location_table, timezone) != NULL) {
1ceb81
+				/* found in cache */
1ceb81
+				return 1;
1ceb81
+			}
1ceb81
+		}
1ceb81
+
1ceb81
+		snprintf(fname, sizeof fname, ZONEINFO_PREFIX "/%s", canonical_tzname(timezone));
1ceb81
+
1ceb81
+		return stat(fname, &st) == 0 && is_valid_tzfile(&st, 0);
1ceb81
+	}
1ceb81
+#endif
1ceb81
+
1ceb81
+	return (inmem_seek_to_tz_position(&tzf, timezone, tzdb));
1ceb81
 }
1ceb81
 
1ceb81
 static int skip_64bit_preamble(const unsigned char **tzf, timelib_tzinfo *tz)
456590
@@ -517,6 +1058,8 @@ static timelib_tzinfo* timelib_tzinfo_ctor(const char *name)
1ceb81
 timelib_tzinfo *timelib_parse_tzfile(const char *timezone, const timelib_tzdb *tzdb, int *error_code)
1ceb81
 {
1ceb81
 	const unsigned char *tzf;
1ceb81
+	char *memmap = NULL;
1ceb81
+	size_t maplen;
1ceb81
 	timelib_tzinfo *tmp;
1ceb81
 	int version;
1ceb81
 	int transitions_result, types_result;
456590
@@ -524,7 +1067,7 @@ timelib_tzinfo *timelib_parse_tzfile(const char *timezone, const timelib_tzdb *t
1ceb81
 
1ceb81
 	*error_code = TIMELIB_ERROR_NO_ERROR;
1ceb81
 
1ceb81
-	if (seek_to_tz_position(&tzf, timezone, tzdb)) {
1ceb81
+	if (seek_to_tz_position(&tzf, timezone, &memmap, &maplen, tzdb)) {
1ceb81
 		tmp = timelib_tzinfo_ctor(timezone);
1ceb81
 
1ceb81
 		version = read_preamble(&tzf, tmp, &type);
456590
@@ -563,11 +1106,36 @@ timelib_tzinfo *timelib_parse_tzfile(const char *timezone, const timelib_tzdb *t
1ceb81
 		}
1ceb81
 		skip_posix_string(&tzf, tmp);
1ceb81
 
1ceb81
+#ifdef HAVE_SYSTEM_TZDATA
1ceb81
+		if (memmap) {
1ceb81
+			const struct location_info *li;
1ceb81
+
1ceb81
+			/* TZif-style - grok the location info from the system database,
1ceb81
+			 * if possible. */
1ceb81
+
1ceb81
+			if ((li = find_zone_info(system_location_table, timezone)) != NULL) {
1ceb81
+				tmp->location.comments = timelib_strdup(li->comment);
1ceb81
+				strncpy(tmp->location.country_code, li->code, 2);
1ceb81
+				tmp->location.longitude = li->longitude;
1ceb81
+				tmp->location.latitude = li->latitude;
1ceb81
+				tmp->bc = 1;
1ceb81
+			}
1ceb81
+			else {
1ceb81
+				set_default_location_and_comments(&tzf, tmp);
1ceb81
+			}
1ceb81
+
1ceb81
+			/* Now done with the mmap segment - discard it. */
1ceb81
+			munmap(memmap, maplen);
1ceb81
+		} else {
1ceb81
+#endif
1ceb81
 		if (type == TIMELIB_TZINFO_PHP) {
1ceb81
 			read_location(&tzf, tmp);
1ceb81
 		} else {
1ceb81
 			set_default_location_and_comments(&tzf, tmp);
1ceb81
 		}
1ceb81
+#ifdef HAVE_SYSTEM_TZDATA
1ceb81
+		}
1ceb81
+#endif
1ceb81
 	} else {
1ceb81
 		*error_code = TIMELIB_ERROR_NO_SUCH_TIMEZONE;
1ceb81
 		tmp = NULL;
456590
diff --git a/ext/date/php_date.c b/ext/date/php_date.c
456590
index 2d5cffb963..389f09f313 100644
456590
--- a/ext/date/php_date.c
456590
+++ b/ext/date/php_date.c
456590
@@ -457,7 +457,11 @@ PHP_MINFO_FUNCTION(date)
456590
 	php_info_print_table_row(2, "date/time support", "enabled");
456590
 	php_info_print_table_row(2, "timelib version", TIMELIB_ASCII_VERSION);
456590
 	php_info_print_table_row(2, "\"Olson\" Timezone Database Version", tzdb->version);
456590
+#ifdef HAVE_SYSTEM_TZDATA
456590
+	php_info_print_table_row(2, "Timezone Database", "system");
456590
+#else
456590
 	php_info_print_table_row(2, "Timezone Database", php_date_global_timezone_db_enabled ? "external" : "internal");
456590
+#endif
456590
 	php_info_print_table_row(2, "Default timezone", guess_timezone(tzdb));
456590
 	php_info_print_table_end();
456590