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