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