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