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