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