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