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