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