/*
  +----------------------------------------------------------------------+
  | phar php single-file executable PHP extension                        |
  | utility functions                                                    |
  +----------------------------------------------------------------------+
  | Copyright © The PHP Group and Contributors.                          |
  +----------------------------------------------------------------------+
  | This source file is subject to the Modified BSD License that is      |
  | bundled with this package in the file LICENSE, and is available      |
  | through the World Wide Web at <https://www.php.net/license/>.        |
  |                                                                      |
  | SPDX-License-Identifier: BSD-3-Clause                                |
  +----------------------------------------------------------------------+
  | Authors: Gregory Beaver <cellog@php.net>                             |
  |          Marcus Boerger <helly@php.net>                              |
  +----------------------------------------------------------------------+
*/

#include "phar_internal.h"
#include "ext/hash/php_hash.h" /* Needed for PHP_HASH_API in ext/hash/php_hash_sha.h */
#include "ext/hash/php_hash_sha.h"
#include "ext/standard/md5.h"

#ifdef PHAR_HAVE_OPENSSL
/* OpenSSL includes */
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/crypto.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/conf.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include <openssl/pkcs12.h>
#else
ZEND_ATTRIBUTE_NONNULL static bool phar_call_openssl_verify(php_stream *fp, zend_off_t end, zend_string *public_key, const char *signature, size_t signature_len, uint32_t sig_type);
static zend_result phar_call_openssl_sign(php_stream *fp, zend_off_t end, const char *key, size_t key_len, char **signature, size_t *signature_len, uint32_t sig_type);
#endif

/* for links to relative location, prepend cwd of the entry */
static zend_string *phar_get_link_location(phar_entry_info *entry) /* {{{ */
{
	ZEND_ASSERT(entry->symlink);

	if (ZSTR_VAL(entry->symlink)[0] == '/') {
		return zend_string_init(ZSTR_VAL(entry->symlink) + 1, ZSTR_LEN(entry->symlink) - 1, false);
	}
	const char *p = strrchr(ZSTR_VAL(entry->filename), '/');
	if (p) {
		/* Important: don't modify the original `p` data because it is a shared string. */
		zend_string *new_name = zend_string_init(ZSTR_VAL(entry->filename), p - ZSTR_VAL(entry->filename), false);
		zend_string *location = zend_string_concat3(
			ZSTR_VAL(new_name), ZSTR_LEN(new_name),
			ZEND_STRL("/"),
			ZSTR_VAL(entry->symlink), ZSTR_LEN(entry->symlink)
		);
		zend_string_release(entry->filename);
		entry->filename = new_name;
		return location;
	}
	return zend_string_copy(entry->symlink);
}
/* }}} */

phar_entry_info *phar_get_link_source(phar_entry_info *entry) /* {{{ */
{
	phar_entry_info *link_entry;
	uint32_t depth = 0, max_depth;

	if (!entry->symlink) {
		return entry;
	}

	max_depth = zend_hash_num_elements(&(entry->phar->manifest));

	while (entry->symlink) {
		if (UNEXPECTED(++depth > max_depth)) {
			return NULL;
		}
		zend_string *link = phar_get_link_location(entry);

		if (NULL != (link_entry = zend_hash_find_ptr(&(entry->phar->manifest), entry->symlink)) ||
			NULL != (link_entry = zend_hash_find_ptr(&(entry->phar->manifest), link))) {
			zend_string_release(link);
			entry = link_entry;
		} else {
			zend_string_release(link);
			return NULL;
		}
	}
	return entry;
}
/* }}} */

static php_stream *phar_get_entrypufp(const phar_entry_info *entry)
{
	if (!entry->is_persistent) {
		return entry->phar->ufp;
	}
	return PHAR_G(cached_fp)[entry->phar->phar_pos].ufp;
}

/* retrieve a phar_entry_info's current file pointer for reading contents */
php_stream *phar_get_efp(phar_entry_info *entry, bool follow_links) /* {{{ */
{
	if (follow_links && entry->symlink) {
		phar_entry_info *link_entry = phar_get_link_source(entry);

		if (link_entry && link_entry != entry) {
			return phar_get_efp(link_entry, true);
		}
	}

	if (phar_get_fp_type(entry) == PHAR_FP) {
		php_stream *stream = phar_get_entrypfp(entry);
		if (!stream) {
			/* re-open just in time for cases where our refcount reached 0 on the phar archive */
			stream = phar_open_archive_fp(entry->phar);
		}
		return stream;
	} else if (phar_get_fp_type(entry) == PHAR_UFP) {
		return phar_get_entrypufp(entry);
	} else if (entry->fp_type == PHAR_MOD) {
		return entry->fp;
	} else {
		/* temporary manifest entry */
		if (!entry->fp) {
			entry->fp = php_stream_open_wrapper(entry->tmp, "rb", STREAM_MUST_SEEK|0, NULL);
		}
		return entry->fp;
	}
}
/* }}} */

static zend_off_t phar_get_fp_offset(const phar_entry_info *entry)
{
	if (!entry->is_persistent) {
		return entry->offset;
	}
	if (PHAR_G(cached_fp)[entry->phar->phar_pos].manifest[entry->manifest_pos].fp_type == PHAR_FP) {
		if (!PHAR_G(cached_fp)[entry->phar->phar_pos].manifest[entry->manifest_pos].offset) {
			PHAR_G(cached_fp)[entry->phar->phar_pos].manifest[entry->manifest_pos].offset = entry->offset;
		}
	}
	return PHAR_G(cached_fp)[entry->phar->phar_pos].manifest[entry->manifest_pos].offset;
}

int phar_seek_efp(phar_entry_info *entry, zend_off_t offset, int whence, zend_off_t position, bool follow_links) /* {{{ */
{
	php_stream *fp = phar_get_efp(entry, follow_links);
	zend_off_t temp, eoffset;

	if (!fp) {
		return -1;
	}

	if (follow_links) {
		phar_entry_info *t;
		t = phar_get_link_source(entry);
		if (t) {
			entry = t;
		}
	}

	if (entry->is_dir) {
		return 0;
	}

	eoffset = phar_get_fp_offset(entry);

	switch (whence) {
		case SEEK_END:
			temp = eoffset + entry->uncompressed_filesize + offset;
			break;
		case SEEK_CUR:
			temp = eoffset + position + offset;
			break;
		case SEEK_SET:
			temp = eoffset + offset;
			break;
		default:
			temp = 0;
	}

	if (temp > eoffset + (zend_off_t) entry->uncompressed_filesize) {
		return -1;
	}

	if (temp < eoffset) {
		return -1;
	}

	return php_stream_seek(fp, temp, SEEK_SET);
}
/* }}} */

/* mount an absolute path or uri to a path internal to the phar archive */
zend_result phar_mount_entry(phar_archive_data *phar, const char *filename, size_t filename_len, char *path, size_t path_len) /* {{{ */
{
	phar_entry_info entry = {0};
	php_stream_statbuf ssb;
	bool is_phar;
	const char *err;

	if (phar_path_check(&path, &path_len, &err) > pcr_is_ok) {
		return FAILURE;
	}

	if (path_len >= sizeof(".phar")-1 && !memcmp(path, ".phar", sizeof(".phar")-1)) {
		/* no creating magic phar files by mounting them */
		return FAILURE;
	}

	is_phar = (filename_len > 7 && !memcmp(filename, "phar://", 7));

	entry.phar = phar;

	if (is_phar) {
		entry.tmp = estrndup(filename, filename_len);
	} else {
		entry.tmp = expand_filepath(filename, NULL);
		if (!entry.tmp) {
			entry.tmp = estrndup(filename, filename_len);
		}
	}
	filename = entry.tmp;

	/* only check openbasedir for files, not for phar streams */
	if (!is_phar && php_check_open_basedir(filename)) {
		efree(entry.tmp);
		return FAILURE;
	}

	entry.is_mounted = true;
	entry.is_crc_checked = true;
	entry.fp_type = PHAR_TMP;

	if (SUCCESS != php_stream_stat_path(filename, &ssb)) {
		efree(entry.tmp);
		return FAILURE;
	}

	entry.filename = zend_string_init(path, path_len, false);
#ifdef PHP_WIN32
	phar_unixify_path_separators(ZSTR_VAL(entry.filename), path_len);
#endif

	if (ssb.sb.st_mode & S_IFDIR) {
		entry.is_dir = true;
		if (NULL == zend_hash_add_ptr(&phar->mounted_dirs, entry.filename, entry.filename)) {
			/* directory already mounted */
			efree(entry.tmp);
			zend_string_efree(entry.filename);
			return FAILURE;
		}
	} else {
		entry.is_dir = false;
		entry.uncompressed_filesize = entry.compressed_filesize = ssb.sb.st_size;
	}

	entry.flags = ssb.sb.st_mode;

	if (NULL != zend_hash_add_mem(&phar->manifest, entry.filename, &entry, sizeof(phar_entry_info))) {
		return SUCCESS;
	}

	efree(entry.tmp);
	zend_string_release_ex(entry.filename, false);
	return FAILURE;
}
/* }}} */

zend_string *phar_find_in_include_path(const zend_string *filename) /* {{{ */
{
	zend_string *ret;
	char *path;
	zend_string *arch;
	phar_archive_data *phar;

	if (!zend_is_executing() || !PHAR_G(cwd)) {
		return NULL;
	}

	zend_string *fname = zend_get_executed_filename_ex();
	if (!fname) {
		return NULL;
	}

	bool is_file_a_phar_wrapper = zend_string_starts_with_literal_ci(fname, "phar://");
	size_t length_phar_protocol = strlen("phar://");

	if (
		PHAR_G(last_phar)
		&& is_file_a_phar_wrapper
		&& ZSTR_LEN(fname) - length_phar_protocol >= ZSTR_LEN(PHAR_G(last_phar_name))
		&& !memcmp(ZSTR_VAL(fname) + length_phar_protocol, ZSTR_VAL(PHAR_G(last_phar_name)), ZSTR_LEN(PHAR_G(last_phar_name)))
	) {
		arch = zend_string_init(ZSTR_VAL(PHAR_G(last_phar_name)), ZSTR_LEN(PHAR_G(last_phar_name)), false);
		phar = PHAR_G(last_phar);
		goto splitted;
	}

	if (!is_file_a_phar_wrapper) {
		return NULL;
	}
	arch = phar_split_fname(ZSTR_VAL(fname), ZSTR_LEN(fname), NULL, 1, 0);
	if (!arch) {
		return NULL;
	}

	if (*ZSTR_VAL(filename) == '.') {
		phar = phar_get_archive(ZSTR_VAL(arch), ZSTR_LEN(arch), NULL, 0, NULL);
		if (!phar) {
			zend_string_release_ex(arch, false);
			return NULL;
		}
splitted:;
		zend_string *test = phar_fix_filepath(ZSTR_VAL(filename), ZSTR_LEN(filename), true);
		if (ZSTR_VAL(test)[0] == '/') {
			if (zend_hash_str_exists(&(phar->manifest), ZSTR_VAL(test) + 1, ZSTR_LEN(test) - 1)) {
				ret = zend_string_concat3(
					"phar://", strlen("phar://"),
					ZSTR_VAL(arch), ZSTR_LEN(arch),
					ZSTR_VAL(test), ZSTR_LEN(test)
				);
				zend_string_release_ex(test, false);
				zend_string_release_ex(arch, false);
				return ret;
			}
		} else {
			if (zend_hash_exists(&(phar->manifest), test)) {
				ret = strpprintf(0, "phar://%s/%s", ZSTR_VAL(arch), ZSTR_VAL(test));
				zend_string_release_ex(test, false);
				zend_string_release_ex(arch, false);
				return ret;
			}
		}
		zend_string_release_ex(test, false);
	}

	spprintf(&path, MAXPATHLEN + 1 + strlen(PG(include_path)), "phar://%s/%s%c%s", ZSTR_VAL(arch), PHAR_G(cwd), DEFAULT_DIR_SEPARATOR, PG(include_path));
	zend_string_release_ex(arch, false);
	ret = php_resolve_path(ZSTR_VAL(filename), ZSTR_LEN(filename), path);
	efree(path);

	return ret;
}
/* }}} */

static ZEND_ATTRIBUTE_NONNULL zend_result phar_create_writeable_entry(phar_archive_data *phar, phar_entry_info *entry, char **error) /* {{{ */
{
	*error = NULL;

	if (entry->fp_type == PHAR_MOD) {
		/* already newly created, truncate */
		php_stream_truncate_set_size(entry->fp, 0);

		entry->old_flags = entry->flags;
		entry->is_modified = 1;
		phar->is_modified = 1;
		/* reset file size */
		entry->uncompressed_filesize = 0;
		entry->compressed_filesize = 0;
		entry->crc32 = 0;
		entry->flags = PHAR_ENT_PERM_DEF_FILE;
		entry->fp_type = PHAR_MOD;
		entry->offset = 0;
		return SUCCESS;
	}

	/* open a new temp file for writing */
	if (entry->symlink) {
		zend_string_release(entry->symlink);
		entry->symlink = NULL;
		entry->tar_type = (entry->is_tar ? TAR_FILE : '\0');
	}

	entry->fp = php_stream_fopen_tmpfile();

	if (!entry->fp) {
		*error = estrdup("phar error: unable to create temporary file");
		return FAILURE;
	}

	entry->old_flags = entry->flags;
	entry->is_modified = 1;
	phar->is_modified = 1;
	/* reset file size */
	entry->uncompressed_filesize = 0;
	entry->compressed_filesize = 0;
	entry->crc32 = 0;
	entry->flags = PHAR_ENT_PERM_DEF_FILE;
	entry->fp_type = PHAR_MOD;
	entry->offset = 0;
	return SUCCESS;
}
/* }}} */

ZEND_ATTRIBUTE_NONNULL static zend_result phar_separate_entry_fp(phar_entry_info *entry, char **error) /* {{{ */
{
	php_stream *fp;
	phar_entry_info *link;

	if (FAILURE == phar_open_entry_fp(entry, error, true)) {
		return FAILURE;
	}

	if (entry->fp_type == PHAR_MOD) {
		return SUCCESS;
	}

	fp = php_stream_fopen_tmpfile();
	if (fp == NULL) {
		*error = estrdup("phar error: unable to create temporary file");
		return FAILURE;
	}
	phar_seek_efp(entry, 0, SEEK_SET, 0, true);
	link = phar_get_link_source(entry);

	if (!link) {
		link = entry;
	}

	if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(link, false), fp, link->uncompressed_filesize, NULL)) {
		spprintf(error, 4096, "phar error: cannot separate entry file \"%s\" contents in phar archive \"%s\" for write access", ZSTR_VAL(entry->filename), ZSTR_VAL(entry->phar->fname));
		return FAILURE;
	}

	if (entry->symlink) {
		zend_string_release(entry->symlink);
		entry->symlink = NULL;
		entry->tar_type = (entry->is_tar ? TAR_FILE : '\0');
	}

	entry->offset = 0;
	entry->fp = fp;
	entry->fp_type = PHAR_MOD;
	entry->is_modified = 1;
	return SUCCESS;
}
/* }}} */

/**
 * Retrieve a copy of the file information on a single file within a phar, or null.
 * This also transfers the open file pointer, if any, to the entry.
 *
 * If the file does not already exist, this will fail.  Pre-existing files can be
 * appended, truncated, or read.  For read, if the entry is marked unmodified, it is
 * assumed that the file pointer, if present, is opened for reading
 */
ZEND_ATTRIBUTE_NONNULL zend_result phar_get_entry_data(phar_entry_data **ret, const zend_string *fname, char *path, size_t path_len, const char *mode, char allow_dir, char **error, bool security) /* {{{ */
{
	phar_entry_info *entry;
	bool for_write  = mode[0] != 'r' || mode[1] == '+';
	bool for_append = mode[0] == 'a';
	bool for_create = mode[0] != 'r';
	bool for_trunc  = mode[0] == 'w';

	*ret = NULL;
	*error = NULL;

	phar_archive_data *phar = phar_get_archive(ZSTR_VAL(fname), ZSTR_LEN(fname), NULL, 0, error);
	if (!phar) {
		return FAILURE;
	}

	if (for_write && PHAR_G(readonly) && !phar->is_data) {
		spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be opened for writing, disabled by ini setting", path, ZSTR_VAL(fname));
		return FAILURE;
	}

	if (!path_len) {
		spprintf(error, 4096, "phar error: file \"\" in phar \"%s\" must not be empty", ZSTR_VAL(fname));
		return FAILURE;
	}
really_get_entry:
	if (allow_dir) {
		entry = phar_get_entry_info_dir(phar, path, path_len, allow_dir, for_create && !PHAR_G(readonly) && !phar->is_data ? NULL : error, security);
		if (!entry) {
			if (for_create && (!PHAR_G(readonly) || phar->is_data)) {
				return SUCCESS;
			}
			return FAILURE;
		}
	} else {
		entry = phar_get_entry_info(phar, path, path_len, for_create && !PHAR_G(readonly) && !phar->is_data ? NULL : error, security);
		if (!entry) {
			if (for_create && (!PHAR_G(readonly) || phar->is_data)) {
				return SUCCESS;
			}
			return FAILURE;
		}
	}

	if (for_write && phar->is_persistent) {
		if (FAILURE == phar_copy_on_write(&phar)) {
			spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be opened for writing, could not make cached phar writeable", path, ZSTR_VAL(fname));
			return FAILURE;
		} else {
			goto really_get_entry;
		}
	}

	if (entry->is_modified && !for_write) {
		spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be opened for reading, writable file pointers are open", path, ZSTR_VAL(fname));
		return FAILURE;
	}

	if (entry->fp_refcount && for_write) {
		spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be opened for writing, readable file pointers are open", path, ZSTR_VAL(fname));
		return FAILURE;
	}

	if (entry->is_deleted) {
		if (!for_create) {
			return FAILURE;
		}
		entry->is_deleted = 0;
	}

	if (entry->is_dir) {
		*ret = (phar_entry_data *) emalloc(sizeof(phar_entry_data));
		(*ret)->position = 0;
		(*ret)->fp = NULL;
		(*ret)->phar = phar;
		(*ret)->internal_file = entry;

		if (!phar->is_persistent) {
			++(entry->phar->refcount);
			++(entry->fp_refcount);
		}

		return SUCCESS;
	}

	if (entry->fp_type == PHAR_MOD) {
		if (for_trunc) {
			if (FAILURE == phar_create_writeable_entry(phar, entry, error)) {
				return FAILURE;
			}
		} else if (for_append) {
			phar_seek_efp(entry, 0, SEEK_END, 0, false);
		}
	} else {
		if (for_write) {
			if (entry->symlink) {
				zend_string_release(entry->symlink);
				entry->symlink = NULL;
				entry->tar_type = (entry->is_tar ? TAR_FILE : '\0');
			}

			if (for_trunc) {
				if (FAILURE == phar_create_writeable_entry(phar, entry, error)) {
					return FAILURE;
				}
			} else {
				if (FAILURE == phar_separate_entry_fp(entry, error)) {
					return FAILURE;
				}
			}
		} else {
			if (FAILURE == phar_open_entry_fp(entry, error, true)) {
				return FAILURE;
			}
		}
	}

	*ret = (phar_entry_data *) emalloc(sizeof(phar_entry_data));
	(*ret)->position = 0;
	(*ret)->phar = phar;
	(*ret)->internal_file = entry;
	(*ret)->fp = phar_get_efp(entry, true);
	if (entry->symlink) {
		phar_entry_info *link = phar_get_link_source(entry);
		if(!link) {
			efree(*ret);
			return FAILURE;
		}
		(*ret)->zero = phar_get_fp_offset(link);
	} else {
		(*ret)->zero = phar_get_fp_offset(entry);
	}

	if (!phar->is_persistent) {
		++(entry->fp_refcount);
		++(entry->phar->refcount);
	}

	return SUCCESS;
}
/* }}} */

/**
 * Create a new dummy file slot within a writeable phar for a newly created file
 */
ZEND_ATTRIBUTE_NONNULL phar_entry_data *phar_get_or_create_entry_data(zend_string *fname, char *path, size_t path_len, const char *mode, char allow_dir, char **error, bool security, uint32_t timestamp) /* {{{ */
{
	phar_entry_info etemp;
	phar_entry_data *ret;
	const char *pcr_error;
	char is_dir;

#ifdef PHP_WIN32
	phar_unixify_path_separators(path, path_len);
#endif

	is_dir = (path_len && path[path_len - 1] == '/') ? 1 : 0;

	phar_archive_data *phar = phar_get_archive(ZSTR_VAL(fname), ZSTR_LEN(fname), NULL, 0, error);
	if (!phar) {
		return NULL;
	}

	if (FAILURE == phar_get_entry_data(&ret, fname, path, path_len, mode, allow_dir, error, security)) {
		return NULL;
	} else if (ret) {
		return ret;
	}

	if (phar_path_check(&path, &path_len, &pcr_error) > pcr_is_ok) {
		spprintf(error, 0, "phar error: invalid path \"%s\" contains %s", path, pcr_error);
		return NULL;
	}

	if (phar->is_persistent && FAILURE == phar_copy_on_write(&phar)) {
		spprintf(error, 4096, "phar error: file \"%s\" in phar \"%s\" cannot be created, could not make cached phar writeable", path, ZSTR_VAL(fname));
		return NULL;
	}

	/* create a new phar data holder */
	ret = (phar_entry_data *) emalloc(sizeof(phar_entry_data));

	/* create an entry, this is a new file */
	memset(&etemp, 0, sizeof(phar_entry_info));
	etemp.fp_type = PHAR_MOD;
	etemp.fp = php_stream_fopen_tmpfile();

	if (!etemp.fp) {
		*error = estrdup("phar error: unable to create temporary file");
		efree(ret);
		return NULL;
	}

	etemp.fp_refcount = 1;

	if (allow_dir == 2) {
		etemp.is_dir = 1;
		etemp.flags = etemp.old_flags = PHAR_ENT_PERM_DEF_DIR;
	} else {
		etemp.flags = etemp.old_flags = PHAR_ENT_PERM_DEF_FILE;
	}
	if (is_dir && path_len) {
		path_len--; /* strip trailing / */
	}

	phar_add_virtual_dirs(phar, path, path_len);
	etemp.is_modified = 1;
	etemp.timestamp = timestamp;
	etemp.is_crc_checked = 1;
	etemp.phar = phar;
	etemp.filename = zend_string_init(path, path_len, false);
	etemp.is_zip = phar->is_zip;

	if (phar->is_tar) {
		etemp.is_tar = phar->is_tar;
		etemp.tar_type = etemp.is_dir ? TAR_DIR : TAR_FILE;
	}

	phar_entry_info *entry = zend_hash_add_mem(&phar->manifest, etemp.filename, &etemp, sizeof(phar_entry_info));
	if (!entry) {
		php_stream_close(etemp.fp);
		spprintf(error, 0, "phar error: unable to add new entry \"%s\" to phar \"%s\"",
			ZSTR_VAL(etemp.filename), ZSTR_VAL(phar->fname));
		efree(ret);
		zend_string_efree(etemp.filename);
		return NULL;
	}

	++(phar->refcount);
	ret->phar = phar;
	ret->fp = entry->fp;
	ret->position = ret->zero = 0;
	ret->internal_file = entry;

	return ret;
}
/* }}} */

static inline void phar_set_pharfp(phar_archive_data *phar, php_stream *fp)
{
	if (!phar->is_persistent) {
		phar->fp =  fp;
		return;
	}

	PHAR_G(cached_fp)[phar->phar_pos].fp = fp;
}

/* Initialize a phar_archive_data's read-only fp for existing phar data.
 * The stream is owned by the `phar` object and must not be closed manually. */
php_stream *phar_open_archive_fp(phar_archive_data *phar) /* {{{ */
{
	php_stream *stream = phar_get_pharfp(phar);
	if (stream) {
		return stream;
	}

	if (php_check_open_basedir(ZSTR_VAL(phar->fname))) {
		return NULL;
	}

	stream = php_stream_open_wrapper(ZSTR_VAL(phar->fname), "rb", IGNORE_URL|STREAM_MUST_SEEK, NULL);
	phar_set_pharfp(phar, stream);

	return stream;
}
/* }}} */

/* copy file data from an existing to a new phar_entry_info that is not in the manifest */
ZEND_ATTRIBUTE_NONNULL zend_result phar_copy_entry_fp(phar_entry_info *source, phar_entry_info *dest, char **error) /* {{{ */
{
	phar_entry_info *link;

	if (FAILURE == phar_open_entry_fp(source, error, true)) {
		return FAILURE;
	}

	if (dest->symlink) {
		zend_string_release(dest->symlink);
		dest->symlink = NULL;
		dest->tar_type = (dest->is_tar ? TAR_FILE : '\0');
	}

	dest->fp_type = PHAR_MOD;
	dest->offset = 0;
	dest->is_modified = 1;
	dest->fp = php_stream_fopen_tmpfile();
	if (dest->fp == NULL) {
		*error = estrdup("phar error: unable to create temporary file");
		return EOF;
	}
	phar_seek_efp(source, 0, SEEK_SET, 0, true);
	link = phar_get_link_source(source);

	if (!link) {
		link = source;
	}

	if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(link, false), dest->fp, link->uncompressed_filesize, NULL)) {
		php_stream_close(dest->fp);
		dest->fp_type = PHAR_FP;
		spprintf(error, 4096, "phar error: unable to copy contents of file \"%s\" to \"%s\" in phar archive \"%s\"",
			ZSTR_VAL(source->filename), ZSTR_VAL(dest->filename), ZSTR_VAL(source->phar->fname));
		return FAILURE;
	}

	return SUCCESS;
}
/* }}} */

static void phar_set_entrypufp(const phar_entry_info *entry, php_stream *fp)
{
	if (!entry->phar->is_persistent) {
		entry->phar->ufp =  fp;
		return;
	}

	PHAR_G(cached_fp)[entry->phar->phar_pos].ufp = fp;
}

static void phar_set_fp_type(phar_entry_info *entry, enum phar_fp_type type, zend_off_t offset)
{
	phar_entry_fp_info *data;

	if (!entry->is_persistent) {
		entry->fp_type = type;
		entry->offset = offset;
		return;
	}
	data = &(PHAR_G(cached_fp)[entry->phar->phar_pos].manifest[entry->manifest_pos]);
	data->fp_type = type;
	data->offset = offset;
}

/* open and decompress a compressed phar entry
 */
ZEND_ATTRIBUTE_NONNULL zend_result phar_open_entry_fp(phar_entry_info *entry, char **error, bool follow_links) /* {{{ */
{
	php_stream_filter *filter;
	phar_archive_data *phar = entry->phar;
	zend_off_t loc;
	php_stream *ufp;
	phar_entry_data dummy;

	if (follow_links && entry->symlink) {
		phar_entry_info *link_entry = phar_get_link_source(entry);
		if (link_entry && link_entry != entry) {
			return phar_open_entry_fp(link_entry, error, true);
		}
	}

	if (entry->is_modified) {
		return SUCCESS;
	}

	if (entry->fp_type == PHAR_TMP) {
		if (!entry->fp) {
			entry->fp = php_stream_open_wrapper(entry->tmp, "rb", STREAM_MUST_SEEK|0, NULL);
		}
		return SUCCESS;
	}

	if (entry->fp_type != PHAR_FP) {
		/* either newly created or already modified */
		return SUCCESS;
	}

	if (!phar_get_pharfp(phar)) {
		if (!phar_open_archive_fp(phar)) {
			spprintf(error, 4096, "phar error: Cannot open phar archive \"%s\" for reading", ZSTR_VAL(phar->fname));
			return FAILURE;
		}
	}

	if ((entry->old_flags && !(entry->old_flags & PHAR_ENT_COMPRESSION_MASK)) || !(entry->flags & PHAR_ENT_COMPRESSION_MASK)) {
		dummy.internal_file = entry;
		dummy.phar = phar;
		dummy.zero = entry->offset;
		dummy.fp = phar_get_pharfp(phar);
		if (FAILURE == phar_postprocess_file(&dummy, entry->crc32, error, 1)) {
			return FAILURE;
		}
		return SUCCESS;
	}

	if (!phar_get_entrypufp(entry)) {
		phar_set_entrypufp(entry, php_stream_fopen_tmpfile());
		if (!phar_get_entrypufp(entry)) {
			spprintf(error, 4096, "phar error: Cannot open temporary file for decompressing phar archive \"%s\" file \"%s\"", ZSTR_VAL(phar->fname), ZSTR_VAL(entry->filename));
			return FAILURE;
		}
	}

	dummy.internal_file = entry;
	dummy.phar = phar;
	dummy.zero = entry->offset;
	dummy.fp = phar_get_pharfp(phar);
	if (FAILURE == phar_postprocess_file(&dummy, entry->crc32, error, 1)) {
		return FAILURE;
	}

	ufp = phar_get_entrypufp(entry);

	const char *filter_name = phar_decompress_filter(entry, false);
	if (filter_name != NULL) {
		filter = php_stream_filter_create(filter_name, NULL, 0);
	} else {
		filter = NULL;
	}

	if (!filter) {
		spprintf(error, 4096, "phar error: unable to read phar \"%s\" (cannot create %s filter while decompressing file \"%s\")", ZSTR_VAL(phar->fname), phar_decompress_filter(entry, true), ZSTR_VAL(entry->filename));
		return FAILURE;
	}

	/* now we can safely use proper decompression */
	/* save the new offset location within ufp */
	php_stream_seek(ufp, 0, SEEK_END);
	loc = php_stream_tell(ufp);
	php_stream_filter_append(&ufp->writefilters, filter);
	php_stream_seek(phar_get_entrypfp(entry), phar_get_fp_offset(entry), SEEK_SET);

	if (entry->uncompressed_filesize) {
		if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_entrypfp(entry), ufp, entry->compressed_filesize, NULL)) {
			spprintf(error, 4096, "phar error: internal corruption of phar \"%s\" (actual filesize mismatch on file \"%s\")", ZSTR_VAL(phar->fname), ZSTR_VAL(entry->filename));
			php_stream_filter_remove(filter, 1);
			return FAILURE;
		}
	}

	php_stream_filter_flush(filter, 1);
	php_stream_flush(ufp);
	php_stream_filter_remove(filter, 1);

	if (php_stream_tell(ufp) - loc != (zend_off_t) entry->uncompressed_filesize) {
		spprintf(error, 4096, "phar error: internal corruption of phar \"%s\" (actual filesize mismatch on file \"%s\")", ZSTR_VAL(phar->fname), ZSTR_VAL(entry->filename));
		return FAILURE;
	}

	entry->old_flags = entry->flags;

	/* this is now the new location of the file contents within this fp */
	phar_set_fp_type(entry, PHAR_UFP, loc);
	dummy.zero = entry->offset;
	dummy.fp = ufp;
	if (FAILURE == phar_postprocess_file(&dummy, entry->crc32, error, 0)) {
		return FAILURE;
	}
	return SUCCESS;
}
/* }}} */

/**
 * helper function to open an internal file's fp just-in-time
 */
ZEND_ATTRIBUTE_NONNULL phar_entry_info * phar_open_jit(const phar_archive_data *phar, phar_entry_info *entry, char **error) /* {{{ */
{
	*error = NULL;
	/* seek to start of internal file and read it */
	if (FAILURE == phar_open_entry_fp(entry, error, true)) {
		return NULL;
	}
	if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, true)) {
		spprintf(error, 4096, "phar error: cannot seek to start of file \"%s\" in phar \"%s\"", ZSTR_VAL(entry->filename), ZSTR_VAL(phar->fname));
		return NULL;
	}
	return entry;
}
/* }}} */

zend_result phar_free_alias(const phar_archive_data *phar) /* {{{ */
{
	if (phar->refcount || phar->is_persistent) {
		return FAILURE;
	}

	/* this archive has no open references, so emit a notice and remove it */
	if (zend_hash_del(&(PHAR_G(phar_fname_map)), phar->fname) != SUCCESS) {
		return FAILURE;
	}

	/* invalidate phar cache */
	PHAR_G(last_phar) = NULL;
	PHAR_G(last_alias) = NULL;
	PHAR_G(last_phar_name) = NULL;

	return SUCCESS;
}
/* }}} */

/**
 * Looks up a phar archive in the filename map, connecting it to the alias
 * (if any) or returns null
 */
phar_archive_data* phar_get_archive(const char *fname, size_t fname_len, const char *alias, size_t alias_len, char **error) /* {{{ */
{
	phar_archive_data *archive;

	phar_request_initialize();

	if (error) {
		*error = NULL;
	}

	if (PHAR_G(last_phar) && zend_string_equals_cstr(PHAR_G(last_phar_name), fname, fname_len)) {
		archive = PHAR_G(last_phar);
		if (alias && alias_len) {

			if (!PHAR_G(last_phar)->is_temporary_alias && (alias_len != PHAR_G(last_phar)->alias_len || memcmp(PHAR_G(last_phar)->alias, alias, alias_len))) {
				if (error) {
					spprintf(error, 0, "alias \"%s\" is already used for archive \"%s\" cannot be overloaded with \"%s\"", alias, ZSTR_VAL(PHAR_G(last_phar)->fname), fname);
				}
				return NULL;
			}

			if (PHAR_G(last_phar)->alias_len && zend_hash_str_exists(&(PHAR_G(phar_alias_map)), PHAR_G(last_phar)->alias, PHAR_G(last_phar)->alias_len)) {
				zend_hash_str_del(&(PHAR_G(phar_alias_map)), PHAR_G(last_phar)->alias, PHAR_G(last_phar)->alias_len);
			}

			zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len, archive);
			PHAR_G(last_alias) = alias;
			PHAR_G(last_alias_len) = alias_len;
		}

		return archive;
	}

	if (alias && alias_len) {
		/* If the alias stored in the last_phar cache matches, just use it directly */
		if (PHAR_G(last_phar) && alias_len == PHAR_G(last_alias_len) && !memcmp(alias, PHAR_G(last_alias), alias_len)) {
			archive = PHAR_G(last_phar);
		} else {
			archive = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len);
		}

		/* If we didn't find the alias, check in the cached manifest to see if we can find it */
		if (!archive && PHAR_G(manifest_cached)) {
			archive = zend_hash_str_find_ptr(&cached_alias, alias, alias_len);
		}

		if (archive) {
			if (!zend_string_equals_cstr(archive->fname, fname, fname_len)) {
				if (error) {
					spprintf(error, 0, "alias \"%s\" is already used for archive \"%s\" cannot be overloaded with \"%s\"", alias, ZSTR_VAL(archive->fname), fname);
				}
				if (SUCCESS == phar_free_alias(archive)) {
					if (error) {
						efree(*error);
						*error = NULL;
					}
				}
				return NULL;
			}

			PHAR_G(last_phar) = archive;
			PHAR_G(last_phar_name) = archive->fname;
			PHAR_G(last_alias) = alias;
			PHAR_G(last_alias_len) = alias_len;

			return archive;
		}
	}

	if (fname && fname_len) {
		archive = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len);
		if (archive) {
			if (alias && alias_len) {
				if (!archive->is_temporary_alias && (alias_len != archive->alias_len || memcmp(archive->alias, alias, alias_len))) {
					if (error) {
						spprintf(error, 0, "alias \"%s\" is already used for archive \"%s\" cannot be overloaded with \"%s\"", alias, ZSTR_VAL(archive->fname), fname);
					}
					return NULL;
				}

				if (archive->alias_len && zend_hash_str_exists(&(PHAR_G(phar_alias_map)), archive->alias, archive->alias_len)) {
					zend_hash_str_del(&(PHAR_G(phar_alias_map)), archive->alias, archive->alias_len);
				}

				zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len, archive);
			}

			PHAR_G(last_phar) = archive;
			PHAR_G(last_phar_name) = archive->fname;
			PHAR_G(last_alias) = archive->alias;
			PHAR_G(last_alias_len) = archive->alias_len;

			return archive;
		}

		if (PHAR_G(manifest_cached) && NULL != (archive = zend_hash_str_find_ptr(&cached_phars, fname, fname_len))) {
			/* this could be problematic - alias should never be different from manifest alias
			   for cached phars */
			if (!archive->is_temporary_alias && alias && alias_len) {
				if (alias_len != archive->alias_len || memcmp(archive->alias, alias, alias_len)) {
					if (error) {
						spprintf(error, 0, "alias \"%s\" is already used for archive \"%s\" cannot be overloaded with \"%s\"", alias, ZSTR_VAL(archive->fname), fname);
					}
					return NULL;
				}
			}

			PHAR_G(last_phar) = archive;
			PHAR_G(last_phar_name) = archive->fname;
			PHAR_G(last_alias) = archive->alias;
			PHAR_G(last_alias_len) = archive->alias_len;

			return archive;
		}

		archive = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), fname, fname_len);

		/* If we didn't find the fname in the alias map, check in the cached manifest to see if we can find it */
		if (!archive && PHAR_G(manifest_cached)) {
			archive = zend_hash_str_find_ptr(&cached_alias, fname, fname_len);
		}

		if (archive) {
			PHAR_G(last_phar) = archive;
			PHAR_G(last_phar_name) = archive->fname;
			PHAR_G(last_alias) = archive->alias;
			PHAR_G(last_alias_len) = archive->alias_len;

			return archive;
		}

		/* not found, try converting \ to / */
		char *my_realpath = expand_filepath(fname, NULL);

		if (UNEXPECTED(!my_realpath)) {
			return NULL;
		}

		size_t my_realpath_len = strlen(my_realpath);
#ifdef PHP_WIN32
		phar_unixify_path_separators(my_realpath, my_realpath_len);
#endif

		archive = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), my_realpath, my_realpath_len);

		/* If we didn't find the path in the fname map, check in the cached manifest to see if we can find it */
		if (!archive && PHAR_G(manifest_cached)) {
			archive = zend_hash_str_find_ptr(&cached_phars, my_realpath, my_realpath_len);
		}
		efree(my_realpath);

		if (archive) {
			if (alias && alias_len) {
				zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len, archive);
			}

			PHAR_G(last_phar) = archive;
			PHAR_G(last_phar_name) = archive->fname;
			PHAR_G(last_alias) = archive->alias;
			PHAR_G(last_alias_len) = archive->alias_len;

			return archive;
		}
	}

	return NULL;
}
/* }}} */

/**
 * Determine which stream compression filter (if any) we need to read this file
 */
const char * phar_compress_filter(const phar_entry_info *entry, bool return_unknown) /* {{{ */
{
	switch (entry->flags & PHAR_ENT_COMPRESSION_MASK) {
	case PHAR_ENT_COMPRESSED_GZ:
		return "zlib.deflate";
	case PHAR_ENT_COMPRESSED_BZ2:
		return "bzip2.compress";
	default:
		return return_unknown ? "unknown" : NULL;
	}
}
/* }}} */

/**
 * Determine which stream decompression filter (if any) we need to read this file
 */
const char * phar_decompress_filter(const phar_entry_info *entry, bool return_unknown) /* {{{ */
{
	uint32_t flags;

	if (entry->is_modified) {
		flags = entry->old_flags;
	} else {
		flags = entry->flags;
	}

	switch (flags & PHAR_ENT_COMPRESSION_MASK) {
		case PHAR_ENT_COMPRESSED_GZ:
			return "zlib.inflate";
		case PHAR_ENT_COMPRESSED_BZ2:
			return "bzip2.decompress";
		default:
			return return_unknown ? "unknown" : NULL;
	}
}
/* }}} */

/**
 * retrieve information on a file contained within a phar, or null if it ain't there
 */
phar_entry_info *phar_get_entry_info(phar_archive_data *phar, char *path, size_t path_len, char **error, bool security) /* {{{ */
{
	return phar_get_entry_info_dir(phar, path, path_len, 0, error, security);
}
/* }}} */
/**
 * retrieve information on a file or directory contained within a phar, or null if none found
 * allow_dir is 0 for none, 1 for both empty directories in the phar and temp directories, and 2 for only
 * valid pre-existing empty directory entries
 */
// TODO: convert this to use zend_string too
phar_entry_info *phar_get_entry_info_dir(phar_archive_data *phar, char *path, size_t path_len, char dir, char **error, bool security) /* {{{ */
{
	const char *pcr_error;
	bool is_dir;

#ifdef PHP_WIN32
	phar_unixify_path_separators(path, path_len);
#endif

	is_dir = path_len && (path[path_len - 1] == '/');

	if (error) {
		*error = NULL;
	}

	if (security && path_len >= sizeof(".phar")-1 && !memcmp(path, ".phar", sizeof(".phar")-1)) {
		if (error) {
			spprintf(error, 4096, "phar error: cannot directly access magic \".phar\" directory or files within it");
		}
		return NULL;
	}

	if (!path_len && !dir) {
		if (error) {
			spprintf(error, 4096, "phar error: invalid path \"%s\" must not be empty", path);
		}
		return NULL;
	}

	if (phar_path_check(&path, &path_len, &pcr_error) > pcr_is_ok) {
		if (error) {
			spprintf(error, 4096, "phar error: invalid path \"%s\" contains %s", path, pcr_error);
		}
		return NULL;
	}

	if (!HT_IS_INITIALIZED(&phar->manifest)) {
		return NULL;
	}

	if (is_dir) {
		if (path_len <= 1) {
			return NULL;
		}
		path_len--;
	}

	phar_entry_info *entry = zend_hash_str_find_ptr(&phar->manifest, path, path_len);
	if (entry) {
		if (entry->is_deleted) {
			/* entry is deleted, but has not been flushed to disk yet */
			return NULL;
		}
		if (entry->is_dir && !dir) {
			if (error) {
				spprintf(error, 4096, "phar error: path \"%s\" is a directory", path);
			}
			return NULL;
		}
		if (!entry->is_dir && dir == 2) {
			/* user requested a directory, we must return one */
			if (error) {
				spprintf(error, 4096, "phar error: path \"%s\" exists and is a not a directory", path);
			}
			return NULL;
		}
		return entry;
	}

	if (dir) {
		if (zend_hash_str_exists(&phar->virtual_dirs, path, path_len)) {
			/* a file or directory exists in a sub-directory of this path */
			entry = (phar_entry_info *) ecalloc(1, sizeof(phar_entry_info));
			/* this next line tells PharFileInfo->__destruct() to efree the filename */
			entry->is_temp_dir = entry->is_dir = 1;
			entry->filename = zend_string_init(path, path_len, false);
			entry->phar = phar;
			return entry;
		}
	}

	if (HT_IS_INITIALIZED(&phar->mounted_dirs) && zend_hash_num_elements(&phar->mounted_dirs)) {
		zend_string *str_key;

		ZEND_HASH_MAP_FOREACH_STR_KEY(&phar->mounted_dirs, str_key) {
			if (ZSTR_LEN(str_key) >= path_len || strncmp(ZSTR_VAL(str_key), path, ZSTR_LEN(str_key))) {
				continue;
			} else {
				char *test;
				size_t test_len;
				php_stream_statbuf ssb;

				entry = zend_hash_find_ptr(&phar->manifest, str_key);
				if (!entry) {
					if (error) {
						spprintf(error, 4096, "phar internal error: mounted path \"%s\" could not be retrieved from manifest", ZSTR_VAL(str_key));
					}
					return NULL;
				}

				if (!entry->tmp || !entry->is_mounted) {
					if (error) {
						spprintf(error, 4096, "phar internal error: mounted path \"%s\" is not properly initialized as a mounted path", ZSTR_VAL(str_key));
					}
					return NULL;
				}

				test_len = spprintf(&test, MAXPATHLEN, "%s%s", entry->tmp, path + ZSTR_LEN(str_key));

				if (SUCCESS != php_stream_stat_path(test, &ssb)) {
					efree(test);
					return NULL;
				}

				if ((ssb.sb.st_mode & S_IFDIR) && !dir) {
					efree(test);
					if (error) {
						spprintf(error, 4096, "phar error: path \"%s\" is a directory", path);
					}
					return NULL;
				}

				if ((ssb.sb.st_mode & S_IFDIR) == 0 && dir) {
					efree(test);
					/* user requested a directory, we must return one */
					if (error) {
						spprintf(error, 4096, "phar error: path \"%s\" exists and is a not a directory", path);
					}
					return NULL;
				}

				/* mount the file just in time */
				if (SUCCESS != phar_mount_entry(phar, test, test_len, path, path_len)) {
					efree(test);
					if (error) {
						spprintf(error, 4096, "phar error: path \"%s\" exists as file \"%s\" and could not be mounted", path, test);
					}
					return NULL;
				}

				efree(test);

				entry = zend_hash_str_find_ptr(&phar->manifest, path, path_len);
				if (!entry) {
					if (error) {
						spprintf(error, 4096, "phar error: path \"%s\" exists as file \"%s\" and could not be retrieved after being mounted", path, test);
					}
					return NULL;
				}
				return entry;
			}
		} ZEND_HASH_FOREACH_END();
	}

	return NULL;
}
/* }}} */

static const char hexChars[] = "0123456789ABCDEF";

static size_t phar_hex_str(const char *digest, size_t digest_len, char **signature) /* {{{ */
{
	size_t pos = 0;
	size_t len = 0;

	*signature = (char*)safe_pemalloc(digest_len, 2, 1, PHAR_G(persist));

	for (; len < digest_len; ++len) {
		(*signature)[pos++] = hexChars[((const unsigned char *)digest)[len] >> 4];
		(*signature)[pos++] = hexChars[((const unsigned char *)digest)[len] & 0x0F];
	}
	(*signature)[pos] = '\0';
	return pos;
}
/* }}} */

#ifndef PHAR_HAVE_OPENSSL
ZEND_ATTRIBUTE_NONNULL static bool phar_call_openssl_verify(
	php_stream *fp,
	zend_off_t end,
	zend_string *public_key,
	const char *signature,
	size_t signature_len,
	uint32_t sig_type
) {
	ZEND_ASSERT(signature_len != 0);
	zend_function *fn = zend_hash_str_find_ptr(CG(function_table), ZEND_STRL("openssl_verify"));

	/* OpenSSL is not available, even as a shared module */
	if (UNEXPECTED(fn == NULL)) {
		return false;
	}

	/* Read and copy stream content */
	php_stream_rewind(fp);
	zend_string *str = php_stream_copy_to_mem(fp, (size_t) end, false);
	/* No content thus signing must fail */
	if (UNEXPECTED(str == NULL || (size_t)end != ZSTR_LEN(str))) {
		return false;
	}

	/* Set up parameters for call to openssl_verify()
	 * openssl_verify(
	 *	string $data,
	 *	string $signature,
	 *	OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $public_key,
	 *	string|int $algorithm = OPENSSL_ALGO_SHA1,
	 *	int $padding = 0
	 * ): int|false
	 */
	zval retval, zp[4];
	ZVAL_STR(&zp[0], str);
	ZVAL_STRINGL(&zp[1], signature, signature_len);
	/* Note we do not own the lifetime of the public key, but it is fine as calling the function will increase the refcount) */
	ZVAL_STR(&zp[2], public_key);
	if (sig_type == PHAR_SIG_OPENSSL_SHA512) {
		ZVAL_LONG(&zp[3], 9); /* value from openssl.c #define OPENSSL_ALGO_SHA512 9 */
	} else if (sig_type == PHAR_SIG_OPENSSL_SHA256) {
		ZVAL_LONG(&zp[3], 7); /* value from openssl.c #define OPENSSL_ALGO_SHA256 7 */
	} else {
		/* don't rely on default value which may change in the future */
		ZVAL_LONG(&zp[3], 1); /* value from openssl.c #define OPENSSL_ALGO_SHA1   1 */
	}
	zend_call_known_function(fn, NULL, NULL, &retval, /* param_count */ 4, zp, NULL);
	/* Free string arguments that we own */
	zval_ptr_dtor_str(&zp[0]);
	zval_ptr_dtor_str(&zp[1]);

	/* Returns 1 if the signature is correct, 0 if it is incorrect, and -1 or false on error. */
	switch (Z_TYPE(retval)) {
		case IS_LONG:
			if (1 == Z_LVAL(retval)) {
				return true;
			}
			ZEND_FALLTHROUGH;
		default:
			/* Unlikely, but the openssl_verify() function may be disabled and redefined in userland and return bollocks */
			zval_ptr_dtor(&retval);
			return false;
	}
}

static zend_result phar_call_openssl_sign(php_stream *fp, zend_off_t end, const char *key, size_t key_len, char **signature, size_t *signature_len, uint32_t sig_type) /* {{{ */
{
	ZEND_ASSERT(end != 0);
	ZEND_ASSERT(*signature_len == 0);
	zval retval, zp[4];

	zend_function *fn = zend_hash_str_find_ptr(CG(function_table), ZEND_STRL("openssl_sign"));

	/* OpenSSL is not available, even as a shared module */
	if (fn == NULL) {
		return FAILURE;
	}

	/* Read and copy stream content */
	php_stream_rewind(fp);
	zend_string *str = php_stream_copy_to_mem(fp, (size_t) end, false);
	/* No content thus signing must fail */
	if (!str || (size_t)end != ZSTR_LEN(str)) {
		return FAILURE;
	}

	/* Set up parameters for call to openssl_sign()
	 * openssl_sign(
	 *	string $data,
	 *	string &$signature,
	 *	#[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key,
	 *	string|int $algorithm = OPENSSL_ALGO_SHA1,
	 *	int $padding = 0
	 * ): bool
	 */
	ZVAL_STR(&zp[0], str);
	ZVAL_EMPTY_STRING(&zp[1]);
	ZVAL_NEW_REF(&zp[1], &zp[1]);
	ZVAL_STRINGL(&zp[2], key, key_len);
	if (sig_type == PHAR_SIG_OPENSSL_SHA512) {
		ZVAL_LONG(&zp[3], 9); /* value from openssl.c #define OPENSSL_ALGO_SHA512 9 */
	} else if (sig_type == PHAR_SIG_OPENSSL_SHA256) {
		ZVAL_LONG(&zp[3], 7); /* value from openssl.c #define OPENSSL_ALGO_SHA256 7 */
	} else {
		/* don't rely on default value which may change in the future */
		ZVAL_LONG(&zp[3], 1); /* value from openssl.c #define OPENSSL_ALGO_SHA1   1 */
	}

	zend_call_known_function(fn, NULL, NULL, &retval, /* param_count */ 4, zp, NULL);

	ZVAL_UNREF(&zp[1]);

	zval_ptr_dtor_str(&zp[0]);
	zval_ptr_dtor_str(&zp[2]);

	switch (Z_TYPE(retval)) {
		case IS_TRUE:
			*signature = estrndup(Z_STRVAL(zp[1]), Z_STRLEN(zp[1]));
			*signature_len = Z_STRLEN(zp[1]);
			zval_ptr_dtor(&zp[1]);
			return SUCCESS;
		default:
			/* Unlikely, but the openssl_sign() function may be disabled and redefined in userland and return bollocks */
			zval_ptr_dtor(&retval);
			zval_ptr_dtor(&zp[1]);
			return FAILURE;
	}
}
/* }}} */
#endif /* #ifndef PHAR_HAVE_OPENSSL */

zend_result phar_verify_signature(php_stream *fp, size_t end_of_phar, uint32_t sig_type, const char *sig, size_t sig_len, const char *fname, char **signature, size_t *signature_len, char **error) /* {{{ */
{
	size_t read_size, len;
	zend_off_t read_len;
	unsigned char buf[1024];

	php_stream_rewind(fp);

	switch (sig_type) {
		case PHAR_SIG_OPENSSL_SHA512:
		case PHAR_SIG_OPENSSL_SHA256:
		case PHAR_SIG_OPENSSL: {
#ifdef PHAR_HAVE_OPENSSL
			BIO *in;
			EVP_PKEY *key;
			const EVP_MD *mdtype;
			EVP_MD_CTX *md_ctx;

			if (sig_type == PHAR_SIG_OPENSSL_SHA512) {
				mdtype = EVP_sha512();
			} else if (sig_type == PHAR_SIG_OPENSSL_SHA256) {
				mdtype = EVP_sha256();
			} else {
				mdtype = EVP_sha1();
			}
#endif
			zend_string *pubkey = NULL;
			char *pfile;
			php_stream *pfp;
#ifndef PHAR_HAVE_OPENSSL
			if (!zend_hash_str_exists(&module_registry, "openssl", sizeof("openssl")-1)) {
				if (error) {
					*error = estrdup("openssl not loaded");
				}
				return FAILURE;
			}
#endif
			/* use __FILE__ . '.pubkey' for public key file */
			spprintf(&pfile, 0, "%s.pubkey", fname);
			pfp = php_stream_open_wrapper(pfile, "rb", 0, NULL);
			efree(pfile);

			if (!pfp) {
				if (error) {
					*error = estrdup("openssl public key could not be read");
				}
				return FAILURE;
			}

			pubkey = php_stream_copy_to_mem(pfp, PHP_STREAM_COPY_ALL, 0);
			php_stream_close(pfp);
			if (!pubkey || !ZSTR_LEN(pubkey)) {
				if (error) {
					*error = estrdup("openssl public key could not be read");
				}
				return FAILURE;
			}

#ifndef PHAR_HAVE_OPENSSL
			if (!phar_call_openssl_verify(fp, end_of_phar, pubkey, sig, sig_len, sig_type)) {
				zend_string_release_ex(pubkey, 0);

				if (error) {
					*error = estrdup("openssl signature could not be verified");
				}

				return FAILURE;
			}

			zend_string_release_ex(pubkey, false);
#else
			in = BIO_new_mem_buf(ZSTR_VAL(pubkey), ZSTR_LEN(pubkey));

			if (NULL == in) {
				zend_string_release_ex(pubkey, 0);
				if (error) {
					*error = estrdup("openssl signature could not be processed");
				}
				return FAILURE;
			}

			key = PEM_read_bio_PUBKEY(in, NULL, NULL, NULL);
			BIO_free(in);
			zend_string_release_ex(pubkey, 0);

			if (NULL == key) {
				if (error) {
					*error = estrdup("openssl signature could not be processed");
				}
				return FAILURE;
			}

			md_ctx = EVP_MD_CTX_create();
			if (!md_ctx || !EVP_VerifyInit(md_ctx, mdtype)) {
				if (md_ctx) {
					EVP_MD_CTX_destroy(md_ctx);
				}
				EVP_PKEY_free(key);
				if (error) {
					*error = estrdup("openssl signature could not be verified");
				}
				return FAILURE;
			}
			read_len = end_of_phar;

			if ((size_t)read_len > sizeof(buf)) {
				read_size = sizeof(buf);
			} else {
				read_size = (size_t)read_len;
			}

			php_stream_seek(fp, 0, SEEK_SET);

			while (read_size && (len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
				if (UNEXPECTED(EVP_VerifyUpdate (md_ctx, buf, len) == 0)) {
					goto failure;
				}
				read_len -= (zend_off_t)len;

				if (read_len < read_size) {
					read_size = (size_t)read_len;
				}
			}

			if (EVP_VerifyFinal(md_ctx, (unsigned char *)sig, sig_len, key) != 1) {
				failure:
				/* 1: signature verified, 0: signature does not match, -1: failed signature operation */
				EVP_PKEY_free(key);
				EVP_MD_CTX_destroy(md_ctx);

				if (error) {
					*error = estrdup("broken openssl signature");
				}

				return FAILURE;
			}

			EVP_PKEY_free(key);
			EVP_MD_CTX_destroy(md_ctx);
#endif

			*signature_len = phar_hex_str(sig, sig_len, signature);
		}
		break;
		case PHAR_SIG_SHA512: {
			unsigned char digest[64];
			PHP_SHA512_CTX context;

			if (sig_len < sizeof(digest)) {
				if (error) {
					*error = estrdup("broken openssl signature");
				}
				return FAILURE;
			}

			PHP_SHA512Init(&context);
			read_len = end_of_phar;

			if ((size_t)read_len > sizeof(buf)) {
				read_size = sizeof(buf);
			} else {
				read_size = (size_t)read_len;
			}

			while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
				PHP_SHA512Update(&context, buf, len);
				read_len -= (zend_off_t)len;
				if ((size_t)read_len < read_size) {
					read_size = (size_t)read_len;
				}
			}

			PHP_SHA512Final(digest, &context);

			if (memcmp(digest, sig, sizeof(digest))) {
				if (error) {
					*error = estrdup("broken openssl signature");
				}
				return FAILURE;
			}

			*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);
			break;
		}
		case PHAR_SIG_SHA256: {
			unsigned char digest[32];
			PHP_SHA256_CTX context;

			if (sig_len < sizeof(digest)) {
				if (error) {
					*error = estrdup("broken openssl signature");
				}
				return FAILURE;
			}

			PHP_SHA256Init(&context);
			read_len = end_of_phar;

			if ((size_t)read_len > sizeof(buf)) {
				read_size = sizeof(buf);
			} else {
				read_size = (size_t)read_len;
			}

			while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
				PHP_SHA256Update(&context, buf, len);
				read_len -= (zend_off_t)len;
				if ((size_t)read_len < read_size) {
					read_size = (size_t)read_len;
				}
			}

			PHP_SHA256Final(digest, &context);

			if (memcmp(digest, sig, sizeof(digest))) {
				if (error) {
					*error = estrdup("broken signature");
				}
				return FAILURE;
			}

			*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);
			break;
		}
		case PHAR_SIG_SHA1: {
			unsigned char digest[20];
			PHP_SHA1_CTX  context;

			if (sig_len < sizeof(digest)) {
				if (error) {
					*error = estrdup("broken signature");
				}
				return FAILURE;
			}

			PHP_SHA1Init(&context);
			read_len = end_of_phar;

			if ((size_t)read_len > sizeof(buf)) {
				read_size = sizeof(buf);
			} else {
				read_size = (size_t)read_len;
			}

			while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
				PHP_SHA1Update(&context, buf, len);
				read_len -= (zend_off_t)len;
				if ((size_t)read_len < read_size) {
					read_size = (size_t)read_len;
				}
			}

			PHP_SHA1Final(digest, &context);

			if (memcmp(digest, sig, sizeof(digest))) {
				if (error) {
					*error = estrdup("broken signature");
				}
				return FAILURE;
			}

			*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);
			break;
		}
		case PHAR_SIG_MD5: {
			unsigned char digest[16];
			PHP_MD5_CTX   context;

			if (sig_len < sizeof(digest)) {
				if (error) {
					*error = estrdup("broken signature");
				}
				return FAILURE;
			}

			PHP_MD5Init(&context);
			read_len = end_of_phar;

			if ((size_t)read_len > sizeof(buf)) {
				read_size = sizeof(buf);
			} else {
				read_size = (size_t)read_len;
			}

			while ((len = php_stream_read(fp, (char*)buf, read_size)) > 0) {
				PHP_MD5Update(&context, buf, len);
				read_len -= (zend_off_t)len;
				if ((size_t)read_len < read_size) {
					read_size = (size_t)read_len;
				}
			}

			PHP_MD5Final(digest, &context);

			if (memcmp(digest, sig, sizeof(digest))) {
				if (error) {
					*error = estrdup("broken signature");
				}
				return FAILURE;
			}

			*signature_len = phar_hex_str((const char*)digest, sizeof(digest), signature);
			break;
		}
		default:
			if (error) {
				*error = estrdup("broken or unsupported signature");
			}
			return FAILURE;
	}
	return SUCCESS;
}
/* }}} */

ZEND_ATTRIBUTE_NONNULL zend_string* phar_create_signature(phar_archive_data *phar, php_stream *fp, char **error) /* {{{ */
{
	zend_string *signature = NULL;
	unsigned char buf[1024];
	size_t sig_len;

	php_stream_rewind(fp);

	if (phar->signature) {
		efree(phar->signature);
		phar->signature = NULL;
	}

	switch(phar->sig_flags) {
		case PHAR_SIG_SHA512: {
			unsigned char digest[64];
			PHP_SHA512_CTX context;

			PHP_SHA512Init(&context);

			while ((sig_len = php_stream_read(fp, (char*)buf, sizeof(buf))) > 0) {
				PHP_SHA512Update(&context, buf, sig_len);
			}

			PHP_SHA512Final(digest, &context);
			signature = zend_string_init((const char*)digest, 64, false);
			break;
		}
		default:
			phar->sig_flags = PHAR_SIG_SHA256;
			ZEND_FALLTHROUGH;
		case PHAR_SIG_SHA256: {
			unsigned char digest[32];
			PHP_SHA256_CTX  context;

			PHP_SHA256Init(&context);

			while ((sig_len = php_stream_read(fp, (char*)buf, sizeof(buf))) > 0) {
				PHP_SHA256Update(&context, buf, sig_len);
			}

			PHP_SHA256Final(digest, &context);
			signature = zend_string_init((const char*)digest, 32, false);
			break;
		}
		case PHAR_SIG_OPENSSL_SHA512:
		case PHAR_SIG_OPENSSL_SHA256:
		case PHAR_SIG_OPENSSL: {
			unsigned char *sigbuf;
#ifdef PHAR_HAVE_OPENSSL
			unsigned int siglen;
			BIO *in;
			EVP_PKEY *key;
			EVP_MD_CTX *md_ctx;
			const EVP_MD *mdtype;

			if (phar->sig_flags == PHAR_SIG_OPENSSL_SHA512) {
				mdtype = EVP_sha512();
			} else if (phar->sig_flags == PHAR_SIG_OPENSSL_SHA256) {
				mdtype = EVP_sha256();
			} else {
				mdtype = EVP_sha1();
			}

			in = BIO_new_mem_buf(PHAR_G(openssl_privatekey), PHAR_G(openssl_privatekey_len));

			if (in == NULL) {
				spprintf(error, 0, "unable to write to phar \"%s\" with requested openssl signature", ZSTR_VAL(phar->fname));
				return NULL;
			}

			key = PEM_read_bio_PrivateKey(in, NULL,NULL, "");
			BIO_free(in);

			if (!key) {
				*error = estrdup("unable to process private key");
				return NULL;
			}

			md_ctx = EVP_MD_CTX_create();
			if (md_ctx == NULL) {
				EVP_PKEY_free(key);
				spprintf(error, 0, "unable to initialize openssl signature for phar \"%s\"", ZSTR_VAL(phar->fname));
				return NULL;
			}

			siglen = EVP_PKEY_size(key);
			sigbuf = emalloc(siglen + 1);

			if (!EVP_SignInit(md_ctx, mdtype)) {
				EVP_PKEY_free(key);
				EVP_MD_CTX_destroy(md_ctx);
				efree(sigbuf);
				spprintf(error, 0, "unable to initialize openssl signature for phar \"%s\"", ZSTR_VAL(phar->fname));
				return NULL;
			}

			while ((sig_len = php_stream_read(fp, (char*)buf, sizeof(buf))) > 0) {
				if (!EVP_SignUpdate(md_ctx, buf, sig_len)) {
					EVP_PKEY_free(key);
					EVP_MD_CTX_destroy(md_ctx);
					efree(sigbuf);
					spprintf(error, 0, "unable to update the openssl signature for phar \"%s\"", ZSTR_VAL(phar->fname));
					return NULL;
				}
			}

			if (!EVP_SignFinal (md_ctx, sigbuf, &siglen, key)) {
				EVP_PKEY_free(key);
				EVP_MD_CTX_destroy(md_ctx);
				efree(sigbuf);
				spprintf(error, 0, "unable to write phar \"%s\" with requested openssl signature", ZSTR_VAL(phar->fname));
				return NULL;
			}

			sigbuf[siglen] = '\0';
			EVP_PKEY_free(key);
			EVP_MD_CTX_destroy(md_ctx);
			signature = zend_string_init((const char*)sigbuf, siglen, false);
			efree(sigbuf);
#else
			size_t siglen;
			sigbuf = NULL;
			siglen = 0;
			php_stream_seek(fp, 0, SEEK_END);

			if (FAILURE == phar_call_openssl_sign(fp, php_stream_tell(fp), PHAR_G(openssl_privatekey), PHAR_G(openssl_privatekey_len), (char **)&sigbuf, &siglen, phar->sig_flags)) {
				spprintf(error, 0, "unable to write phar \"%s\" with requested openssl signature", ZSTR_VAL(phar->fname));
				return NULL;
			}
			signature = zend_string_init((const char*)sigbuf, siglen, false);
			efree(sigbuf);
#endif
		}
		break;
		case PHAR_SIG_SHA1: {
			unsigned char digest[20];
			PHP_SHA1_CTX  context;

			PHP_SHA1Init(&context);

			while ((sig_len = php_stream_read(fp, (char*)buf, sizeof(buf))) > 0) {
				PHP_SHA1Update(&context, buf, sig_len);
			}

			PHP_SHA1Final(digest, &context);
			signature = zend_string_init((const char*)digest, 20, false);
			break;
		}
		case PHAR_SIG_MD5: {
			unsigned char digest[16];
			PHP_MD5_CTX   context;

			PHP_MD5Init(&context);

			while ((sig_len = php_stream_read(fp, (char*)buf, sizeof(buf))) > 0) {
				PHP_MD5Update(&context, buf, sig_len);
			}

			PHP_MD5Final(digest, &context);
			signature = zend_string_init((const char*)digest, 16, false);
			break;
		}
	}

	phar->sig_len = phar_hex_str(ZSTR_VAL(signature), ZSTR_LEN(signature), &phar->signature);
	return signature;
}
/* }}} */

// TODO: convert this to zend_string too
void phar_add_virtual_dirs(phar_archive_data *phar, const char *filename, size_t filename_len) /* {{{ */
{
	const char *s;
	zend_string *str;
	zval *ret;

	while ((s = zend_memrchr(filename, '/', filename_len))) {
		filename_len = s - filename;
		if (!filename_len) {
			break;
		}
		if (GC_FLAGS(&phar->virtual_dirs) & GC_PERSISTENT) {
			str = zend_string_init_interned(filename, filename_len, 1);
		} else {
			str = zend_string_init(filename, filename_len, 0);
		}
		ret = zend_hash_add_empty_element(&phar->virtual_dirs, str);
		zend_string_release(str);
		if (ret == NULL) {
			break;
		}
	}
}
/* }}} */

static int phar_update_cached_entry(zval *data, void *argument) /* {{{ */
{
	phar_entry_info *entry = (phar_entry_info *)Z_PTR_P(data);

	entry->phar = (phar_archive_data *)argument;

	if (entry->symlink) {
		zend_string_addref(entry->symlink);
	}

	if (entry->tmp) {
		entry->tmp = estrdup(entry->tmp);
	}

	zend_string_addref(entry->filename);
	entry->is_persistent = 0;

	/* Replace metadata with non-persistent clones of the metadata. */
	phar_metadata_tracker_clone(&entry->metadata_tracker);
	return ZEND_HASH_APPLY_KEEP;
}
/* }}} */

static void phar_manifest_copy_ctor(zval *zv) /* {{{ */
{
	phar_entry_info *info = emalloc(sizeof(phar_entry_info));
	memcpy(info, Z_PTR_P(zv), sizeof(phar_entry_info));
	Z_PTR_P(zv) = info;
}
/* }}} */

static phar_archive_data* phar_copy_cached_phar(const phar_archive_data *persistent_phar) /* {{{ */
{
	HashTable newmanifest;
	phar_archive_object *objphar;

	phar_archive_data *phar = emalloc(sizeof(phar_archive_data));
	*phar = *persistent_phar;
	phar->is_persistent = 0;
	zend_string_addref(phar->fname);

	if (phar->alias) {
		phar->alias = estrndup(phar->alias, phar->alias_len);
	}

	if (phar->signature) {
		phar->signature = estrdup(phar->signature);
	}

	phar_metadata_tracker_clone(&phar->metadata_tracker);

	zend_hash_init(&newmanifest, sizeof(phar_entry_info), NULL, destroy_phar_manifest_entry, 0);
	zend_hash_copy(&newmanifest, &persistent_phar->manifest, phar_manifest_copy_ctor);
	zend_hash_apply_with_argument(&newmanifest, phar_update_cached_entry, (void *)phar);
	phar->manifest = newmanifest;
	zend_hash_init(&phar->mounted_dirs, sizeof(char *), NULL, NULL, 0);
	zend_hash_init(&phar->virtual_dirs, sizeof(char *), NULL, NULL, 0);
	zend_hash_copy(&phar->virtual_dirs, &persistent_phar->virtual_dirs, NULL);

	/* now, scan the list of persistent Phar objects referencing this phar and update the pointers */
	ZEND_HASH_MAP_FOREACH_PTR(&PHAR_G(phar_persist_map), objphar) {
		if (zend_string_equals(objphar->archive->fname, phar->fname)) {
			objphar->archive = phar;
		}
	} ZEND_HASH_FOREACH_END();
	return phar;
}
/* }}} */

zend_result phar_copy_on_write(phar_archive_data **pphar) /* {{{ */
{
	phar_archive_data *newpphar = phar_copy_cached_phar(*pphar);

	zval *pzv = zend_hash_add_ptr(&(PHAR_G(phar_fname_map)), newpphar->fname, newpphar);
	if (!pzv) {
		return FAILURE;
	}

	/* invalidate phar cache */
	PHAR_G(last_phar) = NULL;
	PHAR_G(last_alias) = NULL;
	PHAR_G(last_phar_name) = NULL;

	if (newpphar->alias_len && NULL == zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), newpphar->alias, newpphar->alias_len, newpphar)) {
		zend_hash_del(&(PHAR_G(phar_fname_map)), newpphar->fname);
		return FAILURE;
	}

	*pphar = newpphar;
	return SUCCESS;
}
/* }}} */
