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