xref: /PHP-8.4/ext/phar/tar.c (revision 2513258a)
1 /*
2   +----------------------------------------------------------------------+
3   | TAR archive support for Phar                                         |
4   +----------------------------------------------------------------------+
5   | Copyright (c) The PHP Group                                          |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | https://www.php.net/license/3_01.txt                                 |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Dmitry Stogov <dmitry@php.net>                              |
16   |          Gregory Beaver <cellog@php.net>                             |
17   +----------------------------------------------------------------------+
18 */
19 
20 #include "phar_internal.h"
21 #include "ext/standard/php_string.h" /* For php_stristr() */
22 
phar_tar_number(const char * buf,size_t len)23 static uint32_t phar_tar_number(const char *buf, size_t len) /* {{{ */
24 {
25 	uint32_t num = 0;
26 	size_t i = 0;
27 
28 	while (i < len && buf[i] == ' ') {
29 		++i;
30 	}
31 
32 	while (i < len && buf[i] >= '0' && buf[i] <= '7') {
33 		num = num * 8 + (buf[i] - '0');
34 		++i;
35 	}
36 
37 	return num;
38 }
39 /* }}} */
40 
41 /* adapted from format_octal() in libarchive
42  *
43  * Copyright (c) 2003-2009 Tim Kientzle
44  * All rights reserved.
45  *
46  * Redistribution and use in source and binary forms, with or without
47  * modification, are permitted provided that the following conditions
48  * are met:
49  * 1. Redistributions of source code must retain the above copyright
50  *    notice, this list of conditions and the following disclaimer.
51  * 2. Redistributions in binary form must reproduce the above copyright
52  *    notice, this list of conditions and the following disclaimer in the
53  *    documentation and/or other materials provided with the distribution.
54  *
55  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
56  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
57  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
58  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
59  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
60  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
61  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
62  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
63  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
64  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
65  */
phar_tar_octal(char * buf,uint32_t val,size_t len)66 static zend_result phar_tar_octal(char *buf, uint32_t val, size_t len) /* {{{ */
67 {
68 	char *p = buf;
69 	size_t s = len;
70 
71 	p += len;		/* Start at the end and work backwards. */
72 	while (s-- > 0) {
73 		*--p = (char)('0' + (val & 7));
74 		val >>= 3;
75 	}
76 
77 	if (val == 0) {
78 		return SUCCESS;
79 	}
80 
81 	/* If it overflowed, fill field with max value. */
82 	while (len-- > 0) {
83 		*p++ = '7';
84 	}
85 
86 	return FAILURE;
87 }
88 /* }}} */
89 
phar_tar_checksum(char * buf,size_t len)90 static uint32_t phar_tar_checksum(char *buf, size_t len) /* {{{ */
91 {
92 	uint32_t sum = 0;
93 	char *end = buf + len;
94 
95 	while (buf != end) {
96 		sum += (unsigned char)*buf;
97 		++buf;
98 	}
99 	return sum;
100 }
101 /* }}} */
102 
phar_is_tar(char * buf,char * fname)103 bool phar_is_tar(char *buf, char *fname) /* {{{ */
104 {
105 	tar_header *header = (tar_header *) buf;
106 	uint32_t checksum = phar_tar_number(header->checksum, sizeof(header->checksum));
107 	bool is_tar;
108 	char save[sizeof(header->checksum)], *bname;
109 
110 	/* assume that the first filename in a tar won't begin with <?php */
111 	if (!strncmp(buf, "<?php", sizeof("<?php")-1)) {
112 		return false;
113 	}
114 
115 	memcpy(save, header->checksum, sizeof(header->checksum));
116 	memset(header->checksum, ' ', sizeof(header->checksum));
117 	is_tar = (checksum == phar_tar_checksum(buf, 512));
118 	memcpy(header->checksum, save, sizeof(header->checksum));
119 	if ((bname = strrchr(fname, PHP_DIR_SEPARATOR))) {
120 		fname = bname;
121 	}
122 	if (!is_tar && (bname = strstr(fname, ".tar")) && (bname[4] == '\0' || bname[4] == '.')) {
123 		/* probably a corrupted tar - so we will pretend it is one */
124 		return true;
125 	}
126 	return is_tar;
127 }
128 /* }}} */
129 
phar_open_or_create_tar(char * fname,size_t fname_len,char * alias,size_t alias_len,int is_data,uint32_t options,phar_archive_data ** pphar,char ** error)130 zend_result phar_open_or_create_tar(char *fname, size_t fname_len, char *alias, size_t alias_len, int is_data, uint32_t options, phar_archive_data** pphar, char **error) /* {{{ */
131 {
132 	phar_archive_data *phar;
133 	zend_result ret = phar_create_or_parse_filename(fname, fname_len, alias, alias_len, is_data, options, &phar, error);
134 
135 	if (FAILURE == ret) {
136 		return FAILURE;
137 	}
138 
139 	if (pphar) {
140 		*pphar = phar;
141 	}
142 
143 	phar->is_data = is_data;
144 
145 	if (phar->is_tar) {
146 		return ret;
147 	}
148 
149 	if (phar->is_brandnew) {
150 		phar->is_tar = 1;
151 		phar->is_zip = 0;
152 		return SUCCESS;
153 	}
154 
155 	/* we've reached here - the phar exists and is a regular phar */
156 	if (error) {
157 		spprintf(error, 4096, "phar tar error: \"%s\" already exists as a regular phar and must be deleted from disk prior to creating as a tar-based phar", fname);
158 	}
159 	return FAILURE;
160 }
161 /* }}} */
162 
phar_tar_process_metadata(phar_entry_info * entry,php_stream * fp)163 static zend_result phar_tar_process_metadata(phar_entry_info *entry, php_stream *fp) /* {{{ */
164 {
165 	char *metadata;
166 	size_t save = php_stream_tell(fp), read;
167 	phar_entry_info *mentry;
168 
169 	metadata = (char *) safe_emalloc(1, entry->uncompressed_filesize, 1);
170 
171 	read = php_stream_read(fp, metadata, entry->uncompressed_filesize);
172 	if (read != entry->uncompressed_filesize) {
173 		efree(metadata);
174 		php_stream_seek(fp, save, SEEK_SET);
175 		return FAILURE;
176 	}
177 
178 	phar_parse_metadata_lazy(metadata, &entry->metadata_tracker, entry->uncompressed_filesize, entry->is_persistent);
179 
180 	if (entry->filename_len == sizeof(".phar/.metadata.bin")-1 && !memcmp(entry->filename, ".phar/.metadata.bin", sizeof(".phar/.metadata.bin")-1)) {
181 		if (phar_metadata_tracker_has_data(&entry->phar->metadata_tracker, entry->phar->is_persistent)) {
182 			efree(metadata);
183 			return FAILURE;
184 		}
185 		entry->phar->metadata_tracker = entry->metadata_tracker;
186 		entry->metadata_tracker.str = NULL;
187 		ZVAL_UNDEF(&entry->metadata_tracker.val);
188 	} else if (entry->filename_len >= sizeof(".phar/.metadata/") + sizeof("/.metadata.bin") - 1 && NULL != (mentry = zend_hash_str_find_ptr(&(entry->phar->manifest), entry->filename + sizeof(".phar/.metadata/") - 1, entry->filename_len - (sizeof("/.metadata.bin") - 1 + sizeof(".phar/.metadata/") - 1)))) {
189 		if (phar_metadata_tracker_has_data(&mentry->metadata_tracker, mentry->is_persistent)) {
190 			efree(metadata);
191 			return FAILURE;
192 		}
193 		/* transfer this metadata to the entry it refers */
194 		mentry->metadata_tracker = entry->metadata_tracker;
195 		entry->metadata_tracker.str = NULL;
196 		ZVAL_UNDEF(&entry->metadata_tracker.val);
197 	}
198 
199 	efree(metadata);
200 	php_stream_seek(fp, save, SEEK_SET);
201 	return SUCCESS;
202 }
203 /* }}} */
204 
phar_parse_tarfile(php_stream * fp,char * fname,size_t fname_len,char * alias,size_t alias_len,phar_archive_data ** pphar,uint32_t compression,char ** error)205 zend_result phar_parse_tarfile(php_stream* fp, char *fname, size_t fname_len, char *alias, size_t alias_len, phar_archive_data** pphar, uint32_t compression, char **error) /* {{{ */
206 {
207 	char buf[512], *actual_alias = NULL, *p;
208 	phar_entry_info entry = {0};
209 	size_t pos = 0, read, totalsize;
210 	tar_header *hdr;
211 	uint32_t sum1, sum2, size, old;
212 	phar_archive_data *myphar, *actual;
213 	int last_was_longlink = 0;
214 	size_t linkname_len;
215 
216 	if (error) {
217 		*error = NULL;
218 	}
219 
220 	php_stream_seek(fp, 0, SEEK_END);
221 	totalsize = php_stream_tell(fp);
222 	php_stream_seek(fp, 0, SEEK_SET);
223 	read = php_stream_read(fp, buf, sizeof(buf));
224 
225 	if (read != sizeof(buf)) {
226 		if (error) {
227 			spprintf(error, 4096, "phar error: \"%s\" is not a tar file or is truncated", fname);
228 		}
229 		php_stream_close(fp);
230 		return FAILURE;
231 	}
232 
233 	hdr = (tar_header*)buf;
234 	old = (memcmp(hdr->magic, "ustar", sizeof("ustar")-1) != 0);
235 
236 	myphar = (phar_archive_data *) pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist));
237 	myphar->is_persistent = PHAR_G(persist);
238 	/* estimate number of entries, can't be certain with tar files */
239 	zend_hash_init(&myphar->manifest, 2 + (totalsize >> 12),
240 		zend_get_hash_value, destroy_phar_manifest_entry, (bool)myphar->is_persistent);
241 	zend_hash_init(&myphar->mounted_dirs, 5,
242 		zend_get_hash_value, NULL, (bool)myphar->is_persistent);
243 	zend_hash_init(&myphar->virtual_dirs, 4 + (totalsize >> 11),
244 		zend_get_hash_value, NULL, (bool)myphar->is_persistent);
245 	myphar->is_tar = 1;
246 	/* remember whether this entire phar was compressed with gz/bzip2 */
247 	myphar->flags = compression;
248 
249 	entry.is_tar = 1;
250 	entry.is_crc_checked = 1;
251 	entry.phar = myphar;
252 	pos += sizeof(buf);
253 
254 	do {
255 		phar_entry_info *newentry;
256 
257 		pos = php_stream_tell(fp);
258 		hdr = (tar_header*) buf;
259 		sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum));
260 		if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) {
261 			break;
262 		}
263 		memset(hdr->checksum, ' ', sizeof(hdr->checksum));
264 		sum2 = phar_tar_checksum(buf, old?sizeof(old_tar_header):sizeof(tar_header));
265 
266 		if (old && sum2 != sum1) {
267 			uint32_t sum3 = phar_tar_checksum(buf, sizeof(tar_header));
268 			if (sum3 == sum1) {
269 				/* apparently a broken tar which is in ustar format w/o setting the ustar marker */
270 				sum2 = sum3;
271 				old = 0;
272 			}
273 		}
274 
275 		size = entry.uncompressed_filesize = entry.compressed_filesize =
276 			phar_tar_number(hdr->size, sizeof(hdr->size));
277 
278 		/* skip global/file headers (pax) */
279 		if (!old && (hdr->typeflag == TAR_GLOBAL_HDR || hdr->typeflag == TAR_FILE_HDR)) {
280 			size = (size+511)&~511;
281 			goto next;
282 		}
283 
284 		if (((!old && hdr->prefix[0] == 0) || old) && zend_strnlen(hdr->name, 100) == sizeof(".phar/signature.bin")-1 && !strncmp(hdr->name, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) {
285 			zend_off_t curloc;
286 			size_t sig_len;
287 
288 			if (size > 511) {
289 				if (error) {
290 					spprintf(error, 4096, "phar error: tar-based phar \"%s\" has signature that is larger than 511 bytes, cannot process", fname);
291 				}
292 bail:
293 				php_stream_close(fp);
294 				phar_destroy_phar_data(myphar);
295 				return FAILURE;
296 			}
297 			curloc = php_stream_tell(fp);
298 			read = php_stream_read(fp, buf, size);
299 			if (read != size || read <= 8) {
300 				if (error) {
301 					spprintf(error, 4096, "phar error: tar-based phar \"%s\" signature cannot be read", fname);
302 				}
303 				goto bail;
304 			}
305 #ifdef WORDS_BIGENDIAN
306 # define PHAR_GET_32(buffer) \
307 	(((((unsigned char*)(buffer))[3]) << 24) \
308 		| ((((unsigned char*)(buffer))[2]) << 16) \
309 		| ((((unsigned char*)(buffer))[1]) <<  8) \
310 		| (((unsigned char*)(buffer))[0]))
311 #else
312 # define PHAR_GET_32(buffer) (uint32_t) *(buffer)
313 #endif
314 			myphar->sig_flags = PHAR_GET_32(buf);
315 			if (FAILURE == phar_verify_signature(fp, php_stream_tell(fp) - size - 512, myphar->sig_flags, buf + 8, size - 8, fname, &myphar->signature, &sig_len, error)) {
316 				if (error) {
317 					char *save = *error;
318 					spprintf(error, 4096, "phar error: tar-based phar \"%s\" signature cannot be verified: %s", fname, save);
319 					efree(save);
320 				}
321 				goto bail;
322 			}
323 			myphar->sig_len = sig_len;
324 			php_stream_seek(fp, curloc + 512, SEEK_SET);
325 			/* signature checked out, let's ensure this is the last file in the phar */
326 			if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) {
327 				/* this is not good enough - seek succeeds even on truncated tars */
328 				php_stream_seek(fp, 512, SEEK_CUR);
329 				if ((uint32_t)php_stream_tell(fp) > totalsize) {
330 					if (error) {
331 						spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
332 					}
333 					php_stream_close(fp);
334 					phar_destroy_phar_data(myphar);
335 					return FAILURE;
336 				}
337 			}
338 
339 			read = php_stream_read(fp, buf, sizeof(buf));
340 
341 			if (read != sizeof(buf)) {
342 				if (error) {
343 					spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
344 				}
345 				php_stream_close(fp);
346 				phar_destroy_phar_data(myphar);
347 				return FAILURE;
348 			}
349 
350 			hdr = (tar_header*) buf;
351 			sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum));
352 
353 			if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) {
354 				break;
355 			}
356 
357 			if (error) {
358 				spprintf(error, 4096, "phar error: \"%s\" has entries after signature, invalid phar", fname);
359 			}
360 
361 			goto bail;
362 		}
363 
364 		if (!last_was_longlink && hdr->typeflag == 'L') {
365 			last_was_longlink = 1;
366 			/* support the ././@LongLink system for storing long filenames */
367 			entry.filename_len = entry.uncompressed_filesize;
368 
369 			/* Check for overflow - bug 61065 */
370 			if (entry.filename_len == UINT_MAX || entry.filename_len == 0) {
371 				if (error) {
372 					spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (invalid entry size)", fname);
373 				}
374 				php_stream_close(fp);
375 				phar_destroy_phar_data(myphar);
376 				return FAILURE;
377 			}
378 			entry.filename = pemalloc(entry.filename_len+1, myphar->is_persistent);
379 
380 			read = php_stream_read(fp, entry.filename, entry.filename_len);
381 			if (read != entry.filename_len) {
382 				efree(entry.filename);
383 				if (error) {
384 					spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
385 				}
386 				php_stream_close(fp);
387 				phar_destroy_phar_data(myphar);
388 				return FAILURE;
389 			}
390 			entry.filename[entry.filename_len] = '\0';
391 
392 			/* skip blank stuff */
393 			size = ((size+511)&~511) - size;
394 
395 			/* this is not good enough - seek succeeds even on truncated tars */
396 			php_stream_seek(fp, size, SEEK_CUR);
397 			if ((uint32_t)php_stream_tell(fp) > totalsize) {
398 				efree(entry.filename);
399 				if (error) {
400 					spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
401 				}
402 				php_stream_close(fp);
403 				phar_destroy_phar_data(myphar);
404 				return FAILURE;
405 			}
406 
407 			read = php_stream_read(fp, buf, sizeof(buf));
408 
409 			if (read != sizeof(buf)) {
410 				efree(entry.filename);
411 				if (error) {
412 					spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
413 				}
414 				php_stream_close(fp);
415 				phar_destroy_phar_data(myphar);
416 				return FAILURE;
417 			}
418 			continue;
419 		} else if (!last_was_longlink && !old && hdr->prefix[0] != 0) {
420 			char name[256];
421 			int i, j;
422 
423 			for (i = 0; i < 155; i++) {
424 				name[i] = hdr->prefix[i];
425 				if (name[i] == '\0') {
426 					break;
427 				}
428 			}
429 			name[i++] = '/';
430 			for (j = 0; j < 100; j++) {
431 				name[i+j] = hdr->name[j];
432 				if (name[i+j] == '\0') {
433 					break;
434 				}
435 			}
436 
437 			entry.filename_len = i+j;
438 
439 			if (name[entry.filename_len - 1] == '/') {
440 				/* some tar programs store directories with trailing slash */
441 				entry.filename_len--;
442 			}
443 			entry.filename = pestrndup(name, entry.filename_len, myphar->is_persistent);
444 		} else if (!last_was_longlink) {
445 			int i;
446 
447 			/* calculate strlen, which can be no longer than 100 */
448 			for (i = 0; i < 100; i++) {
449 				if (hdr->name[i] == '\0') {
450 					break;
451 				}
452 			}
453 			entry.filename_len = i;
454 			entry.filename = pestrndup(hdr->name, i, myphar->is_persistent);
455 
456 			if (i > 0 && entry.filename[entry.filename_len - 1] == '/') {
457 				/* some tar programs store directories with trailing slash */
458 				entry.filename[entry.filename_len - 1] = '\0';
459 				entry.filename_len--;
460 			}
461 		}
462 		last_was_longlink = 0;
463 
464 		phar_add_virtual_dirs(myphar, entry.filename, entry.filename_len);
465 
466 		if (sum1 != sum2) {
467 			if (error) {
468 				spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (checksum mismatch of file \"%s\")", fname, entry.filename);
469 			}
470 			pefree(entry.filename, myphar->is_persistent);
471 			php_stream_close(fp);
472 			phar_destroy_phar_data(myphar);
473 			return FAILURE;
474 		}
475 
476 		uint32_t entry_mode = phar_tar_number(hdr->mode, sizeof(hdr->mode));
477 		entry.tar_type = ((old & (hdr->typeflag == '\0')) ? TAR_FILE : hdr->typeflag);
478 		entry.offset = entry.offset_abs = pos; /* header_offset unused in tar */
479 		entry.fp_type = PHAR_FP;
480 		entry.flags = entry_mode & PHAR_ENT_PERM_MASK;
481 		entry.timestamp = phar_tar_number(hdr->mtime, sizeof(hdr->mtime));
482 		entry.is_persistent = myphar->is_persistent;
483 
484 		if (old && entry.tar_type == TAR_FILE && S_ISDIR(entry_mode)) {
485 			entry.tar_type = TAR_DIR;
486 		}
487 
488 		if (entry.tar_type == TAR_DIR) {
489 			entry.is_dir = 1;
490 		} else {
491 			entry.is_dir = 0;
492 		}
493 
494 		entry.link = NULL;
495 		/* link field is null-terminated unless it has 100 non-null chars.
496 		 * Thus we cannot use strlen. */
497 		linkname_len = zend_strnlen(hdr->linkname, 100);
498 		if (entry.tar_type == TAR_LINK) {
499 			if (!zend_hash_str_exists(&myphar->manifest, hdr->linkname, linkname_len)) {
500 				if (error) {
501 					spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file - hard link to non-existent file \"%.*s\"", fname, (int)linkname_len, hdr->linkname);
502 				}
503 				pefree(entry.filename, entry.is_persistent);
504 				php_stream_close(fp);
505 				phar_destroy_phar_data(myphar);
506 				return FAILURE;
507 			}
508 			entry.link = estrndup(hdr->linkname, linkname_len);
509 		} else if (entry.tar_type == TAR_SYMLINK) {
510 			entry.link = estrndup(hdr->linkname, linkname_len);
511 		}
512 		phar_set_inode(&entry);
513 
514 		newentry = zend_hash_str_update_mem(&myphar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info));
515 		ZEND_ASSERT(newentry != NULL);
516 
517 		if (entry.is_persistent) {
518 			++entry.manifest_pos;
519 		}
520 
521 		if (entry.filename_len >= sizeof(".phar/.metadata")-1 && !memcmp(entry.filename, ".phar/.metadata", sizeof(".phar/.metadata")-1)) {
522 			if (FAILURE == phar_tar_process_metadata(newentry, fp)) {
523 				if (error) {
524 					spprintf(error, 4096, "phar error: tar-based phar \"%s\" has invalid metadata in magic file \"%s\"", fname, entry.filename);
525 				}
526 				php_stream_close(fp);
527 				phar_destroy_phar_data(myphar);
528 				return FAILURE;
529 			}
530 		}
531 
532 		if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
533 			/* found explicit alias */
534 			if (size > 511) {
535 				if (error) {
536 					spprintf(error, 4096, "phar error: tar-based phar \"%s\" has alias that is larger than 511 bytes, cannot process", fname);
537 				}
538 				php_stream_close(fp);
539 				phar_destroy_phar_data(myphar);
540 				return FAILURE;
541 			}
542 
543 			read = php_stream_read(fp, buf, size);
544 
545 			if (read == size) {
546 				buf[size] = '\0';
547 				if (!phar_validate_alias(buf, size)) {
548 					if (size > 50) {
549 						buf[50] = '.';
550 						buf[51] = '.';
551 						buf[52] = '.';
552 						buf[53] = '\0';
553 					}
554 
555 					if (error) {
556 						spprintf(error, 4096, "phar error: invalid alias \"%s\" in tar-based phar \"%s\"", buf, fname);
557 					}
558 
559 					php_stream_close(fp);
560 					phar_destroy_phar_data(myphar);
561 					return FAILURE;
562 				}
563 
564 				actual_alias = pestrndup(buf, size, myphar->is_persistent);
565 				myphar->alias = actual_alias;
566 				myphar->alias_len = size;
567 				php_stream_seek(fp, pos, SEEK_SET);
568 			} else {
569 				if (error) {
570 					spprintf(error, 4096, "phar error: Unable to read alias from tar-based phar \"%s\"", fname);
571 				}
572 
573 				php_stream_close(fp);
574 				phar_destroy_phar_data(myphar);
575 				return FAILURE;
576 			}
577 		}
578 
579 		size = (size+511)&~511;
580 
581 		if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) {
582 next:
583 			/* this is not good enough - seek succeeds even on truncated tars */
584 			php_stream_seek(fp, size, SEEK_CUR);
585 			if ((uint32_t)php_stream_tell(fp) > totalsize) {
586 				if (error) {
587 					spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
588 				}
589 				php_stream_close(fp);
590 				phar_destroy_phar_data(myphar);
591 				return FAILURE;
592 			}
593 		}
594 
595 		read = php_stream_read(fp, buf, sizeof(buf));
596 
597 		if (read != sizeof(buf)) {
598 			if (error) {
599 				spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (truncated)", fname);
600 			}
601 			php_stream_close(fp);
602 			phar_destroy_phar_data(myphar);
603 			return FAILURE;
604 		}
605 	} while (!php_stream_eof(fp));
606 
607 	if (zend_hash_str_exists(&(myphar->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
608 		myphar->is_data = 0;
609 	} else {
610 		myphar->is_data = 1;
611 	}
612 
613 	/* ensure signature set */
614 	if (!myphar->is_data && PHAR_G(require_hash) && !myphar->signature) {
615 		php_stream_close(fp);
616 		phar_destroy_phar_data(myphar);
617 		if (error) {
618 			spprintf(error, 0, "tar-based phar \"%s\" does not have a signature", fname);
619 		}
620 		return FAILURE;
621 	}
622 
623 	myphar->fname = pestrndup(fname, fname_len, myphar->is_persistent);
624 #ifdef PHP_WIN32
625 	phar_unixify_path_separators(myphar->fname, fname_len);
626 #endif
627 	myphar->fname_len = fname_len;
628 	myphar->fp = fp;
629 	p = strrchr(myphar->fname, '/');
630 
631 	if (p) {
632 		myphar->ext = memchr(p, '.', (myphar->fname + fname_len) - p);
633 		if (myphar->ext == p) {
634 			myphar->ext = memchr(p + 1, '.', (myphar->fname + fname_len) - p - 1);
635 		}
636 		if (myphar->ext) {
637 			myphar->ext_len = (myphar->fname + fname_len) - myphar->ext;
638 		}
639 	}
640 
641 	phar_request_initialize();
642 
643 	if (NULL == (actual = zend_hash_str_add_ptr(&(PHAR_G(phar_fname_map)), myphar->fname, fname_len, myphar))) {
644 		if (error) {
645 			spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\" to phar registry", fname);
646 		}
647 		php_stream_close(fp);
648 		phar_destroy_phar_data(myphar);
649 		return FAILURE;
650 	}
651 
652 	myphar = actual;
653 
654 	if (actual_alias) {
655 		phar_archive_data *fd_ptr;
656 
657 		myphar->is_temporary_alias = 0;
658 
659 		if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), actual_alias, myphar->alias_len))) {
660 			if (SUCCESS != phar_free_alias(fd_ptr, actual_alias, myphar->alias_len)) {
661 				if (error) {
662 					spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\", alias is already in use", fname);
663 				}
664 				zend_hash_str_del(&(PHAR_G(phar_fname_map)), myphar->fname, fname_len);
665 				return FAILURE;
666 			}
667 		}
668 
669 		zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), actual_alias, myphar->alias_len, myphar);
670 	} else {
671 		phar_archive_data *fd_ptr;
672 
673 		if (alias_len) {
674 			if (NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) {
675 				if (SUCCESS != phar_free_alias(fd_ptr, alias, alias_len)) {
676 					if (error) {
677 						spprintf(error, 4096, "phar error: Unable to add tar-based phar \"%s\", alias is already in use", fname);
678 					}
679 					zend_hash_str_del(&(PHAR_G(phar_fname_map)), myphar->fname, fname_len);
680 					return FAILURE;
681 				}
682 			}
683 			zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len, myphar);
684 			myphar->alias = pestrndup(alias, alias_len, myphar->is_persistent);
685 			myphar->alias_len = alias_len;
686 		} else {
687 			myphar->alias = pestrndup(myphar->fname, fname_len, myphar->is_persistent);
688 			myphar->alias_len = fname_len;
689 		}
690 
691 		myphar->is_temporary_alias = 1;
692 	}
693 
694 	if (pphar) {
695 		*pphar = myphar;
696 	}
697 
698 	return SUCCESS;
699 }
700 /* }}} */
701 
702 struct _phar_pass_tar_info {
703 	php_stream *old;
704 	php_stream *new;
705 	bool free_fp;
706 	bool free_ufp;
707 	char **error;
708 };
709 
phar_tar_writeheaders_int(phar_entry_info * entry,void * argument)710 static int phar_tar_writeheaders_int(phar_entry_info *entry, void *argument) /* {{{ */
711 {
712 	tar_header header;
713 	size_t pos;
714 	struct _phar_pass_tar_info *fp = (struct _phar_pass_tar_info *)argument;
715 	char padding[512];
716 
717 	if (entry->is_mounted) {
718 		return ZEND_HASH_APPLY_KEEP;
719 	}
720 
721 	if (entry->is_deleted) {
722 		if (entry->fp_refcount <= 0) {
723 			return ZEND_HASH_APPLY_REMOVE;
724 		} else {
725 			/* we can't delete this in-memory until it is closed */
726 			return ZEND_HASH_APPLY_KEEP;
727 		}
728 	}
729 
730 	phar_add_virtual_dirs(entry->phar, entry->filename, entry->filename_len);
731 	memset((char *) &header, 0, sizeof(header));
732 
733 	if (entry->filename_len > 100) {
734 		char *boundary;
735 		if (entry->filename_len > 256) {
736 			if (fp->error) {
737 				spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, filename \"%s\" is too long for tar file format", entry->phar->fname, entry->filename);
738 			}
739 			return ZEND_HASH_APPLY_STOP;
740 		}
741 		boundary = entry->filename + entry->filename_len - 101;
742 		while (*boundary && *boundary != '/') {
743 			++boundary;
744 		}
745 		if (!*boundary || ((boundary - entry->filename) > 155)) {
746 			if (fp->error) {
747 				spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, filename \"%s\" is too long for tar file format", entry->phar->fname, entry->filename);
748 			}
749 			return ZEND_HASH_APPLY_STOP;
750 		}
751 		memcpy(header.prefix, entry->filename, boundary - entry->filename);
752 		memcpy(header.name, boundary + 1, entry->filename_len - (boundary + 1 - entry->filename));
753 	} else {
754 		memcpy(header.name, entry->filename, entry->filename_len);
755 	}
756 
757 	phar_tar_octal(header.mode, entry->flags & PHAR_ENT_PERM_MASK, sizeof(header.mode)-1);
758 
759 	if (FAILURE == phar_tar_octal(header.size, entry->uncompressed_filesize, sizeof(header.size)-1)) {
760 		if (fp->error) {
761 			spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, filename \"%s\" is too large for tar file format", entry->phar->fname, entry->filename);
762 		}
763 		return ZEND_HASH_APPLY_STOP;
764 	}
765 
766 	if (FAILURE == phar_tar_octal(header.mtime, entry->timestamp, sizeof(header.mtime)-1)) {
767 		if (fp->error) {
768 			spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, file modification time of file \"%s\" is too large for tar file format", entry->phar->fname, entry->filename);
769 		}
770 		return ZEND_HASH_APPLY_STOP;
771 	}
772 
773 	/* calc checksum */
774 	header.typeflag = entry->tar_type;
775 
776 	if (entry->link) {
777 		if (strlcpy(header.linkname, entry->link, sizeof(header.linkname)) >= sizeof(header.linkname)) {
778 			if (fp->error) {
779 				spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, link \"%s\" is too long for format", entry->phar->fname, entry->link);
780 			}
781 			return ZEND_HASH_APPLY_STOP;
782 		}
783 	}
784 
785 	memcpy(header.magic, "ustar", sizeof("ustar")-1);
786 	memcpy(header.version, "00", sizeof("00")-1);
787 	memcpy(header.checksum, "        ", sizeof("        ")-1);
788 	entry->crc32 = phar_tar_checksum((char *)&header, sizeof(header));
789 
790 	if (FAILURE == phar_tar_octal(header.checksum, entry->crc32, sizeof(header.checksum)-1)) {
791 		if (fp->error) {
792 			spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, checksum of file \"%s\" is too large for tar file format", entry->phar->fname, entry->filename);
793 		}
794 		return ZEND_HASH_APPLY_STOP;
795 	}
796 
797 	/* write header */
798 	entry->header_offset = php_stream_tell(fp->new);
799 
800 	if (sizeof(header) != php_stream_write(fp->new, (char *) &header, sizeof(header))) {
801 		if (fp->error) {
802 			spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, header for  file \"%s\" could not be written", entry->phar->fname, entry->filename);
803 		}
804 		return ZEND_HASH_APPLY_STOP;
805 	}
806 
807 	pos = php_stream_tell(fp->new); /* save start of file within tar */
808 
809 	/* write contents */
810 	if (entry->uncompressed_filesize) {
811 		if (FAILURE == phar_open_entry_fp(entry, fp->error, 0)) {
812 			return ZEND_HASH_APPLY_STOP;
813 		}
814 
815 		if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0)) {
816 			if (fp->error) {
817 				spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, contents of file \"%s\" could not be written, seek failed", entry->phar->fname, entry->filename);
818 			}
819 			return ZEND_HASH_APPLY_STOP;
820 		}
821 
822 		if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(entry, 0), fp->new, entry->uncompressed_filesize, NULL)) {
823 			if (fp->error) {
824 				spprintf(fp->error, 4096, "tar-based phar \"%s\" cannot be created, contents of file \"%s\" could not be written", entry->phar->fname, entry->filename);
825 			}
826 			return ZEND_HASH_APPLY_STOP;
827 		}
828 
829 		memset(padding, 0, 512);
830 		php_stream_write(fp->new, padding, ((entry->uncompressed_filesize +511)&~511) - entry->uncompressed_filesize);
831 	}
832 
833 	if (!entry->is_modified && entry->fp_refcount) {
834 		/* open file pointers refer to this fp, do not free the stream */
835 		switch (entry->fp_type) {
836 			case PHAR_FP:
837 				fp->free_fp = 0;
838 				break;
839 			case PHAR_UFP:
840 				fp->free_ufp = 0;
841 			default:
842 				break;
843 		}
844 	}
845 
846 	entry->is_modified = 0;
847 
848 	if (entry->fp_type == PHAR_MOD && entry->fp != entry->phar->fp && entry->fp != entry->phar->ufp) {
849 		if (!entry->fp_refcount) {
850 			php_stream_close(entry->fp);
851 		}
852 		entry->fp = NULL;
853 	}
854 
855 	entry->fp_type = PHAR_FP;
856 
857 	/* note new location within tar */
858 	entry->offset = entry->offset_abs = pos;
859 	return ZEND_HASH_APPLY_KEEP;
860 }
861 /* }}} */
862 
phar_tar_writeheaders(zval * zv,void * argument)863 static int phar_tar_writeheaders(zval *zv, void *argument) /* {{{ */
864 {
865 	return phar_tar_writeheaders_int(Z_PTR_P(zv), argument);
866 }
867 /* }}} */
868 
phar_tar_setmetadata(const phar_metadata_tracker * tracker,phar_entry_info * entry,char ** error)869 static int phar_tar_setmetadata(const phar_metadata_tracker *tracker, phar_entry_info *entry, char **error) /* {{{ */
870 {
871 	/* Copy the metadata from tracker to the new entry being written out to temporary files */
872 	const zend_string *serialized_str;
873 	phar_metadata_tracker_copy(&entry->metadata_tracker, tracker, entry->is_persistent);
874 	phar_metadata_tracker_try_ensure_has_serialized_data(&entry->metadata_tracker, entry->is_persistent);
875 	serialized_str = entry->metadata_tracker.str;
876 
877 	/* If there is no data, this will replace the metadata file (e.g. .phar/.metadata.bin) with an empty file */
878 	entry->uncompressed_filesize = entry->compressed_filesize = serialized_str ? ZSTR_LEN(serialized_str) : 0;
879 
880 	if (entry->fp && entry->fp_type == PHAR_MOD) {
881 		php_stream_close(entry->fp);
882 	}
883 
884 	entry->fp_type = PHAR_MOD;
885 	entry->is_modified = 1;
886 	entry->fp = php_stream_fopen_tmpfile();
887 	entry->offset = entry->offset_abs = 0;
888 	if (entry->fp == NULL) {
889 		spprintf(error, 0, "phar error: unable to create temporary file");
890 		return -1;
891 	}
892 	if (serialized_str && ZSTR_LEN(serialized_str) != php_stream_write(entry->fp, ZSTR_VAL(serialized_str), ZSTR_LEN(serialized_str))) {
893 		spprintf(error, 0, "phar tar error: unable to write metadata to magic metadata file \"%s\"", entry->filename);
894 		zend_hash_str_del(&(entry->phar->manifest), entry->filename, entry->filename_len);
895 		return ZEND_HASH_APPLY_STOP;
896 	}
897 
898 	return ZEND_HASH_APPLY_KEEP;
899 }
900 /* }}} */
901 
phar_tar_setupmetadata(zval * zv,void * argument)902 static int phar_tar_setupmetadata(zval *zv, void *argument) /* {{{ */
903 {
904 	int lookfor_len;
905 	struct _phar_pass_tar_info *i = (struct _phar_pass_tar_info *)argument;
906 	char *lookfor, **error = i->error;
907 	phar_entry_info *entry = (phar_entry_info *)Z_PTR_P(zv), *metadata, newentry = {0};
908 
909 	if (entry->filename_len >= sizeof(".phar/.metadata") && !memcmp(entry->filename, ".phar/.metadata", sizeof(".phar/.metadata")-1)) {
910 		if (entry->filename_len == sizeof(".phar/.metadata.bin")-1 && !memcmp(entry->filename, ".phar/.metadata.bin", sizeof(".phar/.metadata.bin")-1)) {
911 			return phar_tar_setmetadata(&entry->phar->metadata_tracker, entry, error);
912 		}
913 		/* search for the file this metadata entry references */
914 		if (entry->filename_len >= sizeof(".phar/.metadata/") + sizeof("/.metadata.bin") - 1 && !zend_hash_str_exists(&(entry->phar->manifest), entry->filename + sizeof(".phar/.metadata/") - 1, entry->filename_len - (sizeof("/.metadata.bin") - 1 + sizeof(".phar/.metadata/") - 1))) {
915 			/* this is orphaned metadata, erase it */
916 			return ZEND_HASH_APPLY_REMOVE;
917 		}
918 		/* we can keep this entry, the file that refers to it exists */
919 		return ZEND_HASH_APPLY_KEEP;
920 	}
921 
922 	if (!entry->is_modified) {
923 		return ZEND_HASH_APPLY_KEEP;
924 	}
925 
926 	/* now we are dealing with regular files, so look for metadata */
927 	lookfor_len = spprintf(&lookfor, 0, ".phar/.metadata/%s/.metadata.bin", entry->filename);
928 
929 	if (!phar_metadata_tracker_has_data(&entry->metadata_tracker, entry->is_persistent)) {
930 		zend_hash_str_del(&(entry->phar->manifest), lookfor, lookfor_len);
931 		efree(lookfor);
932 		return ZEND_HASH_APPLY_KEEP;
933 	}
934 
935 	if (NULL != (metadata = zend_hash_str_find_ptr(&(entry->phar->manifest), lookfor, lookfor_len))) {
936 		int ret;
937 		ret = phar_tar_setmetadata(&entry->metadata_tracker, metadata, error);
938 		efree(lookfor);
939 		return ret;
940 	}
941 
942 	newentry.filename = lookfor;
943 	newentry.filename_len = lookfor_len;
944 	newentry.phar = entry->phar;
945 	newentry.tar_type = TAR_FILE;
946 	newentry.is_tar = 1;
947 
948 	if (NULL == (metadata = zend_hash_str_add_mem(&(entry->phar->manifest), lookfor, lookfor_len, (void *)&newentry, sizeof(phar_entry_info)))) {
949 		efree(lookfor);
950 		spprintf(error, 0, "phar tar error: unable to add magic metadata file to manifest for file \"%s\"", entry->filename);
951 		return ZEND_HASH_APPLY_STOP;
952 	}
953 
954 	return phar_tar_setmetadata(&entry->metadata_tracker, metadata, error);
955 }
956 /* }}} */
957 
phar_tar_flush(phar_archive_data * phar,zend_string * user_stub,bool is_default_stub,char ** error)958 void phar_tar_flush(phar_archive_data *phar, zend_string *user_stub, bool is_default_stub, char **error) /* {{{ */
959 {
960 	static const char newstub[] = "<?php // tar-based phar archive stub file\n__HALT_COMPILER();";
961 	static const char halt_stub[] = "__HALT_COMPILER();";
962 
963 	phar_entry_info entry = {0};
964 	php_stream *oldfile, *newfile;
965 	bool must_close_old_file = false;
966 	size_t signature_length;
967 	struct _phar_pass_tar_info pass;
968 	char *buf, *signature, sigbuf[8];
969 
970 	entry.flags = PHAR_ENT_PERM_DEF_FILE;
971 	entry.timestamp = time(NULL);
972 	entry.is_modified = 1;
973 	entry.is_crc_checked = 1;
974 	entry.is_tar = 1;
975 	entry.tar_type = '0';
976 	entry.phar = phar;
977 	entry.fp_type = PHAR_MOD;
978 	entry.fp = NULL;
979 	entry.filename = NULL;
980 
981 	if (phar->is_persistent) {
982 		if (error) {
983 			spprintf(error, 0, "internal error: attempt to flush cached tar-based phar \"%s\"", phar->fname);
984 		}
985 		return;
986 	}
987 
988 	if (phar->is_data) {
989 		goto nostub;
990 	}
991 
992 	/* set alias */
993 	if (!phar->is_temporary_alias && phar->alias_len) {
994 		entry.filename = estrndup(".phar/alias.txt", sizeof(".phar/alias.txt")-1);
995 		entry.filename_len = sizeof(".phar/alias.txt")-1;
996 		entry.fp = php_stream_fopen_tmpfile();
997 		if (entry.fp == NULL) {
998 			efree(entry.filename);
999 			spprintf(error, 0, "phar error: unable to create temporary file");
1000 			return;
1001 		}
1002 		if (phar->alias_len != php_stream_write(entry.fp, phar->alias, phar->alias_len)) {
1003 			if (error) {
1004 				spprintf(error, 0, "unable to set alias in tar-based phar \"%s\"", phar->fname);
1005 			}
1006 			php_stream_close(entry.fp);
1007 			efree(entry.filename);
1008 			return;
1009 		}
1010 
1011 		entry.uncompressed_filesize = phar->alias_len;
1012 
1013 		zend_hash_str_update_mem(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info));
1014 		/* At this point the entry is saved into the manifest. The manifest destroy
1015 			routine will care about any resources to be freed. */
1016 	} else {
1017 		zend_hash_str_del(&phar->manifest, ".phar/alias.txt", sizeof(".phar/alias.txt")-1);
1018 	}
1019 
1020 	/* set stub */
1021 	if (user_stub && !is_default_stub) {
1022 		char *pos = php_stristr(ZSTR_VAL(user_stub), halt_stub, ZSTR_LEN(user_stub), sizeof(halt_stub) - 1);
1023 
1024 		if (pos == NULL) {
1025 			if (error) {
1026 				spprintf(error, 0, "illegal stub for tar-based phar \"%s\"", phar->fname);
1027 			}
1028 			return;
1029 		}
1030 
1031 		size_t len = pos - ZSTR_VAL(user_stub) + strlen(halt_stub);
1032 		const char end_sequence[] = " ?>\r\n";
1033 		size_t end_sequence_len = strlen(end_sequence);
1034 
1035 		entry.fp = php_stream_fopen_tmpfile();
1036 		if (entry.fp == NULL) {
1037 			spprintf(error, 0, "phar error: unable to create temporary file");
1038 			return;
1039 		}
1040 		entry.uncompressed_filesize = len + end_sequence_len;
1041 
1042 		if (
1043 			len != php_stream_write(entry.fp, ZSTR_VAL(user_stub), len)
1044 			|| end_sequence_len != php_stream_write(entry.fp, end_sequence, end_sequence_len)
1045 		) {
1046 			if (error) {
1047 				spprintf(error, 0, "unable to create stub from string in new tar-based phar \"%s\"", phar->fname);
1048 			}
1049 			php_stream_close(entry.fp);
1050 			return;
1051 		}
1052 
1053 		entry.filename = estrndup(".phar/stub.php", sizeof(".phar/stub.php")-1);
1054 		entry.filename_len = sizeof(".phar/stub.php")-1;
1055 		zend_hash_str_update_mem(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info));
1056 	} else {
1057 		/* Either this is a brand new phar (add the stub), or the default stub is required (overwrite the stub) */
1058 		entry.fp = php_stream_fopen_tmpfile();
1059 		if (entry.fp == NULL) {
1060 			spprintf(error, 0, "phar error: unable to create temporary file");
1061 			return;
1062 		}
1063 		if (sizeof(newstub)-1 != php_stream_write(entry.fp, newstub, sizeof(newstub)-1)) {
1064 			php_stream_close(entry.fp);
1065 			if (error) {
1066 				spprintf(error, 0, "unable to %s stub in%star-based phar \"%s\", failed", user_stub ? "overwrite" : "create", user_stub ? " " : " new ", phar->fname);
1067 			}
1068 			return;
1069 		}
1070 
1071 		entry.uncompressed_filesize = entry.compressed_filesize = sizeof(newstub) - 1;
1072 		entry.filename = estrndup(".phar/stub.php", sizeof(".phar/stub.php")-1);
1073 		entry.filename_len = sizeof(".phar/stub.php")-1;
1074 
1075 		if (!is_default_stub) {
1076 			if (!zend_hash_str_exists(&phar->manifest, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
1077 				if (NULL == zend_hash_str_add_mem(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info))) {
1078 					php_stream_close(entry.fp);
1079 					efree(entry.filename);
1080 					if (error) {
1081 						spprintf(error, 0, "unable to create stub in tar-based phar \"%s\"", phar->fname);
1082 					}
1083 					return;
1084 				}
1085 			} else {
1086 				php_stream_close(entry.fp);
1087 				efree(entry.filename);
1088 			}
1089 		} else {
1090 			zend_hash_str_update_mem(&phar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info));
1091 		}
1092 	}
1093 nostub:
1094 	if (phar->fp && !phar->is_brandnew) {
1095 		oldfile = phar->fp;
1096 		must_close_old_file = false;
1097 		php_stream_rewind(oldfile);
1098 	} else {
1099 		oldfile = php_stream_open_wrapper(phar->fname, "rb", 0, NULL);
1100 		must_close_old_file = oldfile != NULL;
1101 	}
1102 
1103 	newfile = php_stream_fopen_tmpfile();
1104 	if (!newfile) {
1105 		if (error) {
1106 			spprintf(error, 0, "unable to create temporary file");
1107 		}
1108 		if (must_close_old_file) {
1109 			php_stream_close(oldfile);
1110 		}
1111 		return;
1112 	}
1113 
1114 	pass.old = oldfile;
1115 	pass.new = newfile;
1116 	pass.error = error;
1117 	pass.free_fp = 1;
1118 	pass.free_ufp = 1;
1119 
1120 	if (phar_metadata_tracker_has_data(&phar->metadata_tracker, phar->is_persistent)) {
1121 		phar_entry_info *mentry;
1122 		if (NULL != (mentry = zend_hash_str_find_ptr(&(phar->manifest), ".phar/.metadata.bin", sizeof(".phar/.metadata.bin")-1))) {
1123 			if (ZEND_HASH_APPLY_KEEP != phar_tar_setmetadata(&phar->metadata_tracker, mentry, error)) {
1124 				if (must_close_old_file) {
1125 					php_stream_close(oldfile);
1126 				}
1127 				return;
1128 			}
1129 		} else {
1130 			phar_entry_info newentry = {0};
1131 
1132 			newentry.filename = estrndup(".phar/.metadata.bin", sizeof(".phar/.metadata.bin")-1);
1133 			newentry.filename_len = sizeof(".phar/.metadata.bin")-1;
1134 			newentry.phar = phar;
1135 			newentry.tar_type = TAR_FILE;
1136 			newentry.is_tar = 1;
1137 
1138 			if (NULL == (mentry = zend_hash_str_add_mem(&(phar->manifest), ".phar/.metadata.bin", sizeof(".phar/.metadata.bin")-1, (void *)&newentry, sizeof(phar_entry_info)))) {
1139 				spprintf(error, 0, "phar tar error: unable to add magic metadata file to manifest for phar archive \"%s\"", phar->fname);
1140 				if (must_close_old_file) {
1141 					php_stream_close(oldfile);
1142 				}
1143 				return;
1144 			}
1145 
1146 			if (ZEND_HASH_APPLY_KEEP != phar_tar_setmetadata(&phar->metadata_tracker, mentry, error)) {
1147 				zend_hash_str_del(&(phar->manifest), ".phar/.metadata.bin", sizeof(".phar/.metadata.bin")-1);
1148 				if (must_close_old_file) {
1149 					php_stream_close(oldfile);
1150 				}
1151 				return;
1152 			}
1153 		}
1154 	}
1155 
1156 	zend_hash_apply_with_argument(&phar->manifest, phar_tar_setupmetadata, (void *) &pass);
1157 
1158 	if (error && *error) {
1159 		if (must_close_old_file) {
1160 			php_stream_close(oldfile);
1161 		}
1162 
1163 		/* on error in the hash iterator above, error is set */
1164 		php_stream_close(newfile);
1165 		return;
1166 	}
1167 
1168 	zend_hash_apply_with_argument(&phar->manifest, phar_tar_writeheaders, (void *) &pass);
1169 
1170 	/* add signature for executable tars or tars explicitly set with setSignatureAlgorithm */
1171 	if (!phar->is_data || phar->sig_flags) {
1172 		if (FAILURE == phar_create_signature(phar, newfile, &signature, &signature_length, error)) {
1173 			if (error) {
1174 				char *save = *error;
1175 				spprintf(error, 0, "phar error: unable to write signature to tar-based phar: %s", save);
1176 				efree(save);
1177 			}
1178 
1179 			if (must_close_old_file) {
1180 				php_stream_close(oldfile);
1181 			}
1182 
1183 			php_stream_close(newfile);
1184 			return;
1185 		}
1186 
1187 		entry.filename = ".phar/signature.bin";
1188 		entry.filename_len = sizeof(".phar/signature.bin")-1;
1189 		entry.fp = php_stream_fopen_tmpfile();
1190 		if (entry.fp == NULL) {
1191 			spprintf(error, 0, "phar error: unable to create temporary file");
1192 			return;
1193 		}
1194 #ifdef WORDS_BIGENDIAN
1195 # define PHAR_SET_32(destination, source) do { \
1196         uint32_t swapped = (((((unsigned char*)&(source))[3]) << 24) \
1197             | ((((unsigned char*)&(source))[2]) << 16) \
1198             | ((((unsigned char*)&(source))[1]) << 8) \
1199             | (((unsigned char*)&(source))[0])); \
1200         memcpy(destination, &swapped, 4); \
1201     } while (0);
1202 #else
1203 # define PHAR_SET_32(destination, source) memcpy(destination, &source, 4)
1204 #endif
1205 		PHAR_SET_32(sigbuf, phar->sig_flags);
1206 		PHAR_SET_32(sigbuf + 4, signature_length);
1207 
1208 		if (8 != php_stream_write(entry.fp, sigbuf, 8) || signature_length != php_stream_write(entry.fp, signature, signature_length)) {
1209 			efree(signature);
1210 			if (error) {
1211 				spprintf(error, 0, "phar error: unable to write signature to tar-based phar %s", phar->fname);
1212 			}
1213 
1214 			if (must_close_old_file) {
1215 				php_stream_close(oldfile);
1216 			}
1217 			php_stream_close(newfile);
1218 			return;
1219 		}
1220 
1221 		efree(signature);
1222 		entry.uncompressed_filesize = entry.compressed_filesize = signature_length + 8;
1223 		/* throw out return value and write the signature */
1224 		entry.filename_len = phar_tar_writeheaders_int(&entry, (void *)&pass);
1225 
1226 		if (error && *error) {
1227 			if (must_close_old_file) {
1228 				php_stream_close(oldfile);
1229 			}
1230 			/* error is set by writeheaders */
1231 			php_stream_close(newfile);
1232 			return;
1233 		}
1234 	} /* signature */
1235 
1236 	/* add final zero blocks */
1237 	buf = (char *) ecalloc(1024, 1);
1238 	php_stream_write(newfile, buf, 1024);
1239 	efree(buf);
1240 
1241 	if (must_close_old_file) {
1242 		php_stream_close(oldfile);
1243 	}
1244 
1245 	/* on error in the hash iterator above, error is set */
1246 	if (error && *error) {
1247 		php_stream_close(newfile);
1248 		return;
1249 	}
1250 
1251 	if (phar->fp && pass.free_fp) {
1252 		php_stream_close(phar->fp);
1253 	}
1254 
1255 	if (phar->ufp) {
1256 		if (pass.free_ufp) {
1257 			php_stream_close(phar->ufp);
1258 		}
1259 		phar->ufp = NULL;
1260 	}
1261 
1262 	phar->is_brandnew = 0;
1263 	php_stream_rewind(newfile);
1264 
1265 	if (phar->donotflush) {
1266 		/* deferred flush */
1267 		phar->fp = newfile;
1268 	} else {
1269 		phar->fp = php_stream_open_wrapper(phar->fname, "w+b", IGNORE_URL|STREAM_MUST_SEEK|REPORT_ERRORS, NULL);
1270 		if (!phar->fp) {
1271 			phar->fp = newfile;
1272 			if (error) {
1273 				spprintf(error, 0, "unable to open new phar \"%s\" for writing", phar->fname);
1274 			}
1275 			return;
1276 		}
1277 
1278 		if (phar->flags & PHAR_FILE_COMPRESSED_GZ) {
1279 			php_stream_filter *filter;
1280 			/* to properly compress, we have to tell zlib to add a zlib header */
1281 			zval filterparams;
1282 
1283 			array_init(&filterparams);
1284 /* this is defined in zlib's zconf.h */
1285 #ifndef MAX_WBITS
1286 #define MAX_WBITS 15
1287 #endif
1288 			add_assoc_long(&filterparams, "window", MAX_WBITS + 16);
1289 			filter = php_stream_filter_create("zlib.deflate", &filterparams, php_stream_is_persistent(phar->fp));
1290 			zend_array_destroy(Z_ARR(filterparams));
1291 
1292 			if (!filter) {
1293 				/* copy contents uncompressed rather than lose them */
1294 				php_stream_copy_to_stream_ex(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL);
1295 				php_stream_close(newfile);
1296 				if (error) {
1297 					spprintf(error, 4096, "unable to compress all contents of phar \"%s\" using zlib, PHP versions older than 5.2.6 have a buggy zlib", phar->fname);
1298 				}
1299 				return;
1300 			}
1301 
1302 			php_stream_filter_append(&phar->fp->writefilters, filter);
1303 			php_stream_copy_to_stream_ex(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL);
1304 			php_stream_filter_flush(filter, 1);
1305 			php_stream_filter_remove(filter, 1);
1306 			php_stream_close(phar->fp);
1307 			/* use the temp stream as our base */
1308 			phar->fp = newfile;
1309 		} else if (phar->flags & PHAR_FILE_COMPRESSED_BZ2) {
1310 			php_stream_filter *filter;
1311 
1312 			filter = php_stream_filter_create("bzip2.compress", NULL, php_stream_is_persistent(phar->fp));
1313 			php_stream_filter_append(&phar->fp->writefilters, filter);
1314 			php_stream_copy_to_stream_ex(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL);
1315 			php_stream_filter_flush(filter, 1);
1316 			php_stream_filter_remove(filter, 1);
1317 			php_stream_close(phar->fp);
1318 			/* use the temp stream as our base */
1319 			phar->fp = newfile;
1320 		} else {
1321 			php_stream_copy_to_stream_ex(newfile, phar->fp, PHP_STREAM_COPY_ALL, NULL);
1322 			/* we could also reopen the file in "rb" mode but there is no need for that */
1323 			php_stream_close(newfile);
1324 		}
1325 	}
1326 }
1327 /* }}} */
1328