xref: /php-src/ext/phar/phar_object.c (revision 03e2cfda)
1 /*
2   +----------------------------------------------------------------------+
3   | phar php single-file executable PHP extension                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) The PHP Group                                          |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | https://www.php.net/license/3_01.txt                                 |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Gregory Beaver <cellog@php.net>                             |
16   |          Marcus Boerger <helly@php.net>                              |
17   +----------------------------------------------------------------------+
18 */
19 
20 #include "phar_internal.h"
21 #include "func_interceptors.h"
22 #include "phar_object_arginfo.h"
23 #include "ext/spl/spl_array.h"
24 #include "ext/spl/spl_exceptions.h"
25 #include "ext/spl/spl_iterators.h"
26 #include "ext/standard/php_var.h"
27 #include "main/SAPI.h"
28 #include "zend_exceptions.h"
29 #include "zend_interfaces.h"
30 #include "zend_exceptions.h"
31 
32 static zend_class_entry *phar_ce_archive;
33 static zend_class_entry *phar_ce_data;
34 static zend_class_entry *phar_ce_PharException;
35 static zend_class_entry *phar_ce_entry;
36 
phar_file_type(HashTable * mimes,char * file,char ** mime_type)37 static int phar_file_type(HashTable *mimes, char *file, char **mime_type) /* {{{ */
38 {
39 	char *ext;
40 	phar_mime_type *mime;
41 	ext = strrchr(file, '.');
42 	if (!ext) {
43 		*mime_type = "text/plain";
44 		/* no file extension = assume text/plain */
45 		return PHAR_MIME_OTHER;
46 	}
47 	++ext;
48 	if (NULL == (mime = zend_hash_str_find_ptr(mimes, ext, strlen(ext)))) {
49 		*mime_type = "application/octet-stream";
50 		return PHAR_MIME_OTHER;
51 	}
52 	*mime_type = mime->mime;
53 	return mime->type;
54 }
55 /* }}} */
56 
phar_mung_server_vars(char * fname,char * entry,size_t entry_len,char * basename,size_t request_uri_len)57 static void phar_mung_server_vars(char *fname, char *entry, size_t entry_len, char *basename, size_t request_uri_len) /* {{{ */
58 {
59 	HashTable *_SERVER;
60 	zval *stuff;
61 	char *path_info;
62 	size_t basename_len = strlen(basename);
63 	size_t code;
64 	zval temp;
65 
66 	/* "tweak" $_SERVER variables requested in earlier call to Phar::mungServer() */
67 	if (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_UNDEF) {
68 		return;
69 	}
70 
71 	_SERVER = Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]);
72 
73 	/* PATH_INFO and PATH_TRANSLATED should always be munged */
74 	if (NULL != (stuff = zend_hash_str_find(_SERVER, "PATH_INFO", sizeof("PATH_INFO")-1))) {
75 		path_info = Z_STRVAL_P(stuff);
76 		code = Z_STRLEN_P(stuff);
77 		if (code > (size_t)entry_len && !memcmp(path_info, entry, entry_len)) {
78 			ZVAL_STR(&temp, Z_STR_P(stuff));
79 			ZVAL_STRINGL(stuff, path_info + entry_len, request_uri_len);
80 			zend_hash_str_update(_SERVER, "PHAR_PATH_INFO", sizeof("PHAR_PATH_INFO")-1, &temp);
81 		}
82 	}
83 
84 	if (NULL != (stuff = zend_hash_str_find(_SERVER, "PATH_TRANSLATED", sizeof("PATH_TRANSLATED")-1))) {
85 		zend_string *str = strpprintf(4096, "phar://%s%s", fname, entry);
86 
87 		ZVAL_STR(&temp, Z_STR_P(stuff));
88 		ZVAL_NEW_STR(stuff, str);
89 
90 		zend_hash_str_update(_SERVER, "PHAR_PATH_TRANSLATED", sizeof("PHAR_PATH_TRANSLATED")-1, &temp);
91 	}
92 
93 	if (!PHAR_G(phar_SERVER_mung_list)) {
94 		return;
95 	}
96 
97 	if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_REQUEST_URI) {
98 		if (NULL != (stuff = zend_hash_str_find(_SERVER, "REQUEST_URI", sizeof("REQUEST_URI")-1))) {
99 			path_info = Z_STRVAL_P(stuff);
100 			code = Z_STRLEN_P(stuff);
101 			if (code > basename_len && !memcmp(path_info, basename, basename_len)) {
102 				ZVAL_STR(&temp, Z_STR_P(stuff));
103 				ZVAL_STRINGL(stuff, path_info + basename_len, code - basename_len);
104 				zend_hash_str_update(_SERVER, "PHAR_REQUEST_URI", sizeof("PHAR_REQUEST_URI")-1, &temp);
105 			}
106 		}
107 	}
108 
109 	if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_PHP_SELF) {
110 		if (NULL != (stuff = zend_hash_str_find(_SERVER, "PHP_SELF", sizeof("PHP_SELF")-1))) {
111 			path_info = Z_STRVAL_P(stuff);
112 			code = Z_STRLEN_P(stuff);
113 
114 			if (code > basename_len && !memcmp(path_info, basename, basename_len)) {
115 				ZVAL_STR(&temp, Z_STR_P(stuff));
116 				ZVAL_STRINGL(stuff, path_info + basename_len, code - basename_len);
117 				zend_hash_str_update(_SERVER, "PHAR_PHP_SELF", sizeof("PHAR_PHP_SELF")-1, &temp);
118 			}
119 		}
120 	}
121 
122 	if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_SCRIPT_NAME) {
123 		if (NULL != (stuff = zend_hash_str_find(_SERVER, "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1))) {
124 			ZVAL_STR(&temp, Z_STR_P(stuff));
125 			ZVAL_STRINGL(stuff, entry, entry_len);
126 			zend_hash_str_update(_SERVER, "PHAR_SCRIPT_NAME", sizeof("PHAR_SCRIPT_NAME")-1, &temp);
127 		}
128 	}
129 
130 	if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_SCRIPT_FILENAME) {
131 		if (NULL != (stuff = zend_hash_str_find(_SERVER, "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1))) {
132 			zend_string *str = strpprintf(4096, "phar://%s%s", fname, entry);
133 
134 			ZVAL_STR(&temp, Z_STR_P(stuff));
135 			ZVAL_NEW_STR(stuff, str);
136 
137 			zend_hash_str_update(_SERVER, "PHAR_SCRIPT_FILENAME", sizeof("PHAR_SCRIPT_FILENAME")-1, &temp);
138 		}
139 	}
140 }
141 /* }}} */
142 
phar_file_action(phar_archive_data * phar,phar_entry_info * info,char * mime_type,int code,char * entry,size_t entry_len,char * arch,char * basename,char * ru,size_t ru_len)143 static int phar_file_action(phar_archive_data *phar, phar_entry_info *info, char *mime_type, int code, char *entry, size_t entry_len, char *arch, char *basename, char *ru, size_t ru_len) /* {{{ */
144 {
145 	char *name = NULL, buf[8192];
146 	const char *cwd;
147 	zend_syntax_highlighter_ini syntax_highlighter_ini;
148 	sapi_header_line ctr = {0};
149 	size_t got;
150 	zval dummy;
151 	size_t name_len;
152 	zend_file_handle file_handle;
153 	zend_op_array *new_op_array;
154 	zval result;
155 	php_stream *fp;
156 	zend_off_t position;
157 
158 	switch (code) {
159 		case PHAR_MIME_PHPS:
160 			efree(basename);
161 			/* highlight source */
162 			if (entry[0] == '/') {
163 				spprintf(&name, 4096, "phar://%s%s", arch, entry);
164 			} else {
165 				spprintf(&name, 4096, "phar://%s/%s", arch, entry);
166 			}
167 			php_get_highlight_struct(&syntax_highlighter_ini);
168 
169 			highlight_file(name, &syntax_highlighter_ini);
170 
171 			efree(name);
172 #ifdef PHP_WIN32
173 			efree(arch);
174 #endif
175 			zend_bailout();
176 		case PHAR_MIME_OTHER:
177 			/* send headers, output file contents */
178 			efree(basename);
179 			ctr.line_len = spprintf((char **) &(ctr.line), 0, "Content-type: %s", mime_type);
180 			sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
181 			efree((void *) ctr.line);
182 			ctr.line_len = spprintf((char **) &(ctr.line), 0, "Content-length: %u", info->uncompressed_filesize);
183 			sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
184 			efree((void *) ctr.line);
185 
186 			if (FAILURE == sapi_send_headers()) {
187 				zend_bailout();
188 			}
189 
190 			/* prepare to output  */
191 			fp = phar_get_efp(info, 1);
192 
193 			if (!fp) {
194 				char *error;
195 				if (!phar_open_jit(phar, info, &error)) {
196 					if (error) {
197 						zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
198 						efree(error);
199 					}
200 					return -1;
201 				}
202 				fp = phar_get_efp(info, 1);
203 			}
204 			position = 0;
205 			phar_seek_efp(info, 0, SEEK_SET, 0, 1);
206 
207 			do {
208 				got = php_stream_read(fp, buf, MIN(8192, info->uncompressed_filesize - position));
209 				if (got > 0) {
210 					PHPWRITE(buf, got);
211 					position += got;
212 					if (position == (zend_off_t) info->uncompressed_filesize) {
213 						break;
214 					}
215 				}
216 			} while (1);
217 
218 			zend_bailout();
219 		case PHAR_MIME_PHP:
220 			if (basename) {
221 				phar_mung_server_vars(arch, entry, entry_len, basename, ru_len);
222 				efree(basename);
223 			}
224 
225 			if (entry[0] == '/') {
226 				name_len = spprintf(&name, 4096, "phar://%s%s", arch, entry);
227 			} else {
228 				name_len = spprintf(&name, 4096, "phar://%s/%s", arch, entry);
229 			}
230 
231 			zend_stream_init_filename(&file_handle, name);
232 
233 			PHAR_G(cwd) = NULL;
234 			PHAR_G(cwd_len) = 0;
235 
236 			ZVAL_NULL(&dummy);
237 			if (zend_hash_str_add(&EG(included_files), name, name_len, &dummy) != NULL) {
238 				if ((cwd = zend_memrchr(entry, '/', entry_len))) {
239 					PHAR_G(cwd_init) = 1;
240 					if (entry == cwd) {
241 						/* root directory */
242 						PHAR_G(cwd_len) = 0;
243 						PHAR_G(cwd) = NULL;
244 					} else if (entry[0] == '/') {
245 						PHAR_G(cwd_len) = (cwd - (entry + 1));
246 						PHAR_G(cwd) = estrndup(entry + 1, PHAR_G(cwd_len));
247 					} else {
248 						PHAR_G(cwd_len) = (cwd - entry);
249 						PHAR_G(cwd) = estrndup(entry, PHAR_G(cwd_len));
250 					}
251 				}
252 
253 				new_op_array = zend_compile_file(&file_handle, ZEND_REQUIRE);
254 
255 				if (!new_op_array) {
256 					zend_hash_str_del(&EG(included_files), name, name_len);
257 				}
258 			} else {
259 				efree(name);
260 				new_op_array = NULL;
261 			}
262 
263 			zend_destroy_file_handle(&file_handle);
264 #ifdef PHP_WIN32
265 			efree(arch);
266 #endif
267 			if (new_op_array) {
268 				ZVAL_UNDEF(&result);
269 
270 				zend_try {
271 					zend_execute(new_op_array, &result);
272 					if (PHAR_G(cwd)) {
273 						efree(PHAR_G(cwd));
274 						PHAR_G(cwd) = NULL;
275 						PHAR_G(cwd_len) = 0;
276 					}
277 
278 					PHAR_G(cwd_init) = 0;
279 					efree(name);
280 					destroy_op_array(new_op_array);
281 					efree(new_op_array);
282 					zval_ptr_dtor(&result);
283 				} zend_catch {
284 					if (PHAR_G(cwd)) {
285 						efree(PHAR_G(cwd));
286 						PHAR_G(cwd) = NULL;
287 						PHAR_G(cwd_len) = 0;
288 					}
289 
290 					PHAR_G(cwd_init) = 0;
291 					efree(name);
292 				} zend_end_try();
293 
294 				zend_bailout();
295 			}
296 
297 			return PHAR_MIME_PHP;
298 	}
299 	return -1;
300 }
301 /* }}} */
302 
phar_do_403(char * entry,size_t entry_len)303 static void phar_do_403(char *entry, size_t entry_len) /* {{{ */
304 {
305 	sapi_header_line ctr = {0};
306 
307 	ctr.response_code = 403;
308 	ctr.line_len = sizeof("HTTP/1.0 403 Access Denied")-1;
309 	ctr.line = "HTTP/1.0 403 Access Denied";
310 	sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
311 	sapi_send_headers();
312 	PHPWRITE("<html>\n <head>\n  <title>Access Denied</title>\n </head>\n <body>\n  <h1>403 - File ", sizeof("<html>\n <head>\n  <title>Access Denied</title>\n </head>\n <body>\n  <h1>403 - File ") - 1);
313 	PHPWRITE("Access Denied</h1>\n </body>\n</html>", sizeof("Access Denied</h1>\n </body>\n</html>") - 1);
314 }
315 /* }}} */
316 
phar_do_404(phar_archive_data * phar,char * fname,size_t fname_len,char * f404,size_t f404_len,char * entry,size_t entry_len)317 static void phar_do_404(phar_archive_data *phar, char *fname, size_t fname_len, char *f404, size_t f404_len, char *entry, size_t entry_len) /* {{{ */
318 {
319 	sapi_header_line ctr = {0};
320 	phar_entry_info	*info;
321 
322 	if (phar && f404_len) {
323 		info = phar_get_entry_info(phar, f404, f404_len, NULL, 1);
324 
325 		if (info) {
326 			phar_file_action(phar, info, "text/html", PHAR_MIME_PHP, f404, f404_len, fname, NULL, NULL, 0);
327 			return;
328 		}
329 	}
330 
331 	ctr.response_code = 404;
332 	ctr.line_len = sizeof("HTTP/1.0 404 Not Found")-1;
333 	ctr.line = "HTTP/1.0 404 Not Found";
334 	sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
335 	sapi_send_headers();
336 	PHPWRITE("<html>\n <head>\n  <title>File Not Found</title>\n </head>\n <body>\n  <h1>404 - File ", sizeof("<html>\n <head>\n  <title>File Not Found</title>\n </head>\n <body>\n  <h1>404 - File ") - 1);
337 	PHPWRITE("Not Found</h1>\n </body>\n</html>",  sizeof("Not Found</h1>\n </body>\n</html>") - 1);
338 }
339 /* }}} */
340 
341 /* post-process REQUEST_URI and retrieve the actual request URI.  This is for
342    cases like http://localhost/blah.phar/path/to/file.php/extra/stuff
343    which calls "blah.phar" file "path/to/file.php" with PATH_INFO "/extra/stuff" */
phar_postprocess_ru_web(char * fname,size_t fname_len,char ** entry,size_t * entry_len,char ** ru,size_t * ru_len)344 static void phar_postprocess_ru_web(char *fname, size_t fname_len, char **entry, size_t *entry_len, char **ru, size_t *ru_len) /* {{{ */
345 {
346 	char *e = *entry + 1, *u = NULL, *u1 = NULL, *saveu = NULL;
347 	size_t e_len = *entry_len - 1, u_len = 0;
348 	phar_archive_data *pphar;
349 
350 	/* we already know we can retrieve the phar if we reach here */
351 	pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len);
352 
353 	if (!pphar && PHAR_G(manifest_cached)) {
354 		pphar = zend_hash_str_find_ptr(&cached_phars, fname, fname_len);
355 	}
356 
357 	do {
358 		if (zend_hash_str_exists(&(pphar->manifest), e, e_len)) {
359 			if (u) {
360 				u[0] = '/';
361 				*ru = estrndup(u, u_len+1);
362 				++u_len;
363 				u[0] = '\0';
364 			} else {
365 				*ru = NULL;
366 			}
367 			*ru_len = u_len;
368 			*entry_len = e_len + 1;
369 			return;
370 		}
371 
372 		if (u) {
373 			u1 = strrchr(e, '/');
374 			u[0] = '/';
375 			saveu = u;
376 			e_len += u_len + 1;
377 			u = u1;
378 			if (!u) {
379 				return;
380 			}
381 		} else {
382 			u = strrchr(e, '/');
383 			if (!u) {
384 				if (saveu) {
385 					saveu[0] = '/';
386 				}
387 				return;
388 			}
389 		}
390 
391 		u[0] = '\0';
392 		u_len = strlen(u + 1);
393 		e_len -= u_len + 1;
394 	} while (1);
395 }
396 /* }}} */
397 
398 /* {{{ return the name of the currently running phar archive.  If the optional parameter
399  * is set to true, return the phar:// URL to the currently running phar
400  */
PHP_METHOD(Phar,running)401 PHP_METHOD(Phar, running)
402 {
403 	zend_string *fname;
404 	char *arch, *entry;
405 	size_t arch_len, entry_len;
406 	bool retphar = 1;
407 
408 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &retphar) == FAILURE) {
409 		RETURN_THROWS();
410 	}
411 
412 	fname = zend_get_executed_filename_ex();
413 	if (!fname) {
414 		RETURN_EMPTY_STRING();
415 	}
416 
417 	if (
418 		zend_string_starts_with_literal_ci(fname, "phar://")
419 		&& SUCCESS == phar_split_fname(ZSTR_VAL(fname), ZSTR_LEN(fname), &arch, &arch_len, &entry, &entry_len, 2, 0)
420 	) {
421 		efree(entry);
422 		if (retphar) {
423 			RETVAL_STRINGL(ZSTR_VAL(fname), arch_len + 7);
424 			efree(arch);
425 			return;
426 		} else {
427 			// TODO: avoid reallocation ???
428 			RETVAL_STRINGL(arch, arch_len);
429 			efree(arch);
430 			return;
431 		}
432 	}
433 
434 	RETURN_EMPTY_STRING();
435 }
436 /* }}} */
437 
438 /* {{{ mount an external file or path to a location within the phar.  This maps
439  * an external file or directory to a location within the phar archive, allowing
440  * reference to an external location as if it were within the phar archive.  This
441  * is useful for writable temp files like databases
442  */
PHP_METHOD(Phar,mount)443 PHP_METHOD(Phar, mount)
444 {
445 	char *fname, *arch = NULL, *entry = NULL, *path, *actual;
446 	size_t fname_len, arch_len, entry_len;
447 	size_t path_len, actual_len;
448 	phar_archive_data *pphar;
449 #ifdef PHP_WIN32
450 	char *save_fname;
451 	ALLOCA_FLAG(fname_use_heap)
452 #endif
453 
454 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &path, &path_len, &actual, &actual_len) == FAILURE) {
455 		RETURN_THROWS();
456 	}
457 
458 	zend_string *zend_file_name = zend_get_executed_filename_ex();
459 	if (UNEXPECTED(!zend_file_name)) {
460 		fname = "";
461 		fname_len = 0;
462 	} else {
463 		fname = ZSTR_VAL(zend_file_name);
464 		fname_len = ZSTR_LEN(zend_file_name);
465 	}
466 
467 #ifdef PHP_WIN32
468 	save_fname = fname;
469 	if (memchr(fname, '\\', fname_len)) {
470 		fname = do_alloca(fname_len + 1, fname_use_heap);
471 		memcpy(fname, save_fname, fname_len);
472 		fname[fname_len] = '\0';
473 		phar_unixify_path_separators(fname, fname_len);
474 	}
475 #endif
476 
477 	if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
478 		efree(entry);
479 		entry = NULL;
480 
481 		if (path_len > 7 && !memcmp(path, "phar://", 7)) {
482 			zend_throw_exception_ex(phar_ce_PharException, 0, "Can only mount internal paths within a phar archive, use a relative path instead of \"%s\"", path);
483 			efree(arch);
484 			goto finish;
485 		}
486 carry_on2:
487 		if (NULL == (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), arch, arch_len))) {
488 			if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, arch, arch_len))) {
489 				if (SUCCESS == phar_copy_on_write(&pphar)) {
490 					goto carry_on;
491 				}
492 			}
493 
494 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s is not a phar archive, cannot mount", arch);
495 
496 			if (arch) {
497 				efree(arch);
498 			}
499 
500 			goto finish;
501 		}
502 carry_on:
503 		if (SUCCESS != phar_mount_entry(pphar, actual, actual_len, path, path_len)) {
504 			zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s within phar %s failed", path, actual, arch);
505 		}
506 
507 		if (entry && path == entry) {
508 			efree(entry);
509 		}
510 
511 		if (arch) {
512 			efree(arch);
513 		}
514 
515 		goto finish;
516 	} else if (HT_IS_INITIALIZED(&PHAR_G(phar_fname_map)) && NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len))) {
517 		goto carry_on;
518 	} else if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, fname, fname_len))) {
519 		if (SUCCESS == phar_copy_on_write(&pphar)) {
520 			goto carry_on;
521 		}
522 
523 		goto carry_on;
524 	} else if (SUCCESS == phar_split_fname(path, path_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
525 		path = entry;
526 		path_len = entry_len;
527 		goto carry_on2;
528 	}
529 
530 	zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s failed", path, actual);
531 
532 finish: ;
533 #ifdef PHP_WIN32
534 	if (fname != save_fname) {
535 		free_alloca(fname, fname_use_heap);
536 		fname = save_fname;
537 	}
538 #endif
539 }
540 /* }}} */
541 
542 /* {{{ mapPhar for web-based phars. Reads the currently executed file (a phar)
543  * and registers its manifest. When executed in the CLI or CGI command-line sapi,
544  * this works exactly like mapPhar().  When executed by a web-based sapi, this
545  * reads $_SERVER['REQUEST_URI'] (the actual original value) and parses out the
546  * intended internal file.
547  */
PHP_METHOD(Phar,webPhar)548 PHP_METHOD(Phar, webPhar)
549 {
550 	zval *mimeoverride = NULL;
551 	zend_fcall_info rewrite_fci = {0};
552 	zend_fcall_info_cache rewrite_fcc;
553 	char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL;
554 	size_t alias_len = 0, f404_len = 0, free_pathinfo = 0;
555 	size_t ru_len = 0;
556 	char *fname, *path_info, *mime_type = NULL, *entry, *pt;
557 	const char *basename;
558 	size_t fname_len, index_php_len = 0;
559 	size_t entry_len;
560 	int code, not_cgi;
561 	phar_archive_data *phar = NULL;
562 	phar_entry_info *info = NULL;
563 	size_t sapi_mod_name_len = strlen(sapi_module.name);
564 
565 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!s!s!af!", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite_fci, &rewrite_fcc) == FAILURE) {
566 		RETURN_THROWS();
567 	}
568 
569 	phar_request_initialize();
570 
571 	if (phar_open_executed_filename(alias, alias_len, &error) != SUCCESS) {
572 		if (error) {
573 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
574 			efree(error);
575 		}
576 		return;
577 	}
578 
579 	/* retrieve requested file within phar */
580 	if (!(SG(request_info).request_method
581 	      && SG(request_info).request_uri
582 	      && (!strcmp(SG(request_info).request_method, "GET")
583 	       || !strcmp(SG(request_info).request_method, "POST")
584 	       || !strcmp(SG(request_info).request_method, "DELETE")
585 	       || !strcmp(SG(request_info).request_method, "HEAD")
586 	       || !strcmp(SG(request_info).request_method, "OPTIONS")
587 	       || !strcmp(SG(request_info).request_method, "PATCH")
588 	       || !strcmp(SG(request_info).request_method, "PUT")
589 	      )
590 	     )
591 	   ) {
592 		return;
593 	}
594 
595 	zend_string *zend_file_name = zend_get_executed_filename_ex();
596 	if (UNEXPECTED(!zend_file_name)) {
597 		return;
598 	}
599 
600 	fname = ZSTR_VAL(zend_file_name);
601 	fname_len = ZSTR_LEN(zend_file_name);
602 
603 #ifdef PHP_WIN32
604 	if (memchr(fname, '\\', fname_len)) {
605 		fname = estrndup(fname, fname_len);
606 		phar_unixify_path_separators(fname, fname_len);
607 	}
608 #endif
609 	basename = zend_memrchr(fname, '/', fname_len);
610 
611 	if (!basename) {
612 		basename = fname;
613 	} else {
614 		++basename;
615 	}
616 
617 	if ((sapi_mod_name_len == sizeof("cgi-fcgi") - 1 && !strncmp(sapi_module.name, "cgi-fcgi", sizeof("cgi-fcgi") - 1))
618 		|| (sapi_mod_name_len == sizeof("fpm-fcgi") - 1 && !strncmp(sapi_module.name, "fpm-fcgi", sizeof("fpm-fcgi") - 1))
619 		|| (sapi_mod_name_len == sizeof("cgi") - 1 && !strncmp(sapi_module.name, "cgi", sizeof("cgi") - 1))
620 		|| (sapi_mod_name_len == sizeof("litespeed") - 1 && !strncmp(sapi_module.name, "litespeed", sizeof("litespeed") - 1))) {
621 
622 		if (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) != IS_UNDEF) {
623 			HashTable *_server = Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]);
624 			zval *z_script_name, *z_path_info;
625 
626 			if (NULL == (z_script_name = zend_hash_str_find(_server, "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) ||
627 				IS_STRING != Z_TYPE_P(z_script_name) ||
628 				!strstr(Z_STRVAL_P(z_script_name), basename)) {
629 				goto finish;
630 			}
631 
632 			if (NULL != (z_path_info = zend_hash_str_find(_server, "PATH_INFO", sizeof("PATH_INFO")-1)) &&
633 				IS_STRING == Z_TYPE_P(z_path_info)) {
634 				entry_len = Z_STRLEN_P(z_path_info);
635 				entry = estrndup(Z_STRVAL_P(z_path_info), entry_len);
636 				path_info = emalloc(Z_STRLEN_P(z_script_name) + entry_len + 1);
637 				memcpy(path_info, Z_STRVAL_P(z_script_name), Z_STRLEN_P(z_script_name));
638 				memcpy(path_info + Z_STRLEN_P(z_script_name), entry, entry_len + 1);
639 				free_pathinfo = 1;
640 			} else {
641 				entry_len = 0;
642 				entry = estrndup("", 0);
643 				path_info = Z_STRVAL_P(z_script_name);
644 			}
645 
646 			pt = estrndup(Z_STRVAL_P(z_script_name), Z_STRLEN_P(z_script_name));
647 
648 		} else {
649 			char *testit;
650 
651 			testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1);
652 			if (!(pt = strstr(testit, basename))) {
653 				efree(testit);
654 				goto finish;
655 			}
656 
657 			path_info = sapi_getenv("PATH_INFO", sizeof("PATH_INFO")-1);
658 
659 			if (path_info) {
660 				entry = path_info;
661 				entry_len = strlen(entry);
662 				spprintf(&path_info, 0, "%s%s", testit, path_info);
663 				free_pathinfo = 1;
664 			} else {
665 				path_info = testit;
666 				free_pathinfo = 1;
667 				entry = estrndup("", 0);
668 				entry_len = 0;
669 			}
670 
671 			pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname)));
672 		}
673 		not_cgi = 0;
674 	} else {
675 		path_info = SG(request_info).request_uri;
676 
677 		if (!(pt = strstr(path_info, basename))) {
678 			/* this can happen with rewrite rules - and we have no idea what to do then, so return */
679 			goto finish;
680 		}
681 
682 		entry_len = strlen(path_info);
683 		entry_len -= (pt - path_info) + (fname_len - (basename - fname));
684 		entry = estrndup(pt + (fname_len - (basename - fname)), entry_len);
685 
686 		pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname)));
687 		not_cgi = 1;
688 	}
689 
690 	if (ZEND_FCI_INITIALIZED(rewrite_fci)) {
691 		zval params, retval;
692 
693 		ZVAL_STRINGL(&params, entry, entry_len);
694 
695 		rewrite_fci.param_count = 1;
696 		rewrite_fci.params = &params;
697 		rewrite_fci.retval = &retval;
698 
699 		if (FAILURE == zend_call_function(&rewrite_fci, &rewrite_fcc)) {
700 			if (!EG(exception)) {
701 				zend_throw_exception_ex(phar_ce_PharException, 0, "phar error: failed to call rewrite callback");
702 			}
703 			goto cleanup_fail;
704 		}
705 
706 		if (Z_TYPE_P(rewrite_fci.retval) == IS_UNDEF || Z_TYPE(retval) == IS_UNDEF) {
707 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar error: rewrite callback must return a string or false");
708 			goto cleanup_fail;
709 		}
710 
711 		switch (Z_TYPE(retval)) {
712 			case IS_STRING:
713 				efree(entry);
714 				entry = estrndup(Z_STRVAL_P(rewrite_fci.retval), Z_STRLEN_P(rewrite_fci.retval));
715 				entry_len = Z_STRLEN_P(rewrite_fci.retval);
716 				break;
717 			case IS_TRUE:
718 			case IS_FALSE:
719 				phar_do_403(entry, entry_len);
720 
721 				if (free_pathinfo) {
722 					efree(path_info);
723 				}
724 				efree(pt);
725 
726 				zend_bailout();
727 			default:
728 				zend_throw_exception_ex(phar_ce_PharException, 0, "phar error: rewrite callback must return a string or false");
729 
730 cleanup_fail:
731 				zval_ptr_dtor(&params);
732 				if (free_pathinfo) {
733 					efree(path_info);
734 				}
735 				efree(entry);
736 				efree(pt);
737 #ifdef PHP_WIN32
738 				efree(fname);
739 #endif
740 				RETURN_THROWS();
741 		}
742 	}
743 
744 	if (entry_len) {
745 		phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len);
746 	}
747 
748 	if (!entry_len || (entry_len == 1 && entry[0] == '/')) {
749 		efree(entry);
750 		/* direct request */
751 		if (index_php_len) {
752 			entry = index_php;
753 			entry_len = index_php_len;
754 			if (entry[0] != '/') {
755 				spprintf(&entry, 0, "/%s", index_php);
756 				++entry_len;
757 			}
758 		} else {
759 			/* assume "index.php" is starting point */
760 			entry = estrndup("/index.php", sizeof("/index.php"));
761 			entry_len = sizeof("/index.php")-1;
762 		}
763 
764 		if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL) ||
765 			(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0)) == NULL) {
766 			phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len);
767 
768 			if (free_pathinfo) {
769 				efree(path_info);
770 			}
771 
772 			zend_bailout();
773 		} else {
774 			char *tmp = NULL, sa = '\0';
775 			sapi_header_line ctr = {0};
776 			ctr.response_code = 301;
777 			ctr.line_len = sizeof("HTTP/1.1 301 Moved Permanently")-1;
778 			ctr.line = "HTTP/1.1 301 Moved Permanently";
779 			sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
780 
781 			if (not_cgi) {
782 				tmp = strstr(path_info, basename) + fname_len;
783 				sa = *tmp;
784 				*tmp = '\0';
785 			}
786 
787 			ctr.response_code = 0;
788 
789 			if (path_info[strlen(path_info)-1] == '/') {
790 				ctr.line_len = spprintf((char **) &(ctr.line), 4096, "Location: %s%s", path_info, entry + 1);
791 			} else {
792 				ctr.line_len = spprintf((char **) &(ctr.line), 4096, "Location: %s%s", path_info, entry);
793 			}
794 
795 			if (not_cgi) {
796 				*tmp = sa;
797 			}
798 
799 			if (free_pathinfo) {
800 				efree(path_info);
801 			}
802 
803 			sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
804 			sapi_send_headers();
805 			efree((void *) ctr.line);
806 			zend_bailout();
807 		}
808 	}
809 
810 	if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL) ||
811 		(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0)) == NULL) {
812 		phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len);
813 		zend_bailout();
814 	}
815 
816 	if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) {
817 		const char *ext = zend_memrchr(entry, '.', entry_len);
818 		zval *val;
819 
820 		if (ext) {
821 			++ext;
822 
823 			if (NULL != (val = zend_hash_str_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)))) {
824 				switch (Z_TYPE_P(val)) {
825 					case IS_LONG:
826 						if (Z_LVAL_P(val) == PHAR_MIME_PHP || Z_LVAL_P(val) == PHAR_MIME_PHPS) {
827 							mime_type = "";
828 							code = Z_LVAL_P(val);
829 						} else {
830 							zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed");
831 							if (free_pathinfo) {
832 								efree(path_info);
833 							}
834 							efree(pt);
835 							efree(entry);
836 #ifdef PHP_WIN32
837 							efree(fname);
838 #endif
839 							RETURN_THROWS();
840 						}
841 						break;
842 					case IS_STRING:
843 						mime_type = Z_STRVAL_P(val);
844 						code = PHAR_MIME_OTHER;
845 						break;
846 					default:
847 						zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed");
848 						if (free_pathinfo) {
849 							efree(path_info);
850 						}
851 						efree(pt);
852 						efree(entry);
853 #ifdef PHP_WIN32
854 						efree(fname);
855 #endif
856 						RETURN_THROWS();
857 				}
858 			}
859 		}
860 	}
861 
862 	if (!mime_type) {
863 		code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type);
864 	}
865 	phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len);
866 
867 finish: ;
868 #ifdef PHP_WIN32
869 	efree(fname);
870 #endif
871 }
872 /* }}} */
873 
874 /* {{{ Defines a list of up to 4 $_SERVER variables that should be modified for execution
875  * to mask the presence of the phar archive.  This should be used in conjunction with
876  * Phar::webPhar(), and has no effect otherwise
877  * SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME
878  */
PHP_METHOD(Phar,mungServer)879 PHP_METHOD(Phar, mungServer)
880 {
881 	zval *mungvalues, *data;
882 
883 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "a", &mungvalues) == FAILURE) {
884 		RETURN_THROWS();
885 	}
886 
887 	if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) {
888 		zend_throw_exception_ex(phar_ce_PharException, 0, "No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
889 		RETURN_THROWS();
890 	}
891 
892 	if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) {
893 		zend_throw_exception_ex(phar_ce_PharException, 0, "Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
894 		RETURN_THROWS();
895 	}
896 
897 	phar_request_initialize();
898 
899 	ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(mungvalues), data) {
900 
901 		if (Z_TYPE_P(data) != IS_STRING) {
902 			zend_throw_exception_ex(phar_ce_PharException, 0, "Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
903 			RETURN_THROWS();
904 		}
905 
906 		if (zend_string_equals_literal(Z_STR_P(data), "PHP_SELF")) {
907 			PHAR_G(phar_SERVER_mung_list) |= PHAR_MUNG_PHP_SELF;
908 		} else if (zend_string_equals_literal(Z_STR_P(data), "REQUEST_URI")) {
909 			PHAR_G(phar_SERVER_mung_list) |= PHAR_MUNG_REQUEST_URI;
910 		} else if (zend_string_equals_literal(Z_STR_P(data), "SCRIPT_NAME")) {
911 			PHAR_G(phar_SERVER_mung_list) |= PHAR_MUNG_SCRIPT_NAME;
912 		} else if (zend_string_equals_literal(Z_STR_P(data), "SCRIPT_FILENAME")) {
913 			PHAR_G(phar_SERVER_mung_list) |= PHAR_MUNG_SCRIPT_FILENAME;
914 		}
915 		// TODO Warning for invalid value?
916 	} ZEND_HASH_FOREACH_END();
917 }
918 /* }}} */
919 
920 /* {{{ instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
921  * and return stat on files within the phar for relative paths
922  *
923  * Once called, this cannot be reversed, and continue until the end of the request.
924  *
925  * This allows legacy scripts to be pharred unmodified
926  */
PHP_METHOD(Phar,interceptFileFuncs)927 PHP_METHOD(Phar, interceptFileFuncs)
928 {
929 	if (zend_parse_parameters_none() == FAILURE) {
930 		RETURN_THROWS();
931 	}
932 	phar_intercept_functions();
933 }
934 /* }}} */
935 
936 /* {{{ Return a stub that can be used to run a phar-based archive without the phar extension
937  * indexfile is the CLI startup filename, which defaults to "index.php", webindexfile
938  * is the web startup filename, and also defaults to "index.php"
939  */
PHP_METHOD(Phar,createDefaultStub)940 PHP_METHOD(Phar, createDefaultStub)
941 {
942 	char *index = NULL, *webindex = NULL, *error;
943 	zend_string *stub;
944 	size_t index_len = 0, webindex_len = 0;
945 
946 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|p!p!", &index, &index_len, &webindex, &webindex_len) == FAILURE) {
947 		RETURN_THROWS();
948 	}
949 
950 	stub = phar_create_default_stub(index, webindex, &error);
951 
952 	if (error) {
953 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
954 		efree(error);
955 		RETURN_THROWS();
956 	}
957 	RETURN_NEW_STR(stub);
958 }
959 /* }}} */
960 
961 /* {{{ Reads the currently executed file (a phar) and registers its manifest */
PHP_METHOD(Phar,mapPhar)962 PHP_METHOD(Phar, mapPhar)
963 {
964 	char *alias = NULL, *error;
965 	size_t alias_len = 0;
966 	zend_long dataoffset = 0;
967 
968 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!l", &alias, &alias_len, &dataoffset) == FAILURE) {
969 		RETURN_THROWS();
970 	}
971 
972 	phar_request_initialize();
973 
974 	RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error) == SUCCESS);
975 
976 	if (error) {
977 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
978 		efree(error);
979 	}
980 } /* }}} */
981 
982 /* {{{ Loads any phar archive with an alias */
PHP_METHOD(Phar,loadPhar)983 PHP_METHOD(Phar, loadPhar)
984 {
985 	char *fname, *alias = NULL, *error;
986 	size_t fname_len, alias_len = 0;
987 
988 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) {
989 		RETURN_THROWS();
990 	}
991 
992 	phar_request_initialize();
993 
994 	RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS);
995 
996 	if (error) {
997 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
998 		efree(error);
999 	}
1000 } /* }}} */
1001 
1002 /* {{{ Returns the api version */
PHP_METHOD(Phar,apiVersion)1003 PHP_METHOD(Phar, apiVersion)
1004 {
1005 	if (zend_parse_parameters_none() == FAILURE) {
1006 		RETURN_THROWS();
1007 	}
1008 	RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1);
1009 }
1010 /* }}}*/
1011 
1012 /* {{{ Returns whether phar extension supports compression using zlib/bzip2 */
PHP_METHOD(Phar,canCompress)1013 PHP_METHOD(Phar, canCompress)
1014 {
1015 	zend_long method = 0;
1016 
1017 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &method) == FAILURE) {
1018 		RETURN_THROWS();
1019 	}
1020 
1021 	phar_request_initialize();
1022 	switch (method) {
1023 	case PHAR_ENT_COMPRESSED_GZ:
1024 		if (PHAR_G(has_zlib)) {
1025 			RETURN_TRUE;
1026 		} else {
1027 			RETURN_FALSE;
1028 		}
1029 	case PHAR_ENT_COMPRESSED_BZ2:
1030 		if (PHAR_G(has_bz2)) {
1031 			RETURN_TRUE;
1032 		} else {
1033 			RETURN_FALSE;
1034 		}
1035 	default:
1036 		if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) {
1037 			RETURN_TRUE;
1038 		} else {
1039 			RETURN_FALSE;
1040 		}
1041 	}
1042 }
1043 /* }}} */
1044 
1045 /* {{{ Returns whether phar extension supports writing and creating phars */
PHP_METHOD(Phar,canWrite)1046 PHP_METHOD(Phar, canWrite)
1047 {
1048 	if (zend_parse_parameters_none() == FAILURE) {
1049 		RETURN_THROWS();
1050 	}
1051 	RETURN_BOOL(!PHAR_G(readonly));
1052 }
1053 /* }}} */
1054 
1055 /* {{{ Returns whether the given filename is a valid phar filename */
PHP_METHOD(Phar,isValidPharFilename)1056 PHP_METHOD(Phar, isValidPharFilename)
1057 {
1058 	char *fname;
1059 	const char *ext_str;
1060 	size_t fname_len;
1061 	size_t ext_len;
1062 	int is_executable;
1063 	bool executable = 1;
1064 
1065 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|b", &fname, &fname_len, &executable) == FAILURE) {
1066 		RETURN_THROWS();
1067 	}
1068 
1069 	is_executable = executable;
1070 	RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1) == SUCCESS);
1071 }
1072 /* }}} */
1073 
1074 /**
1075  * from spl_directory
1076  */
phar_spl_foreign_dtor(spl_filesystem_object * object)1077 static void phar_spl_foreign_dtor(spl_filesystem_object *object) /* {{{ */
1078 {
1079 	phar_archive_data *phar = (phar_archive_data *) object->oth;
1080 
1081 	if (!phar->is_persistent) {
1082 		phar_archive_delref(phar);
1083 	}
1084 
1085 	object->oth = NULL;
1086 }
1087 /* }}} */
1088 
1089 /**
1090  * from spl_directory
1091  */
phar_spl_foreign_clone(spl_filesystem_object * src,spl_filesystem_object * dst)1092 static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst) /* {{{ */
1093 {
1094 	phar_archive_data *phar_data = (phar_archive_data *) dst->oth;
1095 
1096 	if (!phar_data->is_persistent) {
1097 		++(phar_data->refcount);
1098 	}
1099 }
1100 /* }}} */
1101 
1102 static const spl_other_handler phar_spl_foreign_handler = {
1103 	phar_spl_foreign_dtor,
1104 	phar_spl_foreign_clone
1105 };
1106 
1107 /* {{{ Construct a Phar archive object
1108  *
1109  * proto PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR])
1110  * Construct a PharData archive object
1111  *
1112  * This function is used as the constructor for both the Phar and PharData
1113  * classes, hence the two prototypes above.
1114  */
PHP_METHOD(Phar,__construct)1115 PHP_METHOD(Phar, __construct)
1116 {
1117 	char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname;
1118 	size_t fname_len, alias_len = 0;
1119 	size_t arch_len, entry_len;
1120 	bool is_data;
1121 	zend_long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS;
1122 	zend_long format = 0;
1123 	phar_archive_object *phar_obj;
1124 	phar_archive_data   *phar_data;
1125 	zval *zobj = ZEND_THIS, arg1, arg2;
1126 
1127 	phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset);
1128 
1129 	is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data);
1130 
1131 	if (is_data) {
1132 		if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) {
1133 			RETURN_THROWS();
1134 		}
1135 	} else {
1136 		if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) {
1137 			RETURN_THROWS();
1138 		}
1139 	}
1140 
1141 	if (phar_obj->archive) {
1142 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice");
1143 		RETURN_THROWS();
1144 	}
1145 
1146 	save_fname = fname;
1147 	if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2)) {
1148 		/* use arch (the basename for the archive) for fname instead of fname */
1149 		/* this allows support for RecursiveDirectoryIterator of subdirectories */
1150 #ifdef PHP_WIN32
1151 		phar_unixify_path_separators(arch, arch_len);
1152 #endif
1153 		fname = arch;
1154 		fname_len = arch_len;
1155 #ifdef PHP_WIN32
1156 	} else {
1157 		arch = estrndup(fname, fname_len);
1158 		arch_len = fname_len;
1159 		fname = arch;
1160 		phar_unixify_path_separators(arch, arch_len);
1161 #endif
1162 	}
1163 
1164 	if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error) == FAILURE) {
1165 
1166 		if (fname == arch && fname != save_fname) {
1167 			efree(arch);
1168 			fname = save_fname;
1169 		}
1170 
1171 		if (entry) {
1172 			efree(entry);
1173 		}
1174 
1175 		if (error) {
1176 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1177 				"%s", error);
1178 			efree(error);
1179 		} else {
1180 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1181 				"Phar creation or opening failed");
1182 		}
1183 
1184 		RETURN_THROWS();
1185 	}
1186 
1187 	if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) {
1188 		phar_data->is_zip = 1;
1189 		phar_data->is_tar = 0;
1190 	}
1191 
1192 	if (fname == arch) {
1193 		efree(arch);
1194 		fname = save_fname;
1195 	}
1196 
1197 	if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) {
1198 		if (is_data) {
1199 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1200 				"PharData class can only be used for non-executable tar and zip archives");
1201 		} else {
1202 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1203 				"Phar class can only be used for executable tar and zip archives");
1204 		}
1205 		efree(entry);
1206 		RETURN_THROWS();
1207 	}
1208 
1209 	is_data = phar_data->is_data;
1210 
1211 	if (!phar_data->is_persistent) {
1212 		++(phar_data->refcount);
1213 	}
1214 
1215 	phar_obj->archive = phar_data;
1216 	phar_obj->spl.oth_handler = &phar_spl_foreign_handler;
1217 
1218 	if (entry) {
1219 		fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry);
1220 		efree(entry);
1221 	} else {
1222 		fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname);
1223 	}
1224 
1225 	ZVAL_STRINGL(&arg1, fname, fname_len);
1226 	ZVAL_LONG(&arg2, flags);
1227 
1228 	zend_call_known_instance_method_with_2_params(spl_ce_RecursiveDirectoryIterator->constructor,
1229 		Z_OBJ_P(zobj), NULL, &arg1, &arg2);
1230 
1231 	zval_ptr_dtor(&arg1);
1232 
1233 	if (!phar_data->is_persistent) {
1234 		phar_obj->archive->is_data = is_data;
1235 	} else if (!EG(exception)) {
1236 		/* register this guy so we can modify if necessary */
1237 		zend_hash_str_add_ptr(&PHAR_G(phar_persist_map), (const char *) phar_obj->archive, sizeof(phar_obj->archive), phar_obj);
1238 	}
1239 
1240 	phar_obj->spl.info_class = phar_ce_entry;
1241 	efree(fname);
1242 }
1243 /* }}} */
1244 
1245 /* {{{ Return array of supported signature types */
PHP_METHOD(Phar,getSupportedSignatures)1246 PHP_METHOD(Phar, getSupportedSignatures)
1247 {
1248 	if (zend_parse_parameters_none() == FAILURE) {
1249 		RETURN_THROWS();
1250 	}
1251 
1252 	array_init(return_value);
1253 
1254 	add_next_index_stringl(return_value, "MD5", 3);
1255 	add_next_index_stringl(return_value, "SHA-1", 5);
1256 	add_next_index_stringl(return_value, "SHA-256", 7);
1257 	add_next_index_stringl(return_value, "SHA-512", 7);
1258 #ifdef PHAR_HAVE_OPENSSL
1259 	add_next_index_stringl(return_value, "OpenSSL", 7);
1260 	add_next_index_stringl(return_value, "OpenSSL_SHA256", 14);
1261 	add_next_index_stringl(return_value, "OpenSSL_SHA512", 14);
1262 #else
1263 	if (zend_hash_str_exists(&module_registry, "openssl", sizeof("openssl")-1)) {
1264 		add_next_index_stringl(return_value, "OpenSSL", 7);
1265 		add_next_index_stringl(return_value, "OpenSSL_SHA256", 14);
1266 		add_next_index_stringl(return_value, "OpenSSL_SHA512", 14);
1267 	}
1268 #endif
1269 }
1270 /* }}} */
1271 
1272 /* {{{ Return array of supported comparession algorithms */
PHP_METHOD(Phar,getSupportedCompression)1273 PHP_METHOD(Phar, getSupportedCompression)
1274 {
1275 	if (zend_parse_parameters_none() == FAILURE) {
1276 		RETURN_THROWS();
1277 	}
1278 
1279 	array_init(return_value);
1280 	phar_request_initialize();
1281 
1282 	if (PHAR_G(has_zlib)) {
1283 		add_next_index_stringl(return_value, "GZ", 2);
1284 	}
1285 
1286 	if (PHAR_G(has_bz2)) {
1287 		add_next_index_stringl(return_value, "BZIP2", 5);
1288 	}
1289 }
1290 /* }}} */
1291 
1292 /* {{{ Completely remove a phar archive from memory and disk */
PHP_METHOD(Phar,unlinkArchive)1293 PHP_METHOD(Phar, unlinkArchive)
1294 {
1295 	char *fname, *error, *arch, *entry;
1296 	size_t fname_len;
1297 	size_t arch_len, entry_len;
1298 	phar_archive_data *phar;
1299 
1300 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
1301 		RETURN_THROWS();
1302 	}
1303 
1304 	if (!fname_len) {
1305 		zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"\"");
1306 		RETURN_THROWS();
1307 	}
1308 
1309 	if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) {
1310 		if (error) {
1311 			zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\": %s", fname, error);
1312 			efree(error);
1313 		} else {
1314 			zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\"", fname);
1315 		}
1316 		RETURN_THROWS();
1317 	}
1318 
1319 	zend_string *zend_file_name = zend_get_executed_filename_ex();
1320 
1321 	if (
1322 		zend_file_name
1323 		&& zend_string_starts_with_literal_ci(zend_file_name, "phar://")
1324 		&& SUCCESS == phar_split_fname(ZSTR_VAL(zend_file_name), ZSTR_LEN(zend_file_name), &arch, &arch_len, &entry, &entry_len, 2, 0)
1325 	) {
1326 		if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) {
1327 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" cannot be unlinked from within itself", fname);
1328 			efree(arch);
1329 			efree(entry);
1330 			RETURN_THROWS();
1331 		}
1332 		efree(arch);
1333 		efree(entry);
1334 	}
1335 
1336 	if (phar->is_persistent) {
1337 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname);
1338 		RETURN_THROWS();
1339 	}
1340 
1341 	if (phar->refcount) {
1342 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" has open file handles or objects.  fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname);
1343 		RETURN_THROWS();
1344 	}
1345 
1346 	fname = estrndup(phar->fname, phar->fname_len);
1347 
1348 	/* invalidate phar cache */
1349 	PHAR_G(last_phar) = NULL;
1350 	PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
1351 
1352 	phar_archive_delref(phar);
1353 	unlink(fname);
1354 	efree(fname);
1355 	RETURN_TRUE;
1356 }
1357 /* }}} */
1358 
1359 #define PHAR_ARCHIVE_OBJECT() \
1360 	zval *zobj = ZEND_THIS; \
1361 	phar_archive_object *phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); \
1362 	if (!phar_obj->archive) { \
1363 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
1364 			"Cannot call method on an uninitialized Phar object"); \
1365 		RETURN_THROWS(); \
1366 	}
1367 
1368 /* {{{ if persistent, remove from the cache */
PHP_METHOD(Phar,__destruct)1369 PHP_METHOD(Phar, __destruct)
1370 {
1371 	zval *zobj = ZEND_THIS;
1372 	phar_archive_object *phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset);
1373 
1374 	if (zend_parse_parameters_none() == FAILURE) {
1375 		RETURN_THROWS();
1376 	}
1377 
1378 	if (phar_obj->archive && phar_obj->archive->is_persistent) {
1379 		zend_hash_str_del(&PHAR_G(phar_persist_map), (const char *) phar_obj->archive, sizeof(phar_obj->archive));
1380 	}
1381 }
1382 /* }}} */
1383 
1384 struct _phar_t {
1385 	phar_archive_object *p;
1386 	zend_class_entry *c;
1387 	zend_string *base;
1388 	zval *ret;
1389 	php_stream *fp;
1390 	int count;
1391 };
1392 
phar_build(zend_object_iterator * iter,void * puser)1393 static int phar_build(zend_object_iterator *iter, void *puser) /* {{{ */
1394 {
1395 	zval *value;
1396 	bool close_fp = 1;
1397 	struct _phar_t *p_obj = (struct _phar_t*) puser;
1398 	size_t str_key_len, base_len = ZSTR_LEN(p_obj->base);
1399 	phar_entry_data *data;
1400 	php_stream *fp;
1401 	size_t fname_len;
1402 	size_t contents_len;
1403 	char *fname, *error = NULL, *base = ZSTR_VAL(p_obj->base), *save = NULL, *temp = NULL;
1404 	zend_string *opened;
1405 	char *str_key;
1406 	zend_class_entry *ce = p_obj->c;
1407 	phar_archive_object *phar_obj = p_obj->p;
1408 	php_stream_statbuf ssb;
1409 	char ch;
1410 
1411 	value = iter->funcs->get_current_data(iter);
1412 
1413 	if (EG(exception)) {
1414 		return ZEND_HASH_APPLY_STOP;
1415 	}
1416 
1417 	if (!value) {
1418 		/* failure in get_current_data */
1419 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned no value", ZSTR_VAL(ce->name));
1420 		return ZEND_HASH_APPLY_STOP;
1421 	}
1422 
1423 	switch (Z_TYPE_P(value)) {
1424 		case IS_STRING:
1425 			break;
1426 		case IS_RESOURCE:
1427 			php_stream_from_zval_no_verify(fp, value);
1428 
1429 			if (!fp) {
1430 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Iterator %s returned an invalid stream handle", ZSTR_VAL(ce->name));
1431 				return ZEND_HASH_APPLY_STOP;
1432 			}
1433 
1434 			if (iter->funcs->get_current_key) {
1435 				zval key;
1436 				iter->funcs->get_current_key(iter, &key);
1437 
1438 				if (EG(exception)) {
1439 					return ZEND_HASH_APPLY_STOP;
1440 				}
1441 
1442 				if (Z_TYPE(key) != IS_STRING) {
1443 					zval_ptr_dtor(&key);
1444 					zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid key (must return a string)", ZSTR_VAL(ce->name));
1445 					return ZEND_HASH_APPLY_STOP;
1446 				}
1447 
1448 				str_key_len = Z_STRLEN(key);
1449 				str_key = estrndup(Z_STRVAL(key), str_key_len);
1450 
1451 				save = str_key;
1452 				zval_ptr_dtor_str(&key);
1453 			} else {
1454 				zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid key (must return a string)", ZSTR_VAL(ce->name));
1455 				return ZEND_HASH_APPLY_STOP;
1456 			}
1457 
1458 			close_fp = 0;
1459 			opened = ZSTR_INIT_LITERAL("[stream]", 0);
1460 			goto after_open_fp;
1461 		case IS_OBJECT:
1462 			if (instanceof_function(Z_OBJCE_P(value), spl_ce_SplFileInfo)) {
1463 				char *test = NULL;
1464 				spl_filesystem_object *intern = (spl_filesystem_object*)((char*)Z_OBJ_P(value) - Z_OBJ_P(value)->handlers->offset);
1465 
1466 				if (!base_len) {
1467 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Iterator %s returns an SplFileInfo object, so base directory must be specified", ZSTR_VAL(ce->name));
1468 					return ZEND_HASH_APPLY_STOP;
1469 				}
1470 
1471 				switch (intern->type) {
1472 					case SPL_FS_DIR: {
1473 						zend_string *test_str = spl_filesystem_object_get_path(intern);
1474 						fname_len = spprintf(&fname, 0, "%s%c%s", ZSTR_VAL(test_str), DEFAULT_SLASH, intern->u.dir.entry.d_name);
1475 						zend_string_release_ex(test_str, /* persistent */ false);
1476 						if (php_stream_stat_path(fname, &ssb) == 0 && S_ISDIR(ssb.sb.st_mode)) {
1477 							/* ignore directories */
1478 							efree(fname);
1479 							return ZEND_HASH_APPLY_KEEP;
1480 						}
1481 
1482 						test = expand_filepath(fname, NULL);
1483 						efree(fname);
1484 
1485 						if (test) {
1486 							fname = test;
1487 							fname_len = strlen(fname);
1488 						} else {
1489 							zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Could not resolve file path");
1490 							return ZEND_HASH_APPLY_STOP;
1491 						}
1492 
1493 						save = fname;
1494 						goto phar_spl_fileinfo;
1495 					}
1496 					case SPL_FS_INFO:
1497 					case SPL_FS_FILE:
1498 						fname = expand_filepath(ZSTR_VAL(intern->file_name), NULL);
1499 						if (!fname) {
1500 							zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Could not resolve file path");
1501 							return ZEND_HASH_APPLY_STOP;
1502 						}
1503 
1504 						fname_len = strlen(fname);
1505 						save = fname;
1506 						goto phar_spl_fileinfo;
1507 				}
1508 			}
1509 			ZEND_FALLTHROUGH;
1510 		default:
1511 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid value (must return a string, a stream, or an SplFileInfo object)", ZSTR_VAL(ce->name));
1512 			return ZEND_HASH_APPLY_STOP;
1513 	}
1514 
1515 	fname = Z_STRVAL_P(value);
1516 	fname_len = Z_STRLEN_P(value);
1517 
1518 phar_spl_fileinfo:
1519 	if (base_len) {
1520 		temp = expand_filepath(base, NULL);
1521 		if (!temp) {
1522 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Could not resolve file path");
1523 			if (save) {
1524 				efree(save);
1525 			}
1526 			return ZEND_HASH_APPLY_STOP;
1527 		}
1528 
1529 		base = temp;
1530 		base_len = strlen(base);
1531 
1532 		if (fname_len >= base_len && strncmp(fname, base, base_len) == 0 && ((ch = fname[base_len - IS_SLASH(base[base_len - 1])]) == '\0' || IS_SLASH(ch))) {
1533 			str_key_len = fname_len - base_len;
1534 
1535 			if (str_key_len <= 0) {
1536 				if (save) {
1537 					efree(save);
1538 					efree(temp);
1539 				}
1540 				return ZEND_HASH_APPLY_KEEP;
1541 			}
1542 
1543 			str_key = fname + base_len;
1544 
1545 			if (*str_key == '/' || *str_key == '\\') {
1546 				str_key++;
1547 				str_key_len--;
1548 			}
1549 
1550 		} else {
1551 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned a path \"%s\" that is not in the base directory \"%s\"", ZSTR_VAL(ce->name), fname, base);
1552 
1553 			if (save) {
1554 				efree(save);
1555 				efree(temp);
1556 			}
1557 
1558 			return ZEND_HASH_APPLY_STOP;
1559 		}
1560 	} else {
1561 		if (iter->funcs->get_current_key) {
1562 			zval key;
1563 			iter->funcs->get_current_key(iter, &key);
1564 
1565 			if (EG(exception)) {
1566 				return ZEND_HASH_APPLY_STOP;
1567 			}
1568 
1569 			if (Z_TYPE(key) != IS_STRING) {
1570 				zval_ptr_dtor(&key);
1571 				zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid key (must return a string)", ZSTR_VAL(ce->name));
1572 				return ZEND_HASH_APPLY_STOP;
1573 			}
1574 
1575 			str_key_len = Z_STRLEN(key);
1576 			str_key = estrndup(Z_STRVAL(key), str_key_len);
1577 
1578 			save = str_key;
1579 			zval_ptr_dtor_str(&key);
1580 		} else {
1581 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid key (must return a string)", ZSTR_VAL(ce->name));
1582 			return ZEND_HASH_APPLY_STOP;
1583 		}
1584 	}
1585 
1586 	if (php_check_open_basedir(fname)) {
1587 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned a path \"%s\" that open_basedir prevents opening", ZSTR_VAL(ce->name), fname);
1588 
1589 		if (save) {
1590 			efree(save);
1591 		}
1592 
1593 		if (temp) {
1594 			efree(temp);
1595 		}
1596 
1597 		return ZEND_HASH_APPLY_STOP;
1598 	}
1599 
1600 	/* try to open source file, then create internal phar file and copy contents */
1601 	fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened);
1602 
1603 	if (!fp) {
1604 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned a file that could not be opened \"%s\"", ZSTR_VAL(ce->name), fname);
1605 
1606 		if (save) {
1607 			efree(save);
1608 		}
1609 
1610 		if (temp) {
1611 			efree(temp);
1612 		}
1613 
1614 		return ZEND_HASH_APPLY_STOP;
1615 	}
1616 after_open_fp:
1617 	if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) {
1618 		/* silently skip any files that would be added to the magic .phar directory */
1619 		if (save) {
1620 			efree(save);
1621 		}
1622 
1623 		if (temp) {
1624 			efree(temp);
1625 		}
1626 
1627 		if (opened) {
1628 			zend_string_release_ex(opened, 0);
1629 		}
1630 
1631 		if (close_fp) {
1632 			php_stream_close(fp);
1633 		}
1634 
1635 		return ZEND_HASH_APPLY_KEEP;
1636 	}
1637 
1638 	if (!(data = phar_get_or_create_entry_data(phar_obj->archive->fname, phar_obj->archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1))) {
1639 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s cannot be created: %s", str_key, error);
1640 		efree(error);
1641 
1642 		if (save) {
1643 			efree(save);
1644 		}
1645 
1646 		if (opened) {
1647 			zend_string_release_ex(opened, 0);
1648 		}
1649 
1650 		if (temp) {
1651 			efree(temp);
1652 		}
1653 
1654 		if (close_fp) {
1655 			php_stream_close(fp);
1656 		}
1657 
1658 		return ZEND_HASH_APPLY_STOP;
1659 
1660 	} else {
1661 		if (error) {
1662 			efree(error);
1663 		}
1664 		/* convert to PHAR_UFP */
1665 		if (data->internal_file->fp_type == PHAR_MOD) {
1666 			php_stream_close(data->internal_file->fp);
1667 		}
1668 
1669 		data->internal_file->fp = NULL;
1670 		data->internal_file->fp_type = PHAR_UFP;
1671 		data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp);
1672 		data->fp = NULL;
1673 		php_stream_copy_to_stream_ex(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len);
1674 		data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize =
1675 			php_stream_tell(p_obj->fp) - data->internal_file->offset;
1676 		if (php_stream_stat(fp, &ssb) != -1) {
1677 			data->internal_file->flags = ssb.sb.st_mode & PHAR_ENT_PERM_MASK ;
1678 		} else {
1679 #ifndef _WIN32
1680 			mode_t mask;
1681 			mask = umask(0);
1682 			umask(mask);
1683 			data->internal_file->flags &= ~mask;
1684 #endif
1685 		}
1686 	}
1687 
1688 	if (close_fp) {
1689 		php_stream_close(fp);
1690 	}
1691 
1692 	add_assoc_str(p_obj->ret, str_key, opened);
1693 
1694 	if (save) {
1695 		efree(save);
1696 	}
1697 
1698 	if (temp) {
1699 		efree(temp);
1700 	}
1701 
1702 	data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len;
1703 	phar_entry_delref(data);
1704 
1705 	return ZEND_HASH_APPLY_KEEP;
1706 }
1707 /* }}} */
1708 
1709 /* {{{ Construct a phar archive from an existing directory, recursively.
1710  * Optional second parameter is a regular expression for filtering directory contents.
1711  *
1712  * Return value is an array mapping phar index to actual files added.
1713  */
PHP_METHOD(Phar,buildFromDirectory)1714 PHP_METHOD(Phar, buildFromDirectory)
1715 {
1716 	char *error;
1717 	bool apply_reg = 0;
1718 	zval arg, arg2, iter, iteriter, regexiter;
1719 	struct _phar_t pass;
1720 	zend_string *dir, *regex = NULL;
1721 
1722 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|S", &dir, &regex) == FAILURE) {
1723 		RETURN_THROWS();
1724 	}
1725 
1726 	PHAR_ARCHIVE_OBJECT();
1727 
1728 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
1729 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1730 			"Cannot write to archive - write operations restricted by INI setting");
1731 		RETURN_THROWS();
1732 	}
1733 
1734 	if (SUCCESS != object_init_ex(&iter, spl_ce_RecursiveDirectoryIterator)) {
1735 		zval_ptr_dtor(&iter);
1736 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname);
1737 		RETURN_THROWS();
1738 	}
1739 
1740 	ZVAL_STR(&arg, dir);
1741 	ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
1742 
1743 	zend_call_known_instance_method_with_2_params(spl_ce_RecursiveDirectoryIterator->constructor,
1744 		Z_OBJ(iter), NULL, &arg, &arg2);
1745 
1746 	if (EG(exception)) {
1747 		zval_ptr_dtor(&iter);
1748 		RETURN_THROWS();
1749 	}
1750 
1751 	if (SUCCESS != object_init_ex(&iteriter, spl_ce_RecursiveIteratorIterator)) {
1752 		zval_ptr_dtor(&iter);
1753 		zval_ptr_dtor(&iteriter);
1754 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname);
1755 		RETURN_THROWS();
1756 	}
1757 
1758 	zend_call_known_instance_method_with_1_params(spl_ce_RecursiveIteratorIterator->constructor,
1759 		Z_OBJ(iteriter), NULL, &iter);
1760 
1761 	if (EG(exception)) {
1762 		zval_ptr_dtor(&iter);
1763 		zval_ptr_dtor(&iteriter);
1764 		RETURN_THROWS();
1765 	}
1766 
1767 	zval_ptr_dtor(&iter);
1768 
1769 	if (regex && ZSTR_LEN(regex) > 0) {
1770 		apply_reg = 1;
1771 
1772 		if (SUCCESS != object_init_ex(&regexiter, spl_ce_RegexIterator)) {
1773 			zval_ptr_dtor(&iteriter);
1774 			zval_ptr_dtor(&regexiter);
1775 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate regex iterator for %s", phar_obj->archive->fname);
1776 			RETURN_THROWS();
1777 		}
1778 
1779 		ZVAL_STR(&arg2, regex);
1780 		zend_call_known_instance_method_with_2_params(spl_ce_RegexIterator->constructor,
1781 			Z_OBJ(regexiter), NULL, &iteriter, &arg2);
1782 	}
1783 
1784 	array_init(return_value);
1785 
1786 	pass.c = apply_reg ? Z_OBJCE(regexiter) : Z_OBJCE(iteriter);
1787 	pass.p = phar_obj;
1788 	pass.base = dir;
1789 	pass.count = 0;
1790 	pass.ret = return_value;
1791 	pass.fp = php_stream_fopen_tmpfile();
1792 	if (pass.fp == NULL) {
1793 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" unable to create temporary file", phar_obj->archive->fname);
1794 		RETURN_THROWS();
1795 	}
1796 
1797 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
1798 		zval_ptr_dtor(&iteriter);
1799 		if (apply_reg) {
1800 			zval_ptr_dtor(&regexiter);
1801 		}
1802 		php_stream_close(pass.fp);
1803 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
1804 		RETURN_THROWS();
1805 	}
1806 
1807 	if (SUCCESS == spl_iterator_apply((apply_reg ? &regexiter : &iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass)) {
1808 		zval_ptr_dtor(&iteriter);
1809 
1810 		if (apply_reg) {
1811 			zval_ptr_dtor(&regexiter);
1812 		}
1813 
1814 		phar_obj->archive->ufp = pass.fp;
1815 		phar_flush(phar_obj->archive, &error);
1816 
1817 		if (error) {
1818 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
1819 			efree(error);
1820 		}
1821 
1822 	} else {
1823 		zval_ptr_dtor(&iteriter);
1824 		if (apply_reg) {
1825 			zval_ptr_dtor(&regexiter);
1826 		}
1827 		php_stream_close(pass.fp);
1828 	}
1829 }
1830 /* }}} */
1831 
1832 /* {{{ Construct a phar archive from an iterator.  The iterator must return a series of strings
1833  * that are full paths to files that should be added to the phar.  The iterator key should
1834  * be the path that the file will have within the phar archive.
1835  *
1836  * If base directory is specified, then the key will be ignored, and instead the portion of
1837  * the current value minus the base directory will be used
1838  *
1839  * Returned is an array mapping phar index to actual file added
1840  */
PHP_METHOD(Phar,buildFromIterator)1841 PHP_METHOD(Phar, buildFromIterator)
1842 {
1843 	zval *obj;
1844 	char *error;
1845 	zend_string *base = ZSTR_EMPTY_ALLOC();
1846 	struct _phar_t pass;
1847 
1848 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|S!", &obj, zend_ce_traversable, &base) == FAILURE) {
1849 		RETURN_THROWS();
1850 	}
1851 
1852 	PHAR_ARCHIVE_OBJECT();
1853 
1854 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
1855 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1856 			"Cannot write out phar archive, phar is read-only");
1857 		RETURN_THROWS();
1858 	}
1859 
1860 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
1861 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
1862 		RETURN_THROWS();
1863 	}
1864 
1865 	array_init(return_value);
1866 
1867 	pass.c = Z_OBJCE_P(obj);
1868 	pass.p = phar_obj;
1869 	pass.base = base;
1870 	pass.ret = return_value;
1871 	pass.count = 0;
1872 	pass.fp = php_stream_fopen_tmpfile();
1873 	if (pass.fp == NULL) {
1874 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\": unable to create temporary file", phar_obj->archive->fname);
1875 		RETURN_THROWS();
1876 	}
1877 
1878 	if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass)) {
1879 		phar_obj->archive->ufp = pass.fp;
1880 		phar_flush(phar_obj->archive, &error);
1881 		if (error) {
1882 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
1883 			efree(error);
1884 		}
1885 	} else {
1886 		php_stream_close(pass.fp);
1887 	}
1888 }
1889 /* }}} */
1890 
1891 /* {{{ Returns the number of entries in the Phar archive */
PHP_METHOD(Phar,count)1892 PHP_METHOD(Phar, count)
1893 {
1894 	/* mode can be ignored, maximum depth is 1 */
1895 	zend_long mode;
1896 
1897 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &mode) == FAILURE) {
1898 		RETURN_THROWS();
1899 	}
1900 
1901 	PHAR_ARCHIVE_OBJECT();
1902 
1903 	RETURN_LONG(zend_hash_num_elements(&phar_obj->archive->manifest));
1904 }
1905 /* }}} */
1906 
1907 /* {{{ Returns true if the phar archive is based on the tar/zip/phar file format depending
1908  * on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in
1909  */
PHP_METHOD(Phar,isFileFormat)1910 PHP_METHOD(Phar, isFileFormat)
1911 {
1912 	zend_long type;
1913 
1914 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &type) == FAILURE) {
1915 		RETURN_THROWS();
1916 	}
1917 
1918 	PHAR_ARCHIVE_OBJECT();
1919 
1920 	switch (type) {
1921 		case PHAR_FORMAT_TAR:
1922 			RETURN_BOOL(phar_obj->archive->is_tar);
1923 		case PHAR_FORMAT_ZIP:
1924 			RETURN_BOOL(phar_obj->archive->is_zip);
1925 		case PHAR_FORMAT_PHAR:
1926 			RETURN_BOOL(!phar_obj->archive->is_tar && !phar_obj->archive->is_zip);
1927 		default:
1928 			zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown file format specified");
1929 	}
1930 }
1931 /* }}} */
1932 
phar_copy_file_contents(phar_entry_info * entry,php_stream * fp)1933 static zend_result phar_copy_file_contents(phar_entry_info *entry, php_stream *fp) /* {{{ */
1934 {
1935 	char *error;
1936 	zend_off_t offset;
1937 	phar_entry_info *link;
1938 
1939 	if (FAILURE == phar_open_entry_fp(entry, &error, 1)) {
1940 		if (error) {
1941 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1942 				"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents: %s", entry->phar->fname, entry->filename, error);
1943 			efree(error);
1944 		} else {
1945 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1946 				"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents", entry->phar->fname, entry->filename);
1947 		}
1948 		return FAILURE;
1949 	}
1950 
1951 	/* copy old contents in entirety */
1952 	phar_seek_efp(entry, 0, SEEK_SET, 0, 1);
1953 	offset = php_stream_tell(fp);
1954 	link = phar_get_link_source(entry);
1955 
1956 	if (!link) {
1957 		link = entry;
1958 	}
1959 
1960 	if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(link, 0), fp, link->uncompressed_filesize, NULL)) {
1961 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1962 			"Cannot convert phar archive \"%s\", unable to copy entry \"%s\" contents", entry->phar->fname, entry->filename);
1963 		return FAILURE;
1964 	}
1965 
1966 	if (entry->fp_type == PHAR_MOD) {
1967 		/* save for potential restore on error */
1968 		entry->cfp = entry->fp;
1969 		entry->fp = NULL;
1970 	}
1971 
1972 	/* set new location of file contents */
1973 	entry->fp_type = PHAR_FP;
1974 	entry->offset = offset;
1975 	return SUCCESS;
1976 }
1977 /* }}} */
1978 
phar_rename_archive(phar_archive_data ** sphar,char * ext)1979 static zend_object *phar_rename_archive(phar_archive_data **sphar, char *ext) /* {{{ */
1980 {
1981 	const char *oldname = NULL;
1982 	phar_archive_data *phar = *sphar;
1983 	char *oldpath = NULL;
1984 	char *basename = NULL, *basepath = NULL;
1985 	char *newname = NULL, *newpath = NULL;
1986 	zval ret, arg1;
1987 	zend_class_entry *ce;
1988 	char *error = NULL;
1989 	const char *pcr_error;
1990 	size_t ext_len = ext ? strlen(ext) : 0;
1991 	size_t new_len, oldname_len, phar_ext_len;
1992 	phar_archive_data *pphar = NULL;
1993 	php_stream_statbuf ssb;
1994 
1995 	int phar_ext_list_len, i = 0;
1996 	char *ext_pos = NULL;
1997 	/* Array of PHAR extensions, Must be in order, starting with longest
1998 	 * ending with the shortest. */
1999 	static const char *const phar_ext_list[] = {
2000 		".phar.tar.bz2",
2001 		".phar.tar.gz",
2002 		".phar.php",
2003 		".phar.bz2",
2004 		".phar.zip",
2005 		".phar.tar",
2006 		".phar.gz",
2007 		".tar.bz2",
2008 		".tar.gz",
2009 		".phar",
2010 		".tar",
2011 		".zip"
2012 	};
2013 
2014 	if (!ext) {
2015 		if (phar->is_zip) {
2016 
2017 			if (phar->is_data) {
2018 				ext = "zip";
2019 			} else {
2020 				ext = "phar.zip";
2021 			}
2022 
2023 		} else if (phar->is_tar) {
2024 
2025 			switch (phar->flags) {
2026 				case PHAR_FILE_COMPRESSED_GZ:
2027 					if (phar->is_data) {
2028 						ext = "tar.gz";
2029 					} else {
2030 						ext = "phar.tar.gz";
2031 					}
2032 					break;
2033 				case PHAR_FILE_COMPRESSED_BZ2:
2034 					if (phar->is_data) {
2035 						ext = "tar.bz2";
2036 					} else {
2037 						ext = "phar.tar.bz2";
2038 					}
2039 					break;
2040 				default:
2041 					if (phar->is_data) {
2042 						ext = "tar";
2043 					} else {
2044 						ext = "phar.tar";
2045 					}
2046 			}
2047 		} else {
2048 
2049 			switch (phar->flags) {
2050 				case PHAR_FILE_COMPRESSED_GZ:
2051 					ext = "phar.gz";
2052 					break;
2053 				case PHAR_FILE_COMPRESSED_BZ2:
2054 					ext = "phar.bz2";
2055 					break;
2056 				default:
2057 					ext = "phar";
2058 			}
2059 		}
2060 	} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {
2061 
2062 		if (phar->is_data) {
2063 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
2064 		} else {
2065 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
2066 		}
2067 		return NULL;
2068 	}
2069 
2070 
2071 	oldpath = estrndup(phar->fname, phar->fname_len);
2072 	if ((oldname = zend_memrchr(phar->fname, '/', phar->fname_len))) {
2073 		++oldname;
2074 	} else {
2075 		oldname = phar->fname;
2076 	}
2077 
2078 	oldname_len = strlen(oldname);
2079 	/* Copy the old name to create base for the new name */
2080 	basename = estrndup(oldname, oldname_len);
2081 
2082 	phar_ext_list_len = sizeof(phar_ext_list)/sizeof(phar_ext_list[0]);
2083 	/* Remove possible PHAR extensions */
2084 	/* phar_ext_list must be in order of longest extension to shortest */
2085 	for (i=0; i < phar_ext_list_len; i++) {
2086 		phar_ext_len = strlen(phar_ext_list[i]);
2087 		if (phar_ext_len && oldname_len > phar_ext_len) {
2088 			/* Check if the basename strings ends with the extension */
2089 			if (memcmp(phar_ext_list[i], basename + (oldname_len - phar_ext_len), phar_ext_len) == 0) {
2090 				ext_pos = basename + (oldname_len - phar_ext_len);
2091 				ext_pos[0] = '\0';
2092 				break;
2093 			}
2094 		}
2095 		ext_pos = NULL;
2096 	}
2097 
2098 	/* If no default PHAR extension found remove the last extension */
2099 	if (!ext_pos) {
2100 		ext_pos = strrchr(basename, '.');
2101 		if (ext_pos) {
2102 			ext_pos[0] = '\0';
2103 		}
2104 	}
2105 	ext_pos = NULL;
2106 
2107 	if (ext[0] == '.') {
2108 		++ext;
2109 	}
2110 	/* Append extension to the basename */
2111 	spprintf(&newname, 0, "%s.%s", basename, ext);
2112 	efree(basename);
2113 
2114 	basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));
2115 	new_len = spprintf(&newpath, 0, "%s%s", basepath, newname);
2116 	phar->fname_len = new_len;
2117 	phar->fname = newpath;
2118 	phar->ext = newpath + phar->fname_len - strlen(ext) - 1;
2119 	efree(basepath);
2120 	efree(newname);
2121 
2122 	if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, newpath, phar->fname_len))) {
2123 		efree(oldpath);
2124 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname);
2125 		return NULL;
2126 	}
2127 
2128 	if (NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), newpath, phar->fname_len))) {
2129 		if (pphar->fname_len == phar->fname_len && !memcmp(pphar->fname, phar->fname, phar->fname_len)) {
2130 			if (!zend_hash_num_elements(&phar->manifest)) {
2131 				pphar->is_tar = phar->is_tar;
2132 				pphar->is_zip = phar->is_zip;
2133 				pphar->is_data = phar->is_data;
2134 				pphar->flags = phar->flags;
2135 				pphar->fp = phar->fp;
2136 				phar->fp = NULL;
2137 				/* FIX: GH-10755 Double-free issue caught by ASAN check */
2138 				pphar->alias = phar->alias; /* Transfer alias to pphar to */
2139 				phar->alias = NULL;         /* avoid being free'd twice   */
2140 				phar_destroy_phar_data(phar);
2141 				*sphar = NULL;
2142 				phar = pphar;
2143 				newpath = oldpath;
2144 				goto its_ok;
2145 			}
2146 		}
2147 
2148 		efree(oldpath);
2149 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname);
2150 		return NULL;
2151 	}
2152 its_ok:
2153 	if (SUCCESS == php_stream_stat_path(newpath, &ssb)) {
2154 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar \"%s\" exists and must be unlinked prior to conversion", newpath);
2155 		efree(oldpath);
2156 		return NULL;
2157 	}
2158 	if (!phar->is_data) {
2159 		if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &ext_len, 1, 1, 1)) {
2160 			efree(oldpath);
2161 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar \"%s\" has invalid extension %s", phar->fname, ext);
2162 			return NULL;
2163 		}
2164 		phar->ext_len = ext_len;
2165 
2166 		if (phar->alias) {
2167 			if (phar->is_temporary_alias) {
2168 				phar->alias = NULL;
2169 				phar->alias_len = 0;
2170 			} else {
2171 				phar->alias = estrndup(newpath, strlen(newpath));
2172 				phar->alias_len = strlen(newpath);
2173 				phar->is_temporary_alias = 1;
2174 				zend_hash_str_update_ptr(&(PHAR_G(phar_alias_map)), newpath, phar->fname_len, phar);
2175 			}
2176 		}
2177 
2178 	} else {
2179 
2180 		if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &ext_len, 0, 1, 1)) {
2181 			efree(oldpath);
2182 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "data phar \"%s\" has invalid extension %s", phar->fname, ext);
2183 			return NULL;
2184 		}
2185 		phar->ext_len = ext_len;
2186 
2187 		phar->alias = NULL;
2188 		phar->alias_len = 0;
2189 	}
2190 
2191 	if ((!pphar || phar == pphar) && NULL == zend_hash_str_update_ptr(&(PHAR_G(phar_fname_map)), newpath, phar->fname_len, phar)) {
2192 		efree(oldpath);
2193 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname);
2194 		return NULL;
2195 	}
2196 
2197 	phar_flush_ex(phar, NULL, 1, &error);
2198 
2199 	if (error) {
2200 		zend_hash_str_del(&(PHAR_G(phar_fname_map)), newpath, phar->fname_len);
2201 		*sphar = NULL;
2202 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "%s", error);
2203 		efree(error);
2204 		efree(oldpath);
2205 		return NULL;
2206 	}
2207 
2208 	efree(oldpath);
2209 
2210 	if (phar->is_data) {
2211 		ce = phar_ce_data;
2212 	} else {
2213 		ce = phar_ce_archive;
2214 	}
2215 
2216 	ZVAL_NULL(&ret);
2217 	if (SUCCESS != object_init_ex(&ret, ce)) {
2218 		zval_ptr_dtor(&ret);
2219 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname);
2220 		return NULL;
2221 	}
2222 
2223 	ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len);
2224 
2225 	zend_call_known_instance_method_with_1_params(ce->constructor, Z_OBJ(ret), NULL, &arg1);
2226 	zval_ptr_dtor(&arg1);
2227 	return Z_OBJ(ret);
2228 }
2229 /* }}} */
2230 
phar_convert_to_other(phar_archive_data * source,int convert,char * ext,uint32_t flags)2231 static zend_object *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, uint32_t flags) /* {{{ */
2232 {
2233 	phar_archive_data *phar;
2234 	phar_entry_info *entry, newentry;
2235 	zend_object *ret;
2236 
2237 	/* invalidate phar cache */
2238 	PHAR_G(last_phar) = NULL;
2239 	PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
2240 
2241 	phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data));
2242 	/* set whole-archive compression and type from parameter */
2243 	phar->flags = flags;
2244 	phar->is_data = source->is_data;
2245 
2246 	switch (convert) {
2247 		case PHAR_FORMAT_TAR:
2248 			phar->is_tar = 1;
2249 			break;
2250 		case PHAR_FORMAT_ZIP:
2251 			phar->is_zip = 1;
2252 			break;
2253 		default:
2254 			phar->is_data = 0;
2255 			break;
2256 	}
2257 
2258 	zend_hash_init(&(phar->manifest), sizeof(phar_entry_info),
2259 		zend_get_hash_value, destroy_phar_manifest_entry, 0);
2260 	zend_hash_init(&phar->mounted_dirs, sizeof(char *),
2261 		zend_get_hash_value, NULL, 0);
2262 	zend_hash_init(&phar->virtual_dirs, sizeof(char *),
2263 		zend_get_hash_value, NULL, 0);
2264 
2265 	phar->fp = php_stream_fopen_tmpfile();
2266 	if (phar->fp == NULL) {
2267 		zend_throw_exception_ex(phar_ce_PharException, 0, "unable to create temporary file");
2268 		return NULL;
2269 	}
2270 	phar->fname = source->fname;
2271 	phar->fname_len = source->fname_len;
2272 	phar->is_temporary_alias = source->is_temporary_alias;
2273 	phar->alias = source->alias;
2274 
2275 	phar_metadata_tracker_copy(&phar->metadata_tracker, &source->metadata_tracker, phar->is_persistent);
2276 
2277 	/* first copy each file's uncompressed contents to a temporary file and set per-file flags */
2278 	ZEND_HASH_MAP_FOREACH_PTR(&source->manifest, entry) {
2279 
2280 		newentry = *entry;
2281 
2282 		if (newentry.link) {
2283 			newentry.link = estrdup(newentry.link);
2284 			goto no_copy;
2285 		}
2286 
2287 		if (newentry.tmp) {
2288 			newentry.tmp = estrdup(newentry.tmp);
2289 			goto no_copy;
2290 		}
2291 
2292 		if (FAILURE == phar_copy_file_contents(&newentry, phar->fp)) {
2293 			zend_hash_destroy(&(phar->manifest));
2294 			php_stream_close(phar->fp);
2295 			efree(phar);
2296 			/* exception already thrown */
2297 			return NULL;
2298 		}
2299 no_copy:
2300 		newentry.filename = estrndup(newentry.filename, newentry.filename_len);
2301 
2302 		phar_metadata_tracker_clone(&newentry.metadata_tracker);
2303 
2304 		newentry.is_zip = phar->is_zip;
2305 		newentry.is_tar = phar->is_tar;
2306 
2307 		if (newentry.is_tar) {
2308 			newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE);
2309 		}
2310 
2311 		newentry.is_modified = 1;
2312 		newentry.phar = phar;
2313 		newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; /* remove compression from old_flags */
2314 		phar_set_inode(&newentry);
2315 		zend_hash_str_add_mem(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info));
2316 		phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len);
2317 	} ZEND_HASH_FOREACH_END();
2318 
2319 	if ((ret = phar_rename_archive(&phar, ext))) {
2320 		return ret;
2321 	} else {
2322 		if(phar != NULL) {
2323 			zend_hash_destroy(&(phar->manifest));
2324 			zend_hash_destroy(&(phar->mounted_dirs));
2325 			zend_hash_destroy(&(phar->virtual_dirs));
2326 			if (phar->fp) {
2327 				php_stream_close(phar->fp);
2328 			}
2329 			efree(phar->fname);
2330 			efree(phar);
2331 		}
2332 		return NULL;
2333 	}
2334 }
2335 /* }}} */
2336 
2337 /* {{{ Convert a phar.tar or phar.zip archive to the phar file format. The
2338  * optional parameter allows the user to determine the new
2339  * filename extension (default is phar).
2340  */
PHP_METHOD(Phar,convertToExecutable)2341 PHP_METHOD(Phar, convertToExecutable)
2342 {
2343 	char *ext = NULL;
2344 	int is_data;
2345 	size_t ext_len = 0;
2346 	uint32_t flags;
2347 	zend_object *ret;
2348 	zend_long format, method;
2349 	bool format_is_null = 1, method_is_null = 1;
2350 
2351 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!l!s!", &format, &format_is_null, &method, &method_is_null, &ext, &ext_len) == FAILURE) {
2352 		RETURN_THROWS();
2353 	}
2354 
2355 	PHAR_ARCHIVE_OBJECT();
2356 
2357 	if (PHAR_G(readonly)) {
2358 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2359 			"Cannot write out executable phar archive, phar is read-only");
2360 		RETURN_THROWS();
2361 	}
2362 
2363 	if (format_is_null) {
2364 		format = PHAR_FORMAT_SAME;
2365 	}
2366 	switch (format) {
2367 		case 9021976: /* Retained for BC */
2368 		case PHAR_FORMAT_SAME:
2369 			/* by default, use the existing format */
2370 			if (phar_obj->archive->is_tar) {
2371 				format = PHAR_FORMAT_TAR;
2372 			} else if (phar_obj->archive->is_zip) {
2373 				format = PHAR_FORMAT_ZIP;
2374 			} else {
2375 				format = PHAR_FORMAT_PHAR;
2376 			}
2377 			break;
2378 		case PHAR_FORMAT_PHAR:
2379 		case PHAR_FORMAT_TAR:
2380 		case PHAR_FORMAT_ZIP:
2381 			break;
2382 		default:
2383 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2384 				"Unknown file format specified, please pass one of Phar::PHAR, Phar::TAR or Phar::ZIP");
2385 			RETURN_THROWS();
2386 	}
2387 
2388 	if (method_is_null) {
2389 		flags = phar_obj->archive->flags & PHAR_FILE_COMPRESSION_MASK;
2390 	} else {
2391 		switch (method) {
2392 		case 9021976: /* Retained for BC */
2393 			flags = phar_obj->archive->flags & PHAR_FILE_COMPRESSION_MASK;
2394 			break;
2395 		case 0:
2396 			flags = PHAR_FILE_COMPRESSED_NONE;
2397 			break;
2398 		case PHAR_ENT_COMPRESSED_GZ:
2399 			if (format == PHAR_FORMAT_ZIP) {
2400 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2401 					"Cannot compress entire archive with gzip, zip archives do not support whole-archive compression");
2402 				RETURN_THROWS();
2403 			}
2404 
2405 			if (!PHAR_G(has_zlib)) {
2406 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2407 					"Cannot compress entire archive with gzip, enable ext/zlib in php.ini");
2408 				RETURN_THROWS();
2409 			}
2410 
2411 			flags = PHAR_FILE_COMPRESSED_GZ;
2412 			break;
2413 		case PHAR_ENT_COMPRESSED_BZ2:
2414 			if (format == PHAR_FORMAT_ZIP) {
2415 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2416 					"Cannot compress entire archive with bz2, zip archives do not support whole-archive compression");
2417 				RETURN_THROWS();
2418 			}
2419 
2420 			if (!PHAR_G(has_bz2)) {
2421 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2422 					"Cannot compress entire archive with bz2, enable ext/bz2 in php.ini");
2423 				RETURN_THROWS();
2424 			}
2425 
2426 			flags = PHAR_FILE_COMPRESSED_BZ2;
2427 			break;
2428 		default:
2429 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2430 				"Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2");
2431 			RETURN_THROWS();
2432 		}
2433 	}
2434 
2435 	is_data = phar_obj->archive->is_data;
2436 	phar_obj->archive->is_data = 0;
2437 	ret = phar_convert_to_other(phar_obj->archive, format, ext, flags);
2438 	phar_obj->archive->is_data = is_data;
2439 
2440 	if (ret) {
2441 		RETURN_OBJ(ret);
2442 	} else {
2443 		RETURN_NULL();
2444 	}
2445 }
2446 /* }}} */
2447 
2448 /* {{{ Convert an archive to a non-executable .tar or .zip.
2449  * The optional parameter allows the user to determine the new
2450  * filename extension (default is .zip or .tar).
2451  */
PHP_METHOD(Phar,convertToData)2452 PHP_METHOD(Phar, convertToData)
2453 {
2454 	char *ext = NULL;
2455 	int is_data;
2456 	size_t ext_len = 0;
2457 	uint32_t flags;
2458 	zend_object *ret;
2459 	zend_long format, method;
2460 	bool format_is_null = 1, method_is_null = 1;
2461 
2462 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!l!s!", &format, &format_is_null, &method, &method_is_null, &ext, &ext_len) == FAILURE) {
2463 		RETURN_THROWS();
2464 	}
2465 
2466 	PHAR_ARCHIVE_OBJECT();
2467 
2468 	if (format_is_null) {
2469 		format = PHAR_FORMAT_SAME;
2470 	}
2471 	switch (format) {
2472 		case 9021976: /* Retained for BC */
2473 		case PHAR_FORMAT_SAME:
2474 			/* by default, use the existing format */
2475 			if (phar_obj->archive->is_tar) {
2476 				format = PHAR_FORMAT_TAR;
2477 			} else if (phar_obj->archive->is_zip) {
2478 				format = PHAR_FORMAT_ZIP;
2479 			} else {
2480 				zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2481 					"Cannot write out data phar archive, use Phar::TAR or Phar::ZIP");
2482 				RETURN_THROWS();
2483 			}
2484 			break;
2485 		case PHAR_FORMAT_PHAR:
2486 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2487 				"Cannot write out data phar archive, use Phar::TAR or Phar::ZIP");
2488 			RETURN_THROWS();
2489 		case PHAR_FORMAT_TAR:
2490 		case PHAR_FORMAT_ZIP:
2491 			break;
2492 		default:
2493 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2494 				"Unknown file format specified, please pass one of Phar::TAR or Phar::ZIP");
2495 			RETURN_THROWS();
2496 	}
2497 
2498 	if (method_is_null) {
2499 		flags = phar_obj->archive->flags & PHAR_FILE_COMPRESSION_MASK;
2500 	} else  {
2501 		switch (method) {
2502 		case 9021976: /* Retained for BC */
2503 			flags = phar_obj->archive->flags & PHAR_FILE_COMPRESSION_MASK;
2504 			break;
2505 		case 0:
2506 			flags = PHAR_FILE_COMPRESSED_NONE;
2507 			break;
2508 		case PHAR_ENT_COMPRESSED_GZ:
2509 			if (format == PHAR_FORMAT_ZIP) {
2510 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2511 					"Cannot compress entire archive with gzip, zip archives do not support whole-archive compression");
2512 				RETURN_THROWS();
2513 			}
2514 
2515 			if (!PHAR_G(has_zlib)) {
2516 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2517 					"Cannot compress entire archive with gzip, enable ext/zlib in php.ini");
2518 				RETURN_THROWS();
2519 			}
2520 
2521 			flags = PHAR_FILE_COMPRESSED_GZ;
2522 			break;
2523 		case PHAR_ENT_COMPRESSED_BZ2:
2524 			if (format == PHAR_FORMAT_ZIP) {
2525 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2526 					"Cannot compress entire archive with bz2, zip archives do not support whole-archive compression");
2527 				RETURN_THROWS();
2528 			}
2529 
2530 			if (!PHAR_G(has_bz2)) {
2531 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2532 					"Cannot compress entire archive with bz2, enable ext/bz2 in php.ini");
2533 				RETURN_THROWS();
2534 			}
2535 
2536 			flags = PHAR_FILE_COMPRESSED_BZ2;
2537 			break;
2538 		default:
2539 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2540 				"Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2");
2541 			RETURN_THROWS();
2542 		}
2543 	}
2544 
2545 	is_data = phar_obj->archive->is_data;
2546 	phar_obj->archive->is_data = 1;
2547 	ret = phar_convert_to_other(phar_obj->archive, (int)format, ext, flags);
2548 	phar_obj->archive->is_data = is_data;
2549 
2550 	if (ret) {
2551 		RETURN_OBJ(ret);
2552 	} else {
2553 		RETURN_NULL();
2554 	}
2555 }
2556 /* }}} */
2557 
2558 /* {{{ Returns Phar::GZ or PHAR::BZ2 if the entire archive is compressed
2559  * (.tar.gz/tar.bz2 and so on), or FALSE otherwise.
2560  */
PHP_METHOD(Phar,isCompressed)2561 PHP_METHOD(Phar, isCompressed)
2562 {
2563 	if (zend_parse_parameters_none() == FAILURE) {
2564 		RETURN_THROWS();
2565 	}
2566 
2567 	PHAR_ARCHIVE_OBJECT();
2568 
2569 	if (phar_obj->archive->flags & PHAR_FILE_COMPRESSED_GZ) {
2570 		RETURN_LONG(PHAR_ENT_COMPRESSED_GZ);
2571 	}
2572 
2573 	if (phar_obj->archive->flags & PHAR_FILE_COMPRESSED_BZ2) {
2574 		RETURN_LONG(PHAR_ENT_COMPRESSED_BZ2);
2575 	}
2576 
2577 	RETURN_FALSE;
2578 }
2579 /* }}} */
2580 
2581 /* {{{ Returns true if phar.readonly=0 or phar is a PharData AND the actual file is writable. */
PHP_METHOD(Phar,isWritable)2582 PHP_METHOD(Phar, isWritable)
2583 {
2584 	php_stream_statbuf ssb;
2585 
2586 	if (zend_parse_parameters_none() == FAILURE) {
2587 		RETURN_THROWS();
2588 	}
2589 
2590 	PHAR_ARCHIVE_OBJECT();
2591 
2592 	if (!phar_obj->archive->is_writeable) {
2593 		RETURN_FALSE;
2594 	}
2595 
2596 	if (SUCCESS != php_stream_stat_path(phar_obj->archive->fname, &ssb)) {
2597 		if (phar_obj->archive->is_brandnew) {
2598 			/* assume it works if the file doesn't exist yet */
2599 			RETURN_TRUE;
2600 		}
2601 		RETURN_FALSE;
2602 	}
2603 
2604 	RETURN_BOOL((ssb.sb.st_mode & (S_IWOTH | S_IWGRP | S_IWUSR)) != 0);
2605 }
2606 /* }}} */
2607 
2608 /* {{{ Deletes a named file within the archive. */
PHP_METHOD(Phar,delete)2609 PHP_METHOD(Phar, delete)
2610 {
2611 	zend_string *file_name;
2612 	char *error;
2613 	phar_entry_info *entry;
2614 
2615 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "P", &file_name) == FAILURE) {
2616 		RETURN_THROWS();
2617 	}
2618 
2619 	PHAR_ARCHIVE_OBJECT();
2620 
2621 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
2622 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2623 			"Cannot write out phar archive, phar is read-only");
2624 		RETURN_THROWS();
2625 	}
2626 
2627 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
2628 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
2629 		RETURN_THROWS();
2630 	}
2631 	if (NULL != (entry = zend_hash_find_ptr(&phar_obj->archive->manifest, file_name))) {
2632 		if (entry->is_deleted) {
2633 			/* entry is deleted, but has not been flushed to disk yet */
2634 			RETURN_TRUE;
2635 		} else {
2636 			entry->is_deleted = 1;
2637 			entry->is_modified = 1;
2638 			phar_obj->archive->is_modified = 1;
2639 		}
2640 	} else {
2641 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", ZSTR_VAL(file_name));
2642 		RETURN_THROWS();
2643 	}
2644 
2645 	phar_flush(phar_obj->archive, &error);
2646 	if (error) {
2647 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
2648 		efree(error);
2649 		RETURN_THROWS();
2650 	}
2651 
2652 	RETURN_TRUE;
2653 }
2654 /* }}} */
2655 
2656 /* {{{ Returns the alias for the Phar or NULL. */
PHP_METHOD(Phar,getAlias)2657 PHP_METHOD(Phar, getAlias)
2658 {
2659 	if (zend_parse_parameters_none() == FAILURE) {
2660 		RETURN_THROWS();
2661 	}
2662 
2663 	PHAR_ARCHIVE_OBJECT();
2664 
2665 	if (phar_obj->archive->alias && phar_obj->archive->alias != phar_obj->archive->fname) {
2666 		RETURN_STRINGL(phar_obj->archive->alias, phar_obj->archive->alias_len);
2667 	}
2668 }
2669 /* }}} */
2670 
2671 /* {{{ Returns the real path to the phar archive on disk */
PHP_METHOD(Phar,getPath)2672 PHP_METHOD(Phar, getPath)
2673 {
2674 	if (zend_parse_parameters_none() == FAILURE) {
2675 		RETURN_THROWS();
2676 	}
2677 
2678 	PHAR_ARCHIVE_OBJECT();
2679 
2680 	RETURN_STRINGL(phar_obj->archive->fname, phar_obj->archive->fname_len);
2681 }
2682 /* }}} */
2683 
2684 /* {{{ Sets the alias for a Phar archive. The default value is the full path
2685  * to the archive.
2686  */
PHP_METHOD(Phar,setAlias)2687 PHP_METHOD(Phar, setAlias)
2688 {
2689 	zend_string *new_alias = NULL;
2690 	char *error, *oldalias;
2691 	phar_archive_data *fd_ptr;
2692 	size_t oldalias_len;
2693 	int old_temp, readd = 0;
2694 
2695 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &new_alias) == FAILURE) {
2696 		RETURN_THROWS();
2697 	}
2698 
2699 	PHAR_ARCHIVE_OBJECT();
2700 
2701 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
2702 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2703 			"Cannot write out phar archive, phar is read-only");
2704 		RETURN_THROWS();
2705 	}
2706 
2707 	/* invalidate phar cache */
2708 	PHAR_G(last_phar) = NULL;
2709 	PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
2710 
2711 	if (phar_obj->archive->is_data) {
2712 		if (phar_obj->archive->is_tar) {
2713 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2714 				"A Phar alias cannot be set in a plain tar archive");
2715 		} else {
2716 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2717 				"A Phar alias cannot be set in a plain zip archive");
2718 		}
2719 		RETURN_THROWS();
2720 	}
2721 
2722 	if (zend_string_equals_cstr(new_alias, phar_obj->archive->alias, phar_obj->archive->alias_len)) {
2723 		RETURN_TRUE;
2724 	}
2725 	if (NULL != (fd_ptr = zend_hash_find_ptr(&(PHAR_G(phar_alias_map)), new_alias))) {
2726 		spprintf(&error, 0, "alias \"%s\" is already used for archive \"%s\" and cannot be used for other archives", ZSTR_VAL(new_alias), fd_ptr->fname);
2727 		if (SUCCESS == phar_free_alias(fd_ptr, ZSTR_VAL(new_alias), ZSTR_LEN(new_alias))) {
2728 			efree(error);
2729 			goto valid_alias;
2730 		}
2731 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
2732 		efree(error);
2733 		RETURN_THROWS();
2734 	}
2735 	if (!phar_validate_alias(ZSTR_VAL(new_alias), ZSTR_LEN(new_alias))) {
2736 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2737 			"Invalid alias \"%s\" specified for phar \"%s\"", ZSTR_VAL(new_alias), phar_obj->archive->fname);
2738 		RETURN_THROWS();
2739 	}
2740 valid_alias:
2741 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
2742 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
2743 		RETURN_THROWS();
2744 	}
2745 	if (phar_obj->archive->alias_len && NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), phar_obj->archive->alias, phar_obj->archive->alias_len))) {
2746 		zend_hash_str_del(&(PHAR_G(phar_alias_map)), phar_obj->archive->alias, phar_obj->archive->alias_len);
2747 		readd = 1;
2748 	}
2749 
2750 	oldalias = phar_obj->archive->alias;
2751 	oldalias_len = phar_obj->archive->alias_len;
2752 	old_temp = phar_obj->archive->is_temporary_alias;
2753 
2754 	phar_obj->archive->alias = estrndup(ZSTR_VAL(new_alias), ZSTR_LEN(new_alias));
2755 	phar_obj->archive->alias_len = ZSTR_LEN(new_alias);
2756 	phar_obj->archive->is_temporary_alias = 0;
2757 	phar_flush(phar_obj->archive, &error);
2758 
2759 	if (error) {
2760 		phar_obj->archive->alias = oldalias;
2761 		phar_obj->archive->alias_len = oldalias_len;
2762 		phar_obj->archive->is_temporary_alias = old_temp;
2763 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
2764 		if (readd) {
2765 			zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), oldalias, oldalias_len, phar_obj->archive);
2766 		}
2767 		efree(error);
2768 		RETURN_THROWS();
2769 	}
2770 
2771 	zend_hash_add_ptr(&(PHAR_G(phar_alias_map)), new_alias, phar_obj->archive);
2772 
2773 	if (oldalias) {
2774 		efree(oldalias);
2775 	}
2776 
2777 	RETURN_TRUE;
2778 }
2779 /* }}} */
2780 
2781 /* {{{ Return version info of Phar archive */
PHP_METHOD(Phar,getVersion)2782 PHP_METHOD(Phar, getVersion)
2783 {
2784 	if (zend_parse_parameters_none() == FAILURE) {
2785 		RETURN_THROWS();
2786 	}
2787 
2788 	PHAR_ARCHIVE_OBJECT();
2789 
2790 	RETURN_STRING(phar_obj->archive->version);
2791 }
2792 /* }}} */
2793 
2794 /* {{{ Do not flush a writeable phar (save its contents) until explicitly requested */
PHP_METHOD(Phar,startBuffering)2795 PHP_METHOD(Phar, startBuffering)
2796 {
2797 	if (zend_parse_parameters_none() == FAILURE) {
2798 		RETURN_THROWS();
2799 	}
2800 
2801 	PHAR_ARCHIVE_OBJECT();
2802 
2803 	phar_obj->archive->donotflush = 1;
2804 }
2805 /* }}} */
2806 
2807 /* {{{ Returns whether write operations are flushing to disk immediately. */
PHP_METHOD(Phar,isBuffering)2808 PHP_METHOD(Phar, isBuffering)
2809 {
2810 	if (zend_parse_parameters_none() == FAILURE) {
2811 		RETURN_THROWS();
2812 	}
2813 
2814 	PHAR_ARCHIVE_OBJECT();
2815 
2816 	RETURN_BOOL(phar_obj->archive->donotflush);
2817 }
2818 /* }}} */
2819 
2820 /* {{{ Saves the contents of a modified archive to disk. */
PHP_METHOD(Phar,stopBuffering)2821 PHP_METHOD(Phar, stopBuffering)
2822 {
2823 	char *error;
2824 
2825 	if (zend_parse_parameters_none() == FAILURE) {
2826 		RETURN_THROWS();
2827 	}
2828 
2829 	PHAR_ARCHIVE_OBJECT();
2830 
2831 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
2832 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2833 			"Cannot write out phar archive, phar is read-only");
2834 		RETURN_THROWS();
2835 	}
2836 
2837 	phar_obj->archive->donotflush = 0;
2838 	phar_flush(phar_obj->archive, &error);
2839 
2840 	if (error) {
2841 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
2842 		efree(error);
2843 	}
2844 }
2845 /* }}} */
2846 
2847 /* {{{ Change the stub in a phar, phar.tar or phar.zip archive to something other
2848  * than the default. The stub *must* end with a call to __HALT_COMPILER().
2849  */
PHP_METHOD(Phar,setStub)2850 PHP_METHOD(Phar, setStub)
2851 {
2852 	char *error;
2853 	zend_string *stub;
2854 	zval *zstub;
2855 	zend_long len = -1;
2856 	php_stream *stream;
2857 
2858 	PHAR_ARCHIVE_OBJECT();
2859 
2860 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
2861 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2862 			"Cannot change stub, phar is read-only");
2863 		RETURN_THROWS();
2864 	}
2865 
2866 	if (phar_obj->archive->is_data) {
2867 		if (phar_obj->archive->is_tar) {
2868 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2869 				"A Phar stub cannot be set in a plain tar archive");
2870 		} else {
2871 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2872 				"A Phar stub cannot be set in a plain zip archive");
2873 		}
2874 		RETURN_THROWS();
2875 	}
2876 
2877 	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r|l", &zstub, &len) == SUCCESS) {
2878 		zend_string *method_name = get_active_function_or_method_name();
2879 		zend_error(E_DEPRECATED, "Calling %s(resource $stub, int $length) is deprecated", ZSTR_VAL(method_name));
2880 		zend_string_release(method_name);
2881 		if (UNEXPECTED(EG(exception))) {
2882 			RETURN_THROWS();
2883 		}
2884 
2885 		if ((php_stream_from_zval_no_verify(stream, zstub)) != NULL) {
2886 			if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
2887 				zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
2888 				RETURN_THROWS();
2889 			}
2890 
2891 			zend_string *stub_file_content = NULL;
2892 			if (len > 0) {
2893 				stub_file_content = php_stream_copy_to_mem(stream, len, false);
2894 			} else {
2895 				stub_file_content = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, false);
2896 			}
2897 
2898 			if (stub_file_content == NULL) {
2899 				zend_throw_exception_ex(phar_ce_PharException, 0, "unable to read resource to copy stub to new phar \"%s\"", phar_obj->archive->fname);
2900 				RETURN_THROWS();
2901 			}
2902 
2903 			phar_flush_ex(phar_obj->archive, stub_file_content, /* is_default_stub */ false, &error);
2904 			zend_string_release_ex(stub_file_content, false);
2905 
2906 			if (error) {
2907 				zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
2908 				efree(error);
2909 			}
2910 			RETURN_TRUE;
2911 		} else {
2912 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2913 				"Cannot change stub, unable to read from input stream");
2914 		}
2915 	} else if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &stub) == SUCCESS) {
2916 		if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
2917 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
2918 			RETURN_THROWS();
2919 		}
2920 		phar_flush_ex(phar_obj->archive, stub, /* is_default_stub */ false, &error);
2921 
2922 		if (error) {
2923 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
2924 			efree(error);
2925 			RETURN_THROWS();
2926 		}
2927 
2928 		RETURN_TRUE;
2929 	}
2930 
2931 	RETURN_THROWS();
2932 }
2933 /* }}} */
2934 
2935 /* {{{ In a pure phar archive, sets a stub that can be used to run the archive
2936  * regardless of whether the phar extension is available. The first parameter
2937  * is the CLI startup filename, which defaults to "index.php". The second
2938  * parameter is the web startup filename and also defaults to "index.php"
2939  * (falling back to CLI behaviour).
2940  * Both parameters are optional.
2941  * In a phar.zip or phar.tar archive, the default stub is used only to
2942  * identify the archive to the extension as a Phar object. This allows the
2943  * extension to treat phar.zip and phar.tar types as honorary phars. Since
2944  * files cannot be loaded via this kind of stub, no parameters are accepted
2945  * when the Phar object is zip- or tar-based.
2946  */
PHP_METHOD(Phar,setDefaultStub)2947 PHP_METHOD(Phar, setDefaultStub)
2948 {
2949 	char *index = NULL, *webindex = NULL, *error = NULL;
2950 	zend_string *stub = NULL;
2951 	size_t index_len = 0, webindex_len = 0;
2952 	int created_stub = 0;
2953 
2954 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!s!", &index, &index_len, &webindex, &webindex_len) == FAILURE) {
2955 		RETURN_THROWS();
2956 	}
2957 
2958 	PHAR_ARCHIVE_OBJECT();
2959 
2960 	if (phar_obj->archive->is_data) {
2961 		if (phar_obj->archive->is_tar) {
2962 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2963 				"A Phar stub cannot be set in a plain tar archive");
2964 		} else {
2965 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2966 				"A Phar stub cannot be set in a plain zip archive");
2967 		}
2968 		RETURN_THROWS();
2969 	}
2970 
2971 	if ((index || webindex) && (phar_obj->archive->is_tar || phar_obj->archive->is_zip)) {
2972 		zend_argument_value_error(index ? 1 : 2, "must be null for a tar- or zip-based phar stub, string given");
2973 		RETURN_THROWS();
2974 	}
2975 
2976 	if (PHAR_G(readonly)) {
2977 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2978 			"Cannot change stub: phar.readonly=1");
2979 		RETURN_THROWS();
2980 	}
2981 
2982 	if (!phar_obj->archive->is_tar && !phar_obj->archive->is_zip) {
2983 		stub = phar_create_default_stub(index, webindex, &error);
2984 
2985 		if (error) {
2986 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "%s", error);
2987 			efree(error);
2988 			if (stub) {
2989 				zend_string_free(stub);
2990 			}
2991 			RETURN_THROWS();
2992 		}
2993 
2994 		created_stub = 1;
2995 	}
2996 
2997 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
2998 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
2999 		RETURN_THROWS();
3000 	}
3001 	phar_flush_ex(phar_obj->archive, stub, /* is_default_stub */ true, &error);
3002 
3003 	if (created_stub) {
3004 		zend_string_free(stub);
3005 	}
3006 
3007 	if (error) {
3008 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3009 		efree(error);
3010 		RETURN_THROWS();
3011 	}
3012 
3013 	RETURN_TRUE;
3014 }
3015 /* }}} */
3016 
3017 /* {{{ Sets the signature algorithm for a phar and applies it. The signature
3018  * algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256,
3019  * Phar::SHA512, or Phar::OPENSSL. Note that zip- based phar archives
3020  * cannot support signatures.
3021  */
PHP_METHOD(Phar,setSignatureAlgorithm)3022 PHP_METHOD(Phar, setSignatureAlgorithm)
3023 {
3024 	zend_long algo;
3025 	char *error, *key = NULL;
3026 	size_t key_len = 0;
3027 
3028 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|s!", &algo, &key, &key_len) != SUCCESS) {
3029 		RETURN_THROWS();
3030 	}
3031 
3032 	PHAR_ARCHIVE_OBJECT();
3033 
3034 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3035 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3036 			"Cannot set signature algorithm, phar is read-only");
3037 		RETURN_THROWS();
3038 	}
3039 
3040 	switch (algo) {
3041 		case PHAR_SIG_SHA256:
3042 		case PHAR_SIG_SHA512:
3043 		case PHAR_SIG_MD5:
3044 		case PHAR_SIG_SHA1:
3045 		case PHAR_SIG_OPENSSL:
3046 		case PHAR_SIG_OPENSSL_SHA256:
3047 		case PHAR_SIG_OPENSSL_SHA512:
3048 			if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
3049 				zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
3050 				RETURN_THROWS();
3051 			}
3052 			phar_obj->archive->sig_flags = (uint32_t)algo;
3053 			phar_obj->archive->is_modified = 1;
3054 			PHAR_G(openssl_privatekey) = key;
3055 			PHAR_G(openssl_privatekey_len) = key_len;
3056 
3057 			phar_flush(phar_obj->archive, &error);
3058 			if (error) {
3059 				zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3060 				efree(error);
3061 			}
3062 			break;
3063 		default:
3064 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3065 				"Unknown signature algorithm specified");
3066 	}
3067 }
3068 /* }}} */
3069 
3070 /* {{{ Returns a hash signature, or FALSE if the archive is unsigned. */
PHP_METHOD(Phar,getSignature)3071 PHP_METHOD(Phar, getSignature)
3072 {
3073 	if (zend_parse_parameters_none() == FAILURE) {
3074 		RETURN_THROWS();
3075 	}
3076 
3077 	PHAR_ARCHIVE_OBJECT();
3078 
3079 	if (phar_obj->archive->signature) {
3080 		zend_string *unknown;
3081 
3082 		array_init(return_value);
3083 		add_assoc_stringl(return_value, "hash", phar_obj->archive->signature, phar_obj->archive->sig_len);
3084 		switch(phar_obj->archive->sig_flags) {
3085 			case PHAR_SIG_MD5:
3086 				add_assoc_string(return_value, "hash_type", "MD5");
3087 				break;
3088 			case PHAR_SIG_SHA1:
3089 				add_assoc_string(return_value, "hash_type", "SHA-1");
3090 				break;
3091 			case PHAR_SIG_SHA256:
3092 				add_assoc_string(return_value, "hash_type", "SHA-256");
3093 				break;
3094 			case PHAR_SIG_SHA512:
3095 				add_assoc_string(return_value, "hash_type", "SHA-512");
3096 				break;
3097 			case PHAR_SIG_OPENSSL:
3098 				add_assoc_string(return_value, "hash_type", "OpenSSL");
3099 				break;
3100 			case PHAR_SIG_OPENSSL_SHA256:
3101 				add_assoc_string(return_value, "hash_type", "OpenSSL_SHA256");
3102 				break;
3103 			case PHAR_SIG_OPENSSL_SHA512:
3104 				add_assoc_string(return_value, "hash_type", "OpenSSL_SHA512");
3105 				break;
3106 			default:
3107 				unknown = strpprintf(0, "Unknown (%u)", phar_obj->archive->sig_flags);
3108 				add_assoc_str(return_value, "hash_type", unknown);
3109 				break;
3110 		}
3111 	} else {
3112 		RETURN_FALSE;
3113 	}
3114 }
3115 /* }}} */
3116 
3117 /* {{{ Return whether phar was modified */
PHP_METHOD(Phar,getModified)3118 PHP_METHOD(Phar, getModified)
3119 {
3120 	if (zend_parse_parameters_none() == FAILURE) {
3121 		RETURN_THROWS();
3122 	}
3123 
3124 	PHAR_ARCHIVE_OBJECT();
3125 
3126 	RETURN_BOOL(phar_obj->archive->is_modified);
3127 }
3128 /* }}} */
3129 
phar_set_compression(zval * zv,void * argument)3130 static int phar_set_compression(zval *zv, void *argument) /* {{{ */
3131 {
3132 	phar_entry_info *entry = (phar_entry_info *)Z_PTR_P(zv);
3133 	uint32_t compress = *(uint32_t *)argument;
3134 
3135 	if (entry->is_deleted) {
3136 		return ZEND_HASH_APPLY_KEEP;
3137 	}
3138 
3139 	entry->old_flags = entry->flags;
3140 	entry->flags &= ~PHAR_ENT_COMPRESSION_MASK;
3141 	entry->flags |= compress;
3142 	entry->is_modified = 1;
3143 	return ZEND_HASH_APPLY_KEEP;
3144 }
3145 /* }}} */
3146 
phar_test_compression(zval * zv,void * argument)3147 static int phar_test_compression(zval *zv, void *argument) /* {{{ */
3148 {
3149 	phar_entry_info *entry = (phar_entry_info *)Z_PTR_P(zv);
3150 
3151 	if (entry->is_deleted) {
3152 		return ZEND_HASH_APPLY_KEEP;
3153 	}
3154 
3155 	if (!PHAR_G(has_bz2)) {
3156 		if (entry->flags & PHAR_ENT_COMPRESSED_BZ2) {
3157 			*(int *) argument = 0;
3158 		}
3159 	}
3160 
3161 	if (!PHAR_G(has_zlib)) {
3162 		if (entry->flags & PHAR_ENT_COMPRESSED_GZ) {
3163 			*(int *) argument = 0;
3164 		}
3165 	}
3166 
3167 	return ZEND_HASH_APPLY_KEEP;
3168 }
3169 /* }}} */
3170 
pharobj_set_compression(HashTable * manifest,uint32_t compress)3171 static void pharobj_set_compression(HashTable *manifest, uint32_t compress) /* {{{ */
3172 {
3173 	zend_hash_apply_with_argument(manifest, phar_set_compression, &compress);
3174 }
3175 /* }}} */
3176 
pharobj_cancompress(HashTable * manifest)3177 static int pharobj_cancompress(HashTable *manifest) /* {{{ */
3178 {
3179 	int test;
3180 
3181 	test = 1;
3182 	zend_hash_apply_with_argument(manifest, phar_test_compression, &test);
3183 	return test;
3184 }
3185 /* }}} */
3186 
3187 /* {{{ Compress a .tar, or .phar.tar with whole-file compression
3188  * The parameter can be one of Phar::GZ or Phar::BZ2 to specify
3189  * the kind of compression desired
3190  */
PHP_METHOD(Phar,compress)3191 PHP_METHOD(Phar, compress)
3192 {
3193 	zend_long method;
3194 	char *ext = NULL;
3195 	size_t ext_len = 0;
3196 	uint32_t flags;
3197 	zend_object *ret;
3198 
3199 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|s!", &method, &ext, &ext_len) == FAILURE) {
3200 		RETURN_THROWS();
3201 	}
3202 
3203 	PHAR_ARCHIVE_OBJECT();
3204 
3205 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3206 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3207 			"Cannot compress phar archive, phar is read-only");
3208 		RETURN_THROWS();
3209 	}
3210 
3211 	if (phar_obj->archive->is_zip) {
3212 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3213 			"Cannot compress zip-based archives with whole-archive compression");
3214 		RETURN_THROWS();
3215 	}
3216 
3217 	switch (method) {
3218 		case 0:
3219 			flags = PHAR_FILE_COMPRESSED_NONE;
3220 			break;
3221 		case PHAR_ENT_COMPRESSED_GZ:
3222 			if (!PHAR_G(has_zlib)) {
3223 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3224 					"Cannot compress entire archive with gzip, enable ext/zlib in php.ini");
3225 				RETURN_THROWS();
3226 			}
3227 			flags = PHAR_FILE_COMPRESSED_GZ;
3228 			break;
3229 
3230 		case PHAR_ENT_COMPRESSED_BZ2:
3231 			if (!PHAR_G(has_bz2)) {
3232 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3233 					"Cannot compress entire archive with bz2, enable ext/bz2 in php.ini");
3234 				return;
3235 			}
3236 			flags = PHAR_FILE_COMPRESSED_BZ2;
3237 			break;
3238 		default:
3239 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3240 				"Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2");
3241 			RETURN_THROWS();
3242 	}
3243 
3244 	if (phar_obj->archive->is_tar) {
3245 		ret = phar_convert_to_other(phar_obj->archive, PHAR_FORMAT_TAR, ext, flags);
3246 	} else {
3247 		ret = phar_convert_to_other(phar_obj->archive, PHAR_FORMAT_PHAR, ext, flags);
3248 	}
3249 
3250 	if (ret) {
3251 		RETURN_OBJ(ret);
3252 	} else {
3253 		RETURN_NULL();
3254 	}
3255 }
3256 /* }}} */
3257 
3258 /* {{{ Decompress a .tar, or .phar.tar with whole-file compression */
PHP_METHOD(Phar,decompress)3259 PHP_METHOD(Phar, decompress)
3260 {
3261 	char *ext = NULL;
3262 	size_t ext_len = 0;
3263 	zend_object *ret;
3264 
3265 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!", &ext, &ext_len) == FAILURE) {
3266 		RETURN_THROWS();
3267 	}
3268 
3269 	PHAR_ARCHIVE_OBJECT();
3270 
3271 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3272 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3273 			"Cannot decompress phar archive, phar is read-only");
3274 		RETURN_THROWS();
3275 	}
3276 
3277 	if (phar_obj->archive->is_zip) {
3278 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3279 			"Cannot decompress zip-based archives with whole-archive compression");
3280 		RETURN_THROWS();
3281 	}
3282 
3283 	if (phar_obj->archive->is_tar) {
3284 		ret = phar_convert_to_other(phar_obj->archive, PHAR_FORMAT_TAR, ext, PHAR_FILE_COMPRESSED_NONE);
3285 	} else {
3286 		ret = phar_convert_to_other(phar_obj->archive, PHAR_FORMAT_PHAR, ext, PHAR_FILE_COMPRESSED_NONE);
3287 	}
3288 
3289 	if (ret) {
3290 		RETURN_OBJ(ret);
3291 	} else {
3292 		RETURN_NULL();
3293 	}
3294 }
3295 /* }}} */
3296 
3297 /* {{{ Compress all files within a phar or zip archive using the specified compression
3298  * The parameter can be one of Phar::GZ or Phar::BZ2 to specify
3299  * the kind of compression desired
3300  */
PHP_METHOD(Phar,compressFiles)3301 PHP_METHOD(Phar, compressFiles)
3302 {
3303 	char *error;
3304 	uint32_t flags;
3305 	zend_long method;
3306 
3307 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &method) == FAILURE) {
3308 		RETURN_THROWS();
3309 	}
3310 
3311 	PHAR_ARCHIVE_OBJECT();
3312 
3313 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3314 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3315 			"Phar is readonly, cannot change compression");
3316 		RETURN_THROWS();
3317 	}
3318 
3319 	switch (method) {
3320 		case PHAR_ENT_COMPRESSED_GZ:
3321 			if (!PHAR_G(has_zlib)) {
3322 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3323 					"Cannot compress files within archive with gzip, enable ext/zlib in php.ini");
3324 				RETURN_THROWS();
3325 			}
3326 			flags = PHAR_ENT_COMPRESSED_GZ;
3327 			break;
3328 
3329 		case PHAR_ENT_COMPRESSED_BZ2:
3330 			if (!PHAR_G(has_bz2)) {
3331 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3332 					"Cannot compress files within archive with bz2, enable ext/bz2 in php.ini");
3333 				RETURN_THROWS();
3334 			}
3335 			flags = PHAR_ENT_COMPRESSED_BZ2;
3336 			break;
3337 		default:
3338 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3339 				"Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2");
3340 			RETURN_THROWS();
3341 	}
3342 
3343 	if (phar_obj->archive->is_tar) {
3344 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3345 			"Cannot compress with Gzip compression, tar archives cannot compress individual files, use compress() to compress the whole archive");
3346 		RETURN_THROWS();
3347 	}
3348 
3349 	if (!pharobj_cancompress(&phar_obj->archive->manifest)) {
3350 		if (flags == PHAR_ENT_COMPRESSED_GZ) {
3351 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3352 				"Cannot compress all files as Gzip, some are compressed as bzip2 and cannot be decompressed");
3353 		} else {
3354 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3355 				"Cannot compress all files as Bzip2, some are compressed as gzip and cannot be decompressed");
3356 		}
3357 		RETURN_THROWS();
3358 	}
3359 
3360 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
3361 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
3362 		RETURN_THROWS();
3363 	}
3364 	pharobj_set_compression(&phar_obj->archive->manifest, flags);
3365 	phar_obj->archive->is_modified = 1;
3366 	phar_flush(phar_obj->archive, &error);
3367 
3368 	if (error) {
3369 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "%s", error);
3370 		efree(error);
3371 	}
3372 }
3373 /* }}} */
3374 
3375 /* {{{ decompress every file */
PHP_METHOD(Phar,decompressFiles)3376 PHP_METHOD(Phar, decompressFiles)
3377 {
3378 	char *error;
3379 
3380 	if (zend_parse_parameters_none() == FAILURE) {
3381 		RETURN_THROWS();
3382 
3383 	}
3384 
3385 	PHAR_ARCHIVE_OBJECT();
3386 
3387 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3388 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3389 			"Phar is readonly, cannot change compression");
3390 		RETURN_THROWS();
3391 	}
3392 
3393 	if (!pharobj_cancompress(&phar_obj->archive->manifest)) {
3394 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3395 			"Cannot decompress all files, some are compressed as bzip2 or gzip and cannot be decompressed");
3396 		RETURN_THROWS();
3397 	}
3398 
3399 	if (phar_obj->archive->is_tar) {
3400 		RETURN_TRUE;
3401 	} else {
3402 		if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
3403 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
3404 			RETURN_THROWS();
3405 		}
3406 		pharobj_set_compression(&phar_obj->archive->manifest, PHAR_ENT_COMPRESSED_NONE);
3407 	}
3408 
3409 	phar_obj->archive->is_modified = 1;
3410 	phar_flush(phar_obj->archive, &error);
3411 
3412 	if (error) {
3413 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "%s", error);
3414 		efree(error);
3415 	}
3416 
3417 	RETURN_TRUE;
3418 }
3419 /* }}} */
3420 
3421 /* {{{ copy a file internal to the phar archive to another new file within the phar */
PHP_METHOD(Phar,copy)3422 PHP_METHOD(Phar, copy)
3423 {
3424 	char *error;
3425 	const char *pcr_error;
3426 	phar_entry_info *oldentry, newentry = {0}, *temp;
3427 	zend_string *new_file = NULL;
3428 	zend_string *old_file = NULL;
3429 
3430 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "PP", &old_file, &new_file) == FAILURE) {
3431 		RETURN_THROWS();
3432 	}
3433 
3434 	PHAR_ARCHIVE_OBJECT();
3435 
3436 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3437 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3438 			"Cannot copy \"%s\" to \"%s\", phar is read-only", ZSTR_VAL(old_file), ZSTR_VAL(new_file));
3439 		RETURN_THROWS();
3440 	}
3441 
3442 	if (zend_string_starts_with_literal(old_file, ".phar")) {
3443 		/* can't copy a meta file */
3444 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3445 			"file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", ZSTR_VAL(old_file), ZSTR_VAL(new_file), phar_obj->archive->fname);
3446 		RETURN_THROWS();
3447 	}
3448 
3449 	if (zend_string_starts_with_literal(new_file, ".phar")) {
3450 		/* can't copy a meta file */
3451 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3452 			"file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", ZSTR_VAL(old_file), ZSTR_VAL(new_file), phar_obj->archive->fname);
3453 		RETURN_THROWS();
3454 	}
3455 
3456 	if (NULL == (oldentry = zend_hash_find_ptr(&phar_obj->archive->manifest, old_file)) || oldentry->is_deleted) {
3457 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3458 			"file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", ZSTR_VAL(old_file), ZSTR_VAL(new_file), phar_obj->archive->fname);
3459 		RETURN_THROWS();
3460 	}
3461 
3462 	if (NULL != (temp = zend_hash_find_ptr(&phar_obj->archive->manifest, new_file)) && !temp->is_deleted) {
3463 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3464 			"file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", ZSTR_VAL(old_file), ZSTR_VAL(new_file), phar_obj->archive->fname);
3465 		RETURN_THROWS();
3466 	}
3467 
3468 	size_t tmp_len = ZSTR_LEN(new_file);
3469 	char *tmp_new_file = ZSTR_VAL(new_file);
3470 	if (phar_path_check(&tmp_new_file, &tmp_len, &pcr_error) > pcr_is_ok) {
3471 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3472 				"file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", ZSTR_VAL(new_file), pcr_error, ZSTR_VAL(old_file), phar_obj->archive->fname);
3473 		RETURN_THROWS();
3474 	}
3475 
3476 	if (phar_obj->archive->is_persistent) {
3477 		if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
3478 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
3479 			RETURN_THROWS();
3480 		}
3481 		/* re-populate with copied-on-write entry */
3482 		oldentry = zend_hash_find_ptr(&phar_obj->archive->manifest, old_file);
3483 	}
3484 
3485 	memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info));
3486 
3487 	phar_metadata_tracker_clone(&newentry.metadata_tracker);
3488 
3489 	newentry.filename = estrndup(tmp_new_file, tmp_len);
3490 	newentry.filename_len = tmp_len;
3491 	newentry.fp_refcount = 0;
3492 
3493 	if (oldentry->fp_type != PHAR_FP) {
3494 		if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error)) {
3495 			efree(newentry.filename);
3496 			php_stream_close(newentry.fp);
3497 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3498 			efree(error);
3499 			RETURN_THROWS();
3500 		}
3501 	}
3502 
3503 	zend_hash_str_add_mem(&oldentry->phar->manifest, ZSTR_VAL(new_file), tmp_len, &newentry, sizeof(phar_entry_info));
3504 	phar_obj->archive->is_modified = 1;
3505 	phar_flush(phar_obj->archive, &error);
3506 
3507 	if (error) {
3508 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3509 		efree(error);
3510 	}
3511 
3512 	RETURN_TRUE;
3513 }
3514 /* }}} */
3515 
3516 /* {{{ determines whether a file exists in the phar */
PHP_METHOD(Phar,offsetExists)3517 PHP_METHOD(Phar, offsetExists)
3518 {
3519 	zend_string *file_name;
3520 	phar_entry_info *entry;
3521 
3522 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "P", &file_name) == FAILURE) {
3523 		RETURN_THROWS();
3524 	}
3525 
3526 	PHAR_ARCHIVE_OBJECT();
3527 
3528 	if (zend_hash_exists(&phar_obj->archive->manifest, file_name)) {
3529 		if (NULL != (entry = zend_hash_find_ptr(&phar_obj->archive->manifest, file_name))) {
3530 			if (entry->is_deleted) {
3531 				/* entry is deleted, but has not been flushed to disk yet */
3532 				RETURN_FALSE;
3533 			}
3534 		}
3535 
3536 		if (zend_string_starts_with_literal(file_name, ".phar")) {
3537 			/* none of these are real files, so they don't exist */
3538 			RETURN_FALSE;
3539 		}
3540 		RETURN_TRUE;
3541 	} else {
3542 		/* If the info class is not based on PharFileInfo, directories are not directly instantiable */
3543 		if (UNEXPECTED(!instanceof_function(phar_obj->spl.info_class, phar_ce_entry))) {
3544 			RETURN_FALSE;
3545 		}
3546 		RETURN_BOOL(zend_hash_exists(&phar_obj->archive->virtual_dirs, file_name));
3547 	}
3548 }
3549 /* }}} */
3550 
3551 /* {{{ get a PharFileInfo object for a specific file */
PHP_METHOD(Phar,offsetGet)3552 PHP_METHOD(Phar, offsetGet)
3553 {
3554 	char *error;
3555 	phar_entry_info *entry;
3556 	zend_string *file_name = NULL;
3557 
3558 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "P", &file_name) == FAILURE) {
3559 		RETURN_THROWS();
3560 	}
3561 
3562 	PHAR_ARCHIVE_OBJECT();
3563 
3564 	/* security is 0 here so that we can get a better error message than "entry doesn't exist" */
3565 	if (!(entry = phar_get_entry_info_dir(phar_obj->archive, ZSTR_VAL(file_name), ZSTR_LEN(file_name), 1, &error, 0))) {
3566 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist%s%s", ZSTR_VAL(file_name), error?", ":"", error?error:"");
3567 	} else {
3568 		if (zend_string_equals_literal(file_name, ".phar/stub.php")) {
3569 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get stub \".phar/stub.php\" directly in phar \"%s\", use getStub", phar_obj->archive->fname);
3570 			RETURN_THROWS();
3571 		}
3572 
3573 		if (zend_string_equals_literal(file_name, ".phar/alias.txt")) {
3574 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get alias \".phar/alias.txt\" directly in phar \"%s\", use getAlias", phar_obj->archive->fname);
3575 			RETURN_THROWS();
3576 		}
3577 
3578 		if (zend_string_starts_with_literal(file_name, ".phar")) {
3579 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot directly get any files or directories in magic \".phar\" directory");
3580 			RETURN_THROWS();
3581 		}
3582 
3583 		if (entry->is_temp_dir) {
3584 			efree(entry->filename);
3585 			efree(entry);
3586 		}
3587 
3588 		zend_string *sfname = strpprintf(0, "phar://%s/%s", phar_obj->archive->fname, ZSTR_VAL(file_name));
3589 		zval zfname;
3590 		ZVAL_NEW_STR(&zfname, sfname);
3591 
3592 		/* Instantiate object and call constructor */
3593 		zend_result is_initialized = object_init_with_constructor(return_value, phar_obj->spl.info_class, 1, &zfname, NULL);
3594 		zval_ptr_dtor(&zfname);
3595 		if (is_initialized == FAILURE) {
3596 			RETURN_THROWS();
3597 		}
3598 	}
3599 }
3600 /* }}} */
3601 
3602 /* {{{ add a file within the phar archive from a string or resource */
phar_add_file(phar_archive_data ** pphar,zend_string * file_name,const zend_string * content,zval * zresource)3603 static void phar_add_file(phar_archive_data **pphar, zend_string *file_name, const zend_string *content, zval *zresource)
3604 {
3605 	char *error;
3606 	phar_entry_data *data;
3607 	php_stream *contents_file = NULL;
3608 	php_stream_statbuf ssb;
3609 #ifdef PHP_WIN32
3610 	char *save_filename;
3611 	ALLOCA_FLAG(filename_use_heap)
3612 #endif
3613 
3614 	if (
3615 		zend_string_starts_with_literal(file_name, ".phar")
3616 		|| zend_string_starts_with_literal(file_name, "/.phar")
3617 	) {
3618 		size_t prefix_len = (ZSTR_VAL(file_name)[0] == '/') + sizeof(".phar")-1;
3619 		char next_char = ZSTR_VAL(file_name)[prefix_len];
3620 		if (next_char == '/' || next_char == '\\' || next_char == '\0') {
3621 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot create any files in magic \".phar\" directory");
3622 			return;
3623 		}
3624 	}
3625 
3626 	/* TODO How to handle Windows path normalisation with zend_string ? */
3627 	char *filename = ZSTR_VAL(file_name);
3628 	size_t filename_len = ZSTR_LEN(file_name);
3629 #ifdef PHP_WIN32
3630 	save_filename = filename;
3631 	if (memchr(filename, '\\', filename_len)) {
3632 		filename = do_alloca(filename_len + 1, filename_use_heap);
3633 		memcpy(filename, save_filename, filename_len);
3634 		filename[filename_len] = '\0';
3635 	}
3636 #endif
3637 
3638 	if (!(data = phar_get_or_create_entry_data((*pphar)->fname, (*pphar)->fname_len, filename, filename_len, "w+b", 0, &error, 1))) {
3639 		if (error) {
3640 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be created: %s", filename, error);
3641 			efree(error);
3642 		} else {
3643 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be created", filename);
3644 		}
3645 		goto finish;
3646 	} else {
3647 		if (error) {
3648 			efree(error);
3649 		}
3650 
3651 		if (!data->internal_file->is_dir) {
3652 			size_t contents_len = 0;
3653 			if (content) {
3654 				contents_len = ZSTR_LEN(content);
3655 				size_t written_len = php_stream_write(data->fp, ZSTR_VAL(content), ZSTR_LEN(content));
3656 				if (written_len != contents_len) {
3657 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s could not be written to", filename);
3658 					goto finish;
3659 				}
3660 			} else {
3661 				if (!(php_stream_from_zval_no_verify(contents_file, zresource))) {
3662 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s could not be written to", filename);
3663 					goto finish;
3664 				}
3665 				php_stream_copy_to_stream_ex(contents_file, data->fp, PHP_STREAM_COPY_ALL, &contents_len);
3666 			}
3667 			data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len;
3668 		}
3669 
3670 		if (contents_file != NULL && php_stream_stat(contents_file, &ssb) != -1) {
3671 			data->internal_file->flags = ssb.sb.st_mode & PHAR_ENT_PERM_MASK ;
3672 		} else {
3673 #ifndef _WIN32
3674 			mode_t mask;
3675 			mask = umask(0);
3676 			umask(mask);
3677 			data->internal_file->flags &= ~mask;
3678 #endif
3679 		}
3680 
3681 		/* check for copy-on-write */
3682 		if (pphar[0] != data->phar) {
3683 			*pphar = data->phar;
3684 		}
3685 		phar_entry_delref(data);
3686 		phar_flush(*pphar, &error);
3687 
3688 		if (error) {
3689 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3690 			efree(error);
3691 		}
3692 	}
3693 
3694 finish: ;
3695 #ifdef PHP_WIN32
3696 	if (filename != save_filename) {
3697 		free_alloca(filename, filename_use_heap);
3698 		filename = save_filename;
3699 	}
3700 #endif
3701 }
3702 /* }}} */
3703 
3704 /* {{{ create a directory within the phar archive */
phar_mkdir(phar_archive_data ** pphar,zend_string * dir_name)3705 static void phar_mkdir(phar_archive_data **pphar, zend_string *dir_name)
3706 {
3707 	char *error;
3708 	phar_entry_data *data;
3709 
3710 	if (!(data = phar_get_or_create_entry_data((*pphar)->fname, (*pphar)->fname_len, ZSTR_VAL(dir_name), ZSTR_LEN(dir_name), "w+b", 2, &error, 1))) {
3711 		if (error) {
3712 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Directory %s does not exist and cannot be created: %s", ZSTR_VAL(dir_name), error);
3713 			efree(error);
3714 		} else {
3715 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Directory %s does not exist and cannot be created", ZSTR_VAL(dir_name));
3716 		}
3717 
3718 		return;
3719 	} else {
3720 		if (error) {
3721 			efree(error);
3722 		}
3723 
3724 		/* check for copy on write */
3725 		if (data->phar != *pphar) {
3726 			*pphar = data->phar;
3727 		}
3728 		phar_entry_delref(data);
3729 		phar_flush(*pphar, &error);
3730 
3731 		if (error) {
3732 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3733 			efree(error);
3734 		}
3735 	}
3736 }
3737 /* }}} */
3738 
3739 /* {{{ set the contents of an internal file to those of an external file */
PHP_METHOD(Phar,offsetSet)3740 PHP_METHOD(Phar, offsetSet)
3741 {
3742 	zval *zresource = NULL;
3743 	zend_string *file_name = NULL;
3744 	zend_string *file_content = NULL;
3745 
3746 	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "Pr", &file_name, &zresource) == FAILURE
3747 	&& zend_parse_parameters(ZEND_NUM_ARGS(), "PS", &file_name, &file_content) == FAILURE) {
3748 		RETURN_THROWS();
3749 	}
3750 
3751 	PHAR_ARCHIVE_OBJECT();
3752 
3753 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3754 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
3755 		RETURN_THROWS();
3756 	}
3757 
3758 	if (zend_string_equals_literal(file_name, ".phar/stub.php")) {
3759 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname);
3760 		RETURN_THROWS();
3761 	}
3762 
3763 	if (zend_string_equals_literal(file_name, ".phar/alias.txt")) {
3764 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname);
3765 		RETURN_THROWS();
3766 	}
3767 
3768 	if (zend_string_starts_with_literal(file_name, ".phar")) {
3769 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory");
3770 		RETURN_THROWS();
3771 	}
3772 
3773 	phar_add_file(&(phar_obj->archive), file_name, file_content, zresource);
3774 }
3775 /* }}} */
3776 
3777 /* {{{ remove a file from a phar */
PHP_METHOD(Phar,offsetUnset)3778 PHP_METHOD(Phar, offsetUnset)
3779 {
3780 	char *error;
3781 	zend_string *file_name;
3782 	phar_entry_info *entry;
3783 
3784 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "P", &file_name) == FAILURE) {
3785 		RETURN_THROWS();
3786 	}
3787 
3788 	PHAR_ARCHIVE_OBJECT();
3789 
3790 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3791 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
3792 		RETURN_THROWS();
3793 	}
3794 
3795 	if (zend_hash_exists(&phar_obj->archive->manifest, file_name)) {
3796 		if (NULL != (entry = zend_hash_find_ptr(&phar_obj->archive->manifest, file_name))) {
3797 			if (entry->is_deleted) {
3798 				/* entry is deleted, but has not been flushed to disk yet */
3799 				return;
3800 			}
3801 
3802 			if (phar_obj->archive->is_persistent) {
3803 				if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
3804 					zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
3805 					RETURN_THROWS();
3806 				}
3807 				/* re-populate entry after copy on write */
3808 				entry = zend_hash_find_ptr(&phar_obj->archive->manifest, file_name);
3809 			}
3810 			entry->is_modified = 0;
3811 			entry->is_deleted = 1;
3812 			/* we need to "flush" the stream to save the newly deleted file on disk */
3813 			phar_flush(phar_obj->archive, &error);
3814 
3815 			if (error) {
3816 				zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3817 				efree(error);
3818 			}
3819 		}
3820 	}
3821 }
3822 /* }}} */
3823 
3824 /* {{{ Adds an empty directory to the phar archive */
PHP_METHOD(Phar,addEmptyDir)3825 PHP_METHOD(Phar, addEmptyDir)
3826 {
3827 	zend_string *dir_name;
3828 
3829 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "P", &dir_name) == FAILURE) {
3830 		RETURN_THROWS();
3831 	}
3832 
3833 	PHAR_ARCHIVE_OBJECT();
3834 
3835 	if (zend_string_starts_with_literal(dir_name, ".phar")) {
3836 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot create a directory in magic \".phar\" directory");
3837 		RETURN_THROWS();
3838 	}
3839 
3840 	phar_mkdir(&phar_obj->archive, dir_name);
3841 }
3842 /* }}} */
3843 
3844 /* {{{ Adds a file to the archive using the filename, or the second parameter as the name within the archive */
PHP_METHOD(Phar,addFile)3845 PHP_METHOD(Phar, addFile)
3846 {
3847 	zend_string *file_name;
3848 	zend_string *local_name = NULL;
3849 	php_stream *resource;
3850 	zval zresource;
3851 
3852 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|S!", &file_name, &local_name) == FAILURE) {
3853 		RETURN_THROWS();
3854 	}
3855 
3856 	PHAR_ARCHIVE_OBJECT();
3857 
3858 	if (!strstr(ZSTR_VAL(file_name), "://") && php_check_open_basedir(ZSTR_VAL(file_name))) {
3859 		zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", ZSTR_VAL(file_name));
3860 		RETURN_THROWS();
3861 	}
3862 
3863 	if (!(resource = php_stream_open_wrapper(ZSTR_VAL(file_name), "rb", 0, NULL))) {
3864 		zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive", ZSTR_VAL(file_name));
3865 		RETURN_THROWS();
3866 	}
3867 
3868 	if (local_name) {
3869 		file_name = local_name;
3870 	}
3871 
3872 	php_stream_to_zval(resource, &zresource);
3873 	phar_add_file(&(phar_obj->archive), file_name, NULL, &zresource);
3874 	zval_ptr_dtor(&zresource);
3875 }
3876 /* }}} */
3877 
3878 /* {{{ Adds a file to the archive using its contents as a string */
PHP_METHOD(Phar,addFromString)3879 PHP_METHOD(Phar, addFromString)
3880 {
3881 	zend_string *local_name = NULL;
3882 	zend_string *file_content = NULL;
3883 
3884 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "PS", &local_name, &file_content) == FAILURE) {
3885 		RETURN_THROWS();
3886 	}
3887 
3888 	PHAR_ARCHIVE_OBJECT();
3889 
3890 	phar_add_file(&(phar_obj->archive), local_name, file_content, NULL);
3891 }
3892 /* }}} */
3893 
3894 /* {{{ Returns the stub at the head of a phar archive as a string. */
PHP_METHOD(Phar,getStub)3895 PHP_METHOD(Phar, getStub)
3896 {
3897 	size_t len;
3898 	zend_string *buf;
3899 	php_stream *fp;
3900 	php_stream_filter *filter = NULL;
3901 	phar_entry_info *stub;
3902 
3903 	if (zend_parse_parameters_none() == FAILURE) {
3904 		RETURN_THROWS();
3905 	}
3906 
3907 	PHAR_ARCHIVE_OBJECT();
3908 
3909 	if (phar_obj->archive->is_tar || phar_obj->archive->is_zip) {
3910 
3911 		if (NULL != (stub = zend_hash_str_find_ptr(&(phar_obj->archive->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1))) {
3912 			if (phar_obj->archive->fp && !phar_obj->archive->is_brandnew && !(stub->flags & PHAR_ENT_COMPRESSION_MASK)) {
3913 				fp = phar_obj->archive->fp;
3914 			} else {
3915 				if (!(fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", 0, NULL))) {
3916 					zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "phar error: unable to open phar \"%s\"", phar_obj->archive->fname);
3917 					RETURN_THROWS();
3918 				}
3919 				if (stub->flags & PHAR_ENT_COMPRESSION_MASK) {
3920 					char *filter_name;
3921 
3922 					if ((filter_name = phar_decompress_filter(stub, 0)) != NULL) {
3923 						filter = php_stream_filter_create(filter_name, NULL, php_stream_is_persistent(fp));
3924 					} else {
3925 						filter = NULL;
3926 					}
3927 					if (!filter) {
3928 						zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "phar error: unable to read stub of phar \"%s\" (cannot create %s filter)", phar_obj->archive->fname, phar_decompress_filter(stub, 1));
3929 						RETURN_THROWS();
3930 					}
3931 					php_stream_filter_append(&fp->readfilters, filter);
3932 				}
3933 			}
3934 
3935 			if (!fp)  {
3936 				zend_throw_exception_ex(spl_ce_RuntimeException, 0,
3937 					"Unable to read stub");
3938 				RETURN_THROWS();
3939 			}
3940 
3941 			php_stream_seek(fp, stub->offset_abs, SEEK_SET);
3942 			len = stub->uncompressed_filesize;
3943 			goto carry_on;
3944 		} else {
3945 			RETURN_EMPTY_STRING();
3946 		}
3947 	}
3948 	len = phar_obj->archive->halt_offset;
3949 
3950 	if (phar_obj->archive->fp && !phar_obj->archive->is_brandnew) {
3951 		fp = phar_obj->archive->fp;
3952 	} else {
3953 		fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", 0, NULL);
3954 	}
3955 
3956 	if (!fp)  {
3957 		zend_throw_exception_ex(spl_ce_RuntimeException, 0,
3958 			"Unable to read stub");
3959 		RETURN_THROWS();
3960 	}
3961 
3962 	php_stream_rewind(fp);
3963 carry_on:
3964 	buf = zend_string_alloc(len, 0);
3965 
3966 	if (len != php_stream_read(fp, ZSTR_VAL(buf), len)) {
3967 		if (fp != phar_obj->archive->fp) {
3968 			php_stream_close(fp);
3969 		}
3970 		zend_throw_exception_ex(spl_ce_RuntimeException, 0,
3971 			"Unable to read stub");
3972 		zend_string_release_ex(buf, 0);
3973 		RETURN_THROWS();
3974 	}
3975 
3976 	if (filter) {
3977 		php_stream_filter_flush(filter, 1);
3978 		php_stream_filter_remove(filter, 1);
3979 	}
3980 
3981 	if (fp != phar_obj->archive->fp) {
3982 		php_stream_close(fp);
3983 	}
3984 
3985 	ZSTR_VAL(buf)[len] = '\0';
3986 	ZSTR_LEN(buf) = len;
3987 	RETVAL_STR(buf);
3988 }
3989 /* }}}*/
3990 
3991 /* {{{ Returns TRUE if the phar has global metadata, FALSE otherwise. */
PHP_METHOD(Phar,hasMetadata)3992 PHP_METHOD(Phar, hasMetadata)
3993 {
3994 	if (zend_parse_parameters_none() == FAILURE) {
3995 		RETURN_THROWS();
3996 	}
3997 
3998 	PHAR_ARCHIVE_OBJECT();
3999 
4000 	RETURN_BOOL(phar_metadata_tracker_has_data(&phar_obj->archive->metadata_tracker, phar_obj->archive->is_persistent));
4001 }
4002 /* }}} */
4003 
4004 /* {{{ Returns the global metadata of the phar */
PHP_METHOD(Phar,getMetadata)4005 PHP_METHOD(Phar, getMetadata)
4006 {
4007 	HashTable *unserialize_options = NULL;
4008 	phar_metadata_tracker *tracker;
4009 
4010 	ZEND_PARSE_PARAMETERS_START(0, 1)
4011 		Z_PARAM_OPTIONAL
4012 		Z_PARAM_ARRAY_HT(unserialize_options)
4013 	ZEND_PARSE_PARAMETERS_END();
4014 
4015 	PHAR_ARCHIVE_OBJECT();
4016 
4017 	tracker = &phar_obj->archive->metadata_tracker;
4018 	if (phar_metadata_tracker_has_data(tracker, phar_obj->archive->is_persistent)) {
4019 		phar_metadata_tracker_unserialize_or_copy(tracker, return_value, phar_obj->archive->is_persistent, unserialize_options, "Phar::getMetadata");
4020 	}
4021 }
4022 /* }}} */
4023 
4024 /* {{{ Modifies the phar metadata or throws */
serialize_metadata_or_throw(phar_metadata_tracker * tracker,int persistent,zval * metadata)4025 static zend_result serialize_metadata_or_throw(phar_metadata_tracker *tracker, int persistent, zval *metadata)
4026 {
4027 	php_serialize_data_t metadata_hash;
4028 	smart_str main_metadata_str = {0};
4029 
4030 	PHP_VAR_SERIALIZE_INIT(metadata_hash);
4031 	php_var_serialize(&main_metadata_str, metadata, &metadata_hash);
4032 	PHP_VAR_SERIALIZE_DESTROY(metadata_hash);
4033 	if (EG(exception)) {
4034 		/* Serialization can throw. Don't overwrite the original value or original string. */
4035 		return FAILURE;
4036 	}
4037 
4038 	phar_metadata_tracker_free(tracker, persistent);
4039 	if (EG(exception)) {
4040 		/* Destructor can throw. */
4041 		zend_string_release(main_metadata_str.s);
4042 		return FAILURE;
4043 	}
4044 
4045 	if (tracker->str) {
4046 		zend_throw_exception_ex(phar_ce_PharException, 0, "Metadata unexpectedly changed during setMetadata()");
4047 		zend_string_release(main_metadata_str.s);
4048 		return FAILURE;
4049 	}
4050 	ZVAL_COPY(&tracker->val, metadata);
4051 	tracker->str = main_metadata_str.s;
4052 	return SUCCESS;
4053 }
4054 
4055 /* {{{ Sets the global metadata of the phar */
PHP_METHOD(Phar,setMetadata)4056 PHP_METHOD(Phar, setMetadata)
4057 {
4058 	char *error;
4059 	zval *metadata;
4060 
4061 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &metadata) == FAILURE) {
4062 		RETURN_THROWS();
4063 	}
4064 
4065 	PHAR_ARCHIVE_OBJECT();
4066 
4067 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
4068 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
4069 		RETURN_THROWS();
4070 	}
4071 
4072 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
4073 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
4074 		RETURN_THROWS();
4075 	}
4076 
4077 	ZEND_ASSERT(!phar_obj->archive->is_persistent); /* Should no longer be persistent */
4078 	if (serialize_metadata_or_throw(&phar_obj->archive->metadata_tracker, phar_obj->archive->is_persistent, metadata) != SUCCESS) {
4079 		RETURN_THROWS();
4080 	}
4081 
4082 	phar_obj->archive->is_modified = 1;
4083 	phar_flush(phar_obj->archive, &error);
4084 
4085 	if (error) {
4086 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
4087 		efree(error);
4088 	}
4089 }
4090 /* }}} */
4091 
4092 /* {{{ Deletes the global metadata of the phar */
PHP_METHOD(Phar,delMetadata)4093 PHP_METHOD(Phar, delMetadata)
4094 {
4095 	char *error;
4096 
4097 	if (zend_parse_parameters_none() == FAILURE) {
4098 		RETURN_THROWS();
4099 	}
4100 
4101 	PHAR_ARCHIVE_OBJECT();
4102 
4103 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
4104 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
4105 		RETURN_THROWS();
4106 	}
4107 
4108 	if (!phar_metadata_tracker_has_data(&phar_obj->archive->metadata_tracker, phar_obj->archive->is_persistent)) {
4109 		RETURN_TRUE;
4110 	}
4111 
4112 	phar_metadata_tracker_free(&phar_obj->archive->metadata_tracker, phar_obj->archive->is_persistent);
4113 	phar_obj->archive->is_modified = 1;
4114 	phar_flush(phar_obj->archive, &error);
4115 
4116 	if (error) {
4117 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
4118 		efree(error);
4119 		RETURN_THROWS();
4120 	} else {
4121 		RETURN_TRUE;
4122 	}
4123 }
4124 /* }}} */
4125 
phar_extract_file(bool overwrite,phar_entry_info * entry,char * dest,size_t dest_len,char ** error)4126 static zend_result phar_extract_file(bool overwrite, phar_entry_info *entry, char *dest, size_t dest_len, char **error) /* {{{ */
4127 {
4128 	php_stream_statbuf ssb;
4129 	size_t len;
4130 	php_stream *fp;
4131 	char *fullpath;
4132 	const char *slash;
4133 	mode_t mode;
4134 	cwd_state new_state;
4135 	char *filename;
4136 	size_t filename_len;
4137 
4138 	if (entry->is_mounted) {
4139 		/* silently ignore mounted entries */
4140 		return SUCCESS;
4141 	}
4142 
4143 	if (entry->filename_len >= sizeof(".phar")-1 && !memcmp(entry->filename, ".phar", sizeof(".phar")-1)) {
4144 		return SUCCESS;
4145 	}
4146 	/* strip .. from path and restrict it to be under dest directory */
4147 	new_state.cwd = (char*)emalloc(2);
4148 	new_state.cwd[0] = DEFAULT_SLASH;
4149 	new_state.cwd[1] = '\0';
4150 	new_state.cwd_length = 1;
4151 	if (virtual_file_ex(&new_state, entry->filename, NULL, CWD_EXPAND) != 0 ||
4152 			new_state.cwd_length <= 1) {
4153 		if (EINVAL == errno && entry->filename_len > 50) {
4154 			char *tmp = estrndup(entry->filename, 50);
4155 			spprintf(error, 4096, "Cannot extract \"%s...\" to \"%s...\", extracted filename is too long for filesystem", tmp, dest);
4156 			efree(tmp);
4157 		} else {
4158 			spprintf(error, 4096, "Cannot extract \"%s\", internal error", entry->filename);
4159 		}
4160 		efree(new_state.cwd);
4161 		return FAILURE;
4162 	}
4163 	filename = new_state.cwd + 1;
4164 	filename_len = new_state.cwd_length - 1;
4165 #ifdef PHP_WIN32
4166 	/* unixify the path back, otherwise non zip formats might be broken */
4167 	{
4168 		size_t cnt = 0;
4169 
4170 		do {
4171 			if ('\\' == filename[cnt]) {
4172 				filename[cnt] = '/';
4173 			}
4174 		} while (cnt++ < filename_len);
4175 	}
4176 #endif
4177 
4178 	len = spprintf(&fullpath, 0, "%s/%s", dest, filename);
4179 
4180 	if (len >= MAXPATHLEN) {
4181 		char *tmp;
4182 		/* truncate for error message */
4183 		fullpath[50] = '\0';
4184 		if (entry->filename_len > 50) {
4185 			tmp = estrndup(entry->filename, 50);
4186 			spprintf(error, 4096, "Cannot extract \"%s...\" to \"%s...\", extracted filename is too long for filesystem", tmp, fullpath);
4187 			efree(tmp);
4188 		} else {
4189 			spprintf(error, 4096, "Cannot extract \"%s\" to \"%s...\", extracted filename is too long for filesystem", entry->filename, fullpath);
4190 		}
4191 		efree(fullpath);
4192 		efree(new_state.cwd);
4193 		return FAILURE;
4194 	}
4195 
4196 	if (!len) {
4197 		spprintf(error, 4096, "Cannot extract \"%s\", internal error", entry->filename);
4198 		efree(fullpath);
4199 		efree(new_state.cwd);
4200 		return FAILURE;
4201 	}
4202 
4203 	if (php_check_open_basedir(fullpath)) {
4204 		spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", openbasedir/safe mode restrictions in effect", entry->filename, fullpath);
4205 		efree(fullpath);
4206 		efree(new_state.cwd);
4207 		return FAILURE;
4208 	}
4209 
4210 	/* let see if the path already exists */
4211 	if (!overwrite && SUCCESS == php_stream_stat_path(fullpath, &ssb)) {
4212 		spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", path already exists", entry->filename, fullpath);
4213 		efree(fullpath);
4214 		efree(new_state.cwd);
4215 		return FAILURE;
4216 	}
4217 
4218 	/* perform dirname */
4219 	slash = zend_memrchr(filename, '/', filename_len);
4220 
4221 	if (slash) {
4222 		fullpath[dest_len + (slash - filename) + 1] = '\0';
4223 	} else {
4224 		fullpath[dest_len] = '\0';
4225 	}
4226 
4227 	if (FAILURE == php_stream_stat_path(fullpath, &ssb)) {
4228 		if (entry->is_dir) {
4229 			if (!php_stream_mkdir(fullpath, entry->flags & PHAR_ENT_PERM_MASK,  PHP_STREAM_MKDIR_RECURSIVE, NULL)) {
4230 				spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath);
4231 				efree(fullpath);
4232 				efree(new_state.cwd);
4233 				return FAILURE;
4234 			}
4235 		} else {
4236 			if (!php_stream_mkdir(fullpath, 0777,  PHP_STREAM_MKDIR_RECURSIVE, NULL)) {
4237 				spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath);
4238 				efree(fullpath);
4239 				efree(new_state.cwd);
4240 				return FAILURE;
4241 			}
4242 		}
4243 	}
4244 
4245 	if (slash) {
4246 		fullpath[dest_len + (slash - filename) + 1] = '/';
4247 	} else {
4248 		fullpath[dest_len] = '/';
4249 	}
4250 
4251 	filename = NULL;
4252 	efree(new_state.cwd);
4253 	/* it is a standalone directory, job done */
4254 	if (entry->is_dir) {
4255 		efree(fullpath);
4256 		return SUCCESS;
4257 	}
4258 
4259 	fp = php_stream_open_wrapper(fullpath, "w+b", REPORT_ERRORS, NULL);
4260 
4261 	if (!fp) {
4262 		spprintf(error, 4096, "Cannot extract \"%s\", could not open for writing \"%s\"", entry->filename, fullpath);
4263 		efree(fullpath);
4264 		return FAILURE;
4265 	}
4266 
4267 	if ((phar_get_fp_type(entry) == PHAR_FP && (entry->flags & PHAR_ENT_COMPRESSION_MASK)) || !phar_get_efp(entry, 0)) {
4268 		if (FAILURE == phar_open_entry_fp(entry, error, 1)) {
4269 			if (error) {
4270 				spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer: %s", entry->filename, fullpath, *error);
4271 			} else {
4272 				spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer", entry->filename, fullpath);
4273 			}
4274 			efree(fullpath);
4275 			php_stream_close(fp);
4276 			return FAILURE;
4277 		}
4278 	}
4279 
4280 	if (-1 == phar_seek_efp(entry, 0, SEEK_SET, 0, 0)) {
4281 		spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to seek internal file pointer", entry->filename, fullpath);
4282 		efree(fullpath);
4283 		php_stream_close(fp);
4284 		return FAILURE;
4285 	}
4286 
4287 	if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(entry, 0), fp, entry->uncompressed_filesize, NULL)) {
4288 		spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", copying contents failed", entry->filename, fullpath);
4289 		efree(fullpath);
4290 		php_stream_close(fp);
4291 		return FAILURE;
4292 	}
4293 
4294 	php_stream_close(fp);
4295 	mode = (mode_t) entry->flags & PHAR_ENT_PERM_MASK;
4296 
4297 	if (FAILURE == VCWD_CHMOD(fullpath, mode)) {
4298 		spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", setting file permissions failed", entry->filename, fullpath);
4299 		efree(fullpath);
4300 		return FAILURE;
4301 	}
4302 
4303 	efree(fullpath);
4304 	return SUCCESS;
4305 }
4306 /* }}} */
4307 
extract_helper(phar_archive_data * archive,zend_string * search,char * pathto,size_t pathto_len,bool overwrite,char ** error)4308 static int extract_helper(phar_archive_data *archive, zend_string *search, char *pathto, size_t pathto_len, bool overwrite, char **error) { /* {{{ */
4309 	int extracted = 0;
4310 	phar_entry_info *entry;
4311 
4312 	if (!search) {
4313 		/* nothing to match -- extract all files */
4314 		ZEND_HASH_MAP_FOREACH_PTR(&archive->manifest, entry) {
4315 			if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, error)) return -1;
4316 			extracted++;
4317 		} ZEND_HASH_FOREACH_END();
4318 	} else if ('/' == ZSTR_VAL(search)[ZSTR_LEN(search) - 1]) {
4319 		/* ends in "/" -- extract all entries having that prefix */
4320 		ZEND_HASH_MAP_FOREACH_PTR(&archive->manifest, entry) {
4321 			if (0 != strncmp(ZSTR_VAL(search), entry->filename, ZSTR_LEN(search))) continue;
4322 			if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, error)) return -1;
4323 			extracted++;
4324 		} ZEND_HASH_FOREACH_END();
4325 	} else {
4326 		/* otherwise, looking for an exact match */
4327 		entry = zend_hash_find_ptr(&archive->manifest, search);
4328 		if (NULL == entry) return 0;
4329 		if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, error)) return -1;
4330 		return 1;
4331 	}
4332 
4333 	return extracted;
4334 }
4335 /* }}} */
4336 
4337 /* {{{ Extract one or more file from a phar archive, optionally overwriting existing files */
PHP_METHOD(Phar,extractTo)4338 PHP_METHOD(Phar, extractTo)
4339 {
4340 	php_stream *fp;
4341 	php_stream_statbuf ssb;
4342 	char *pathto;
4343 	zend_string *filename = NULL;
4344 	size_t pathto_len;
4345 	int ret;
4346 	zval *zval_file;
4347 	HashTable *files_ht = NULL;
4348 	bool overwrite = 0;
4349 	char *error = NULL;
4350 
4351 	ZEND_PARSE_PARAMETERS_START(1, 3)
4352 		Z_PARAM_PATH(pathto, pathto_len)
4353 		Z_PARAM_OPTIONAL
4354 		Z_PARAM_ARRAY_HT_OR_STR_OR_NULL(files_ht, filename)
4355 		Z_PARAM_BOOL(overwrite)
4356 	ZEND_PARSE_PARAMETERS_END();
4357 
4358 	PHAR_ARCHIVE_OBJECT();
4359 
4360 	fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, NULL);
4361 
4362 	if (!fp) {
4363 		zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
4364 			"Invalid argument, %s cannot be found", phar_obj->archive->fname);
4365 		RETURN_THROWS();
4366 	}
4367 
4368 	php_stream_close(fp);
4369 
4370 	if (pathto_len < 1) {
4371 		zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
4372 			"Invalid argument, extraction path must be non-zero length");
4373 		RETURN_THROWS();
4374 	}
4375 
4376 	if (pathto_len >= MAXPATHLEN) {
4377 		char *tmp = estrndup(pathto, 50);
4378 		/* truncate for error message */
4379 		zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Cannot extract to \"%s...\", destination directory is too long for filesystem", tmp);
4380 		efree(tmp);
4381 		RETURN_THROWS();
4382 	}
4383 
4384 	if (php_stream_stat_path(pathto, &ssb) < 0) {
4385 		ret = php_stream_mkdir(pathto, 0777,  PHP_STREAM_MKDIR_RECURSIVE, NULL);
4386 		if (!ret) {
4387 			zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4388 				"Unable to create path \"%s\" for extraction", pathto);
4389 			RETURN_THROWS();
4390 		}
4391 	} else if (!(ssb.sb.st_mode & S_IFDIR)) {
4392 		zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4393 			"Unable to use path \"%s\" for extraction, it is a file, must be a directory", pathto);
4394 		RETURN_THROWS();
4395 	}
4396 
4397 	if (files_ht) {
4398 		if (zend_hash_num_elements(files_ht) == 0) {
4399 			RETURN_FALSE;
4400 		}
4401 
4402 		ZEND_HASH_FOREACH_VAL(files_ht, zval_file) {
4403 			ZVAL_DEREF(zval_file);
4404 			if (IS_STRING != Z_TYPE_P(zval_file)) {
4405 				zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
4406 					"Invalid argument, array of filenames to extract contains non-string value");
4407 				RETURN_THROWS();
4408 			}
4409 			switch (extract_helper(phar_obj->archive, Z_STR_P(zval_file), pathto, pathto_len, overwrite, &error)) {
4410 				case -1:
4411 					zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s",
4412 						phar_obj->archive->fname, error);
4413 					efree(error);
4414 					RETURN_THROWS();
4415 				case 0:
4416 					zend_throw_exception_ex(phar_ce_PharException, 0,
4417 						"phar error: attempted to extract non-existent file or directory \"%s\" from phar \"%s\"",
4418 						ZSTR_VAL(Z_STR_P(zval_file)), phar_obj->archive->fname);
4419 					RETURN_THROWS();
4420 			}
4421 		} ZEND_HASH_FOREACH_END();
4422 		RETURN_TRUE;
4423 	}
4424 
4425 	ret = extract_helper(phar_obj->archive, filename, pathto, pathto_len, overwrite, &error);
4426 	if (-1 == ret) {
4427 		zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s",
4428 			phar_obj->archive->fname, error);
4429 		efree(error);
4430 	} else if (0 == ret && NULL != filename) {
4431 		zend_throw_exception_ex(phar_ce_PharException, 0,
4432 			"phar error: attempted to extract non-existent file or directory \"%s\" from phar \"%s\"",
4433 			ZSTR_VAL(filename), phar_obj->archive->fname);
4434 	} else {
4435 		RETURN_TRUE;
4436 	}
4437 }
4438 /* }}} */
4439 
4440 
4441 /* {{{ Construct a Phar entry object */
PHP_METHOD(PharFileInfo,__construct)4442 PHP_METHOD(PharFileInfo, __construct)
4443 {
4444 	char *fname, *arch, *entry, *error;
4445 	size_t fname_len;
4446 	size_t arch_len, entry_len;
4447 	phar_entry_object *entry_obj;
4448 	phar_entry_info *entry_info;
4449 	phar_archive_data *phar_data;
4450 	zval *zobj = ZEND_THIS, arg1;
4451 
4452 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
4453 		RETURN_THROWS();
4454 	}
4455 
4456 	entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset);
4457 
4458 	if (entry_obj->entry) {
4459 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice");
4460 		RETURN_THROWS();
4461 	}
4462 
4463 	if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) {
4464 		zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4465 			"'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname);
4466 		RETURN_THROWS();
4467 	}
4468 
4469 	if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) {
4470 		efree(arch);
4471 		efree(entry);
4472 		if (error) {
4473 			zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4474 				"Cannot open phar file '%s': %s", fname, error);
4475 			efree(error);
4476 		} else {
4477 			zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4478 				"Cannot open phar file '%s'", fname);
4479 		}
4480 		RETURN_THROWS();
4481 	}
4482 
4483 	if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) {
4484 		zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4485 			"Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : "");
4486 		efree(arch);
4487 		efree(entry);
4488 		RETURN_THROWS();
4489 	}
4490 
4491 	efree(arch);
4492 	efree(entry);
4493 
4494 	entry_obj->entry = entry_info;
4495 
4496 	ZVAL_STRINGL(&arg1, fname, fname_len);
4497 
4498 	zend_call_known_instance_method_with_1_params(spl_ce_SplFileInfo->constructor,
4499 		Z_OBJ_P(zobj), NULL, &arg1);
4500 
4501 	zval_ptr_dtor(&arg1);
4502 }
4503 /* }}} */
4504 
4505 #define PHAR_ENTRY_OBJECT() \
4506 	zval *zobj = ZEND_THIS; \
4507 	phar_entry_object *entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); \
4508 	if (!entry_obj->entry) { \
4509 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4510 			"Cannot call method on an uninitialized PharFileInfo object"); \
4511 		RETURN_THROWS(); \
4512 	}
4513 
4514 /* {{{ clean up directory-based entry objects */
PHP_METHOD(PharFileInfo,__destruct)4515 PHP_METHOD(PharFileInfo, __destruct)
4516 {
4517 	zval *zobj = ZEND_THIS;
4518 	phar_entry_object *entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset);
4519 
4520 	if (zend_parse_parameters_none() == FAILURE) {
4521 		RETURN_THROWS();
4522 	}
4523 
4524 	if (entry_obj->entry && entry_obj->entry->is_temp_dir) {
4525 		if (entry_obj->entry->filename) {
4526 			efree(entry_obj->entry->filename);
4527 			entry_obj->entry->filename = NULL;
4528 		}
4529 
4530 		efree(entry_obj->entry);
4531 		entry_obj->entry = NULL;
4532 	}
4533 }
4534 /* }}} */
4535 
4536 /* {{{ Returns the compressed size */
PHP_METHOD(PharFileInfo,getCompressedSize)4537 PHP_METHOD(PharFileInfo, getCompressedSize)
4538 {
4539 	if (zend_parse_parameters_none() == FAILURE) {
4540 		RETURN_THROWS();
4541 	}
4542 
4543 	PHAR_ENTRY_OBJECT();
4544 
4545 	RETURN_LONG(entry_obj->entry->compressed_filesize);
4546 }
4547 /* }}} */
4548 
4549 /* {{{ Returns whether the entry is compressed, and whether it is compressed with Phar::GZ or Phar::BZ2 if specified */
PHP_METHOD(PharFileInfo,isCompressed)4550 PHP_METHOD(PharFileInfo, isCompressed)
4551 {
4552 	zend_long method;
4553 	bool method_is_null = 1;
4554 
4555 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!", &method, &method_is_null) == FAILURE) {
4556 		RETURN_THROWS();
4557 	}
4558 
4559 	PHAR_ENTRY_OBJECT();
4560 
4561 	if (method_is_null) {
4562 		RETURN_BOOL(entry_obj->entry->flags & PHAR_ENT_COMPRESSION_MASK);
4563 	}
4564 
4565 	switch (method) {
4566 		case 9021976: /* Retained for BC */
4567 			RETURN_BOOL(entry_obj->entry->flags & PHAR_ENT_COMPRESSION_MASK);
4568 		case PHAR_ENT_COMPRESSED_GZ:
4569 			RETURN_BOOL(entry_obj->entry->flags & PHAR_ENT_COMPRESSED_GZ);
4570 		case PHAR_ENT_COMPRESSED_BZ2:
4571 			RETURN_BOOL(entry_obj->entry->flags & PHAR_ENT_COMPRESSED_BZ2);
4572 		default:
4573 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unknown compression type specified");
4574 			RETURN_THROWS();
4575 	}
4576 }
4577 /* }}} */
4578 
4579 /* {{{ Returns CRC32 code or throws an exception if not CRC checked */
PHP_METHOD(PharFileInfo,getCRC32)4580 PHP_METHOD(PharFileInfo, getCRC32)
4581 {
4582 	if (zend_parse_parameters_none() == FAILURE) {
4583 		RETURN_THROWS();
4584 	}
4585 
4586 	PHAR_ENTRY_OBJECT();
4587 
4588 	if (entry_obj->entry->is_dir) {
4589 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4590 			"Phar entry is a directory, does not have a CRC"); \
4591 		RETURN_THROWS();
4592 	}
4593 
4594 	if (entry_obj->entry->is_crc_checked) {
4595 		RETURN_LONG(entry_obj->entry->crc32);
4596 	} else {
4597 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Phar entry was not CRC checked");
4598 		RETURN_THROWS();
4599 	}
4600 }
4601 /* }}} */
4602 
4603 /* {{{ Returns whether file entry is CRC checked */
PHP_METHOD(PharFileInfo,isCRCChecked)4604 PHP_METHOD(PharFileInfo, isCRCChecked)
4605 {
4606 	if (zend_parse_parameters_none() == FAILURE) {
4607 		RETURN_THROWS();
4608 	}
4609 
4610 	PHAR_ENTRY_OBJECT();
4611 
4612 	RETURN_BOOL(entry_obj->entry->is_crc_checked);
4613 }
4614 /* }}} */
4615 
4616 /* {{{ Returns the Phar file entry flags */
PHP_METHOD(PharFileInfo,getPharFlags)4617 PHP_METHOD(PharFileInfo, getPharFlags)
4618 {
4619 	if (zend_parse_parameters_none() == FAILURE) {
4620 		RETURN_THROWS();
4621 	}
4622 
4623 	PHAR_ENTRY_OBJECT();
4624 
4625 	RETURN_LONG(entry_obj->entry->flags & ~(PHAR_ENT_PERM_MASK|PHAR_ENT_COMPRESSION_MASK));
4626 }
4627 /* }}} */
4628 
4629 /* {{{ set the file permissions for the Phar.  This only allows setting execution bit, read/write */
PHP_METHOD(PharFileInfo,chmod)4630 PHP_METHOD(PharFileInfo, chmod)
4631 {
4632 	char *error;
4633 	zend_long perms;
4634 
4635 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &perms) == FAILURE) {
4636 		RETURN_THROWS();
4637 	}
4638 
4639 	PHAR_ENTRY_OBJECT();
4640 
4641 	if (entry_obj->entry->is_temp_dir) {
4642 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4643 			"Phar entry \"%s\" is a temporary directory (not an actual entry in the archive), cannot chmod", entry_obj->entry->filename); \
4644 		RETURN_THROWS();
4645 	}
4646 
4647 	if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) {
4648 		zend_throw_exception_ex(phar_ce_PharException, 0, "Cannot modify permissions for file \"%s\" in phar \"%s\", write operations are prohibited", entry_obj->entry->filename, entry_obj->entry->phar->fname);
4649 		RETURN_THROWS();
4650 	}
4651 
4652 	if (entry_obj->entry->is_persistent) {
4653 		phar_archive_data *phar = entry_obj->entry->phar;
4654 
4655 		if (FAILURE == phar_copy_on_write(&phar)) {
4656 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
4657 			RETURN_THROWS();
4658 		}
4659 		/* re-populate after copy-on-write */
4660 		entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len);
4661 	}
4662 	/* clear permissions */
4663 	entry_obj->entry->flags &= ~PHAR_ENT_PERM_MASK;
4664 	perms &= 0777;
4665 	entry_obj->entry->flags |= perms;
4666 	entry_obj->entry->old_flags = entry_obj->entry->flags;
4667 	entry_obj->entry->phar->is_modified = 1;
4668 	entry_obj->entry->is_modified = 1;
4669 
4670 	/* hackish cache in php_stat needs to be cleared */
4671 	/* if this code fails to work, check main/streams/streams.c, _php_stream_stat_path */
4672 	if (BG(CurrentLStatFile)) {
4673 		zend_string_release(BG(CurrentLStatFile));
4674 	}
4675 
4676 	if (BG(CurrentStatFile)) {
4677 		zend_string_release(BG(CurrentStatFile));
4678 	}
4679 
4680 	BG(CurrentLStatFile) = NULL;
4681 	BG(CurrentStatFile) = NULL;
4682 	phar_flush(entry_obj->entry->phar, &error);
4683 
4684 	if (error) {
4685 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
4686 		efree(error);
4687 	}
4688 }
4689 /* }}} */
4690 
4691 /* {{{ Returns the metadata of the entry */
PHP_METHOD(PharFileInfo,hasMetadata)4692 PHP_METHOD(PharFileInfo, hasMetadata)
4693 {
4694 	if (zend_parse_parameters_none() == FAILURE) {
4695 		RETURN_THROWS();
4696 	}
4697 
4698 	PHAR_ENTRY_OBJECT();
4699 
4700 	RETURN_BOOL(phar_metadata_tracker_has_data(&entry_obj->entry->metadata_tracker, entry_obj->entry->is_persistent));
4701 }
4702 /* }}} */
4703 
4704 /* {{{ Returns the metadata of the entry */
PHP_METHOD(PharFileInfo,getMetadata)4705 PHP_METHOD(PharFileInfo, getMetadata)
4706 {
4707 	HashTable *unserialize_options = NULL;
4708 	phar_metadata_tracker *tracker;
4709 
4710 	ZEND_PARSE_PARAMETERS_START(0, 1)
4711 		Z_PARAM_OPTIONAL
4712 		Z_PARAM_ARRAY_HT(unserialize_options)
4713 	ZEND_PARSE_PARAMETERS_END();
4714 
4715 	PHAR_ENTRY_OBJECT();
4716 
4717 	tracker = &entry_obj->entry->metadata_tracker;
4718 	if (phar_metadata_tracker_has_data(tracker, entry_obj->entry->is_persistent)) {
4719 		phar_metadata_tracker_unserialize_or_copy(tracker, return_value, entry_obj->entry->is_persistent, unserialize_options, "PharFileInfo::getMetadata");
4720 	}
4721 }
4722 /* }}} */
4723 
4724 /* {{{ Sets the metadata of the entry */
PHP_METHOD(PharFileInfo,setMetadata)4725 PHP_METHOD(PharFileInfo, setMetadata)
4726 {
4727 	char *error;
4728 	zval *metadata;
4729 
4730 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &metadata) == FAILURE) {
4731 		RETURN_THROWS();
4732 	}
4733 
4734 	PHAR_ENTRY_OBJECT();
4735 
4736 	if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) {
4737 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
4738 		RETURN_THROWS();
4739 	}
4740 
4741 	if (entry_obj->entry->is_temp_dir) {
4742 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4743 			"Phar entry is a temporary directory (not an actual entry in the archive), cannot set metadata"); \
4744 		RETURN_THROWS();
4745 	}
4746 
4747 	if (entry_obj->entry->is_persistent) {
4748 		phar_archive_data *phar = entry_obj->entry->phar;
4749 
4750 		if (FAILURE == phar_copy_on_write(&phar)) {
4751 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
4752 			RETURN_THROWS();
4753 		}
4754 		/* re-populate after copy-on-write */
4755 		entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len);
4756 		ZEND_ASSERT(!entry_obj->entry->is_persistent); /* Should no longer be persistent */
4757 	}
4758 
4759 	if (serialize_metadata_or_throw(&entry_obj->entry->metadata_tracker, entry_obj->entry->is_persistent, metadata) != SUCCESS) {
4760 		RETURN_THROWS();
4761 	}
4762 
4763 	entry_obj->entry->is_modified = 1;
4764 	entry_obj->entry->phar->is_modified = 1;
4765 	phar_flush(entry_obj->entry->phar, &error);
4766 
4767 	if (error) {
4768 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
4769 		efree(error);
4770 	}
4771 }
4772 /* }}} */
4773 
4774 /* {{{ Deletes the metadata of the entry */
PHP_METHOD(PharFileInfo,delMetadata)4775 PHP_METHOD(PharFileInfo, delMetadata)
4776 {
4777 	char *error;
4778 
4779 	if (zend_parse_parameters_none() == FAILURE) {
4780 		RETURN_THROWS();
4781 	}
4782 
4783 	PHAR_ENTRY_OBJECT();
4784 
4785 	if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) {
4786 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
4787 		RETURN_THROWS();
4788 	}
4789 
4790 	if (entry_obj->entry->is_temp_dir) {
4791 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4792 			"Phar entry is a temporary directory (not an actual entry in the archive), cannot delete metadata"); \
4793 		RETURN_THROWS();
4794 	}
4795 
4796 	if (phar_metadata_tracker_has_data(&entry_obj->entry->metadata_tracker, entry_obj->entry->is_persistent)) {
4797 		if (entry_obj->entry->is_persistent) {
4798 			phar_archive_data *phar = entry_obj->entry->phar;
4799 
4800 			if (FAILURE == phar_copy_on_write(&phar)) {
4801 				zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
4802 				RETURN_THROWS();
4803 			}
4804 			/* re-populate after copy-on-write */
4805 			entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len);
4806 		}
4807 		/* multiple values may reference the metadata */
4808 		phar_metadata_tracker_free(&entry_obj->entry->metadata_tracker, entry_obj->entry->is_persistent);
4809 		entry_obj->entry->is_modified = 1;
4810 		entry_obj->entry->phar->is_modified = 1;
4811 
4812 		phar_flush(entry_obj->entry->phar, &error);
4813 
4814 		if (error) {
4815 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
4816 			efree(error);
4817 			RETURN_THROWS();
4818 		} else {
4819 			RETURN_TRUE;
4820 		}
4821 
4822 	} else {
4823 		RETURN_TRUE;
4824 	}
4825 }
4826 /* }}} */
4827 
4828 /* {{{ return the complete file contents of the entry (like file_get_contents) */
PHP_METHOD(PharFileInfo,getContent)4829 PHP_METHOD(PharFileInfo, getContent)
4830 {
4831 	char *error;
4832 	php_stream *fp;
4833 	phar_entry_info *link;
4834 	zend_string *str;
4835 
4836 	if (zend_parse_parameters_none() == FAILURE) {
4837 		RETURN_THROWS();
4838 	}
4839 
4840 	PHAR_ENTRY_OBJECT();
4841 
4842 	if (entry_obj->entry->is_dir) {
4843 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4844 			"phar error: Cannot retrieve contents, \"%s\" in phar \"%s\" is a directory", entry_obj->entry->filename, entry_obj->entry->phar->fname);
4845 		RETURN_THROWS();
4846 	}
4847 
4848 	link = phar_get_link_source(entry_obj->entry);
4849 
4850 	if (!link) {
4851 		link = entry_obj->entry;
4852 	}
4853 
4854 	if (SUCCESS != phar_open_entry_fp(link, &error, 0)) {
4855 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4856 			"phar error: Cannot retrieve contents, \"%s\" in phar \"%s\": %s", entry_obj->entry->filename, entry_obj->entry->phar->fname, error);
4857 		efree(error);
4858 		RETURN_THROWS();
4859 	}
4860 
4861 	if (!(fp = phar_get_efp(link, 0))) {
4862 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4863 			"phar error: Cannot retrieve contents of \"%s\" in phar \"%s\"", entry_obj->entry->filename, entry_obj->entry->phar->fname);
4864 		RETURN_THROWS();
4865 	}
4866 
4867 	phar_seek_efp(link, 0, SEEK_SET, 0, 0);
4868 	str = php_stream_copy_to_mem(fp, link->uncompressed_filesize, 0);
4869 	if (str) {
4870 		RETURN_STR(str);
4871 	} else {
4872 		RETURN_EMPTY_STRING();
4873 	}
4874 }
4875 /* }}} */
4876 
4877 /* {{{ Instructs the Phar class to compress the current file using zlib or bzip2 compression */
PHP_METHOD(PharFileInfo,compress)4878 PHP_METHOD(PharFileInfo, compress)
4879 {
4880 	zend_long method;
4881 	char *error;
4882 
4883 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &method) == FAILURE) {
4884 		RETURN_THROWS();
4885 	}
4886 
4887 	PHAR_ENTRY_OBJECT();
4888 
4889 	if (entry_obj->entry->is_tar) {
4890 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4891 			"Cannot compress with Gzip compression, not possible with tar-based phar archives");
4892 		RETURN_THROWS();
4893 	}
4894 
4895 	if (entry_obj->entry->is_dir) {
4896 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4897 			"Phar entry is a directory, cannot set compression"); \
4898 		RETURN_THROWS();
4899 	}
4900 
4901 	if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) {
4902 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4903 			"Phar is readonly, cannot change compression");
4904 		RETURN_THROWS();
4905 	}
4906 
4907 	if (entry_obj->entry->is_deleted) {
4908 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4909 			"Cannot compress deleted file");
4910 		RETURN_THROWS();
4911 	}
4912 
4913 	if (entry_obj->entry->is_persistent) {
4914 		phar_archive_data *phar = entry_obj->entry->phar;
4915 
4916 		if (FAILURE == phar_copy_on_write(&phar)) {
4917 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
4918 			RETURN_THROWS();
4919 		}
4920 		/* re-populate after copy-on-write */
4921 		entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len);
4922 	}
4923 	switch (method) {
4924 		case PHAR_ENT_COMPRESSED_GZ:
4925 			if (entry_obj->entry->flags & PHAR_ENT_COMPRESSED_GZ) {
4926 				RETURN_TRUE;
4927 			}
4928 
4929 			if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSED_BZ2) != 0) {
4930 				if (!PHAR_G(has_bz2)) {
4931 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4932 						"Cannot compress with gzip compression, file is already compressed with bzip2 compression and bz2 extension is not enabled, cannot decompress");
4933 					RETURN_THROWS();
4934 				}
4935 
4936 				/* decompress this file indirectly */
4937 				if (SUCCESS != phar_open_entry_fp(entry_obj->entry, &error, 1)) {
4938 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4939 						"phar error: Cannot decompress bzip2-compressed file \"%s\" in phar \"%s\" in order to compress with gzip: %s", entry_obj->entry->filename, entry_obj->entry->phar->fname, error);
4940 					efree(error);
4941 					RETURN_THROWS();
4942 				}
4943 			}
4944 
4945 			if (!PHAR_G(has_zlib)) {
4946 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4947 					"Cannot compress with gzip compression, zlib extension is not enabled");
4948 				RETURN_THROWS();
4949 			}
4950 
4951 			entry_obj->entry->old_flags = entry_obj->entry->flags;
4952 			entry_obj->entry->flags &= ~PHAR_ENT_COMPRESSION_MASK;
4953 			entry_obj->entry->flags |= PHAR_ENT_COMPRESSED_GZ;
4954 			break;
4955 		case PHAR_ENT_COMPRESSED_BZ2:
4956 			if (entry_obj->entry->flags & PHAR_ENT_COMPRESSED_BZ2) {
4957 				RETURN_TRUE;
4958 			}
4959 
4960 			if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSED_GZ) != 0) {
4961 				if (!PHAR_G(has_zlib)) {
4962 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4963 						"Cannot compress with bzip2 compression, file is already compressed with gzip compression and zlib extension is not enabled, cannot decompress");
4964 					RETURN_THROWS();
4965 				}
4966 
4967 				/* decompress this file indirectly */
4968 				if (SUCCESS != phar_open_entry_fp(entry_obj->entry, &error, 1)) {
4969 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4970 						"phar error: Cannot decompress gzip-compressed file \"%s\" in phar \"%s\" in order to compress with bzip2: %s", entry_obj->entry->filename, entry_obj->entry->phar->fname, error);
4971 					efree(error);
4972 					RETURN_THROWS();
4973 				}
4974 			}
4975 
4976 			if (!PHAR_G(has_bz2)) {
4977 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4978 					"Cannot compress with bzip2 compression, bz2 extension is not enabled");
4979 				RETURN_THROWS();
4980 			}
4981 			entry_obj->entry->old_flags = entry_obj->entry->flags;
4982 			entry_obj->entry->flags &= ~PHAR_ENT_COMPRESSION_MASK;
4983 			entry_obj->entry->flags |= PHAR_ENT_COMPRESSED_BZ2;
4984 			break;
4985 		default:
4986 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unknown compression type specified");
4987 			RETURN_THROWS();
4988 	}
4989 
4990 	entry_obj->entry->phar->is_modified = 1;
4991 	entry_obj->entry->is_modified = 1;
4992 	phar_flush(entry_obj->entry->phar, &error);
4993 
4994 	if (error) {
4995 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
4996 		efree(error);
4997 		RETURN_THROWS();
4998 	}
4999 
5000 	RETURN_TRUE;
5001 }
5002 /* }}} */
5003 
5004 /* {{{ Instructs the Phar class to decompress the current file */
PHP_METHOD(PharFileInfo,decompress)5005 PHP_METHOD(PharFileInfo, decompress)
5006 {
5007 	char *error;
5008 	char *compression_type;
5009 
5010 	if (zend_parse_parameters_none() == FAILURE) {
5011 		RETURN_THROWS();
5012 	}
5013 
5014 	PHAR_ENTRY_OBJECT();
5015 
5016 	if (entry_obj->entry->is_dir) {
5017 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
5018 			"Phar entry is a directory, cannot set compression"); \
5019 		RETURN_THROWS();
5020 	}
5021 
5022 	if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSION_MASK) == 0) {
5023 		RETURN_TRUE;
5024 	}
5025 
5026 	if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) {
5027 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5028 			"Phar is readonly, cannot decompress");
5029 		RETURN_THROWS();
5030 	}
5031 
5032 	if (entry_obj->entry->is_deleted) {
5033 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5034 			"Cannot compress deleted file");
5035 		RETURN_THROWS();
5036 	}
5037 
5038 	if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSED_GZ) != 0 && !PHAR_G(has_zlib)) {
5039 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5040 			"Cannot decompress Gzip-compressed file, zlib extension is not enabled");
5041 		RETURN_THROWS();
5042 	}
5043 
5044 	if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSED_BZ2) != 0 && !PHAR_G(has_bz2)) {
5045 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5046 			"Cannot decompress Bzip2-compressed file, bz2 extension is not enabled");
5047 		RETURN_THROWS();
5048 	}
5049 
5050 	if (entry_obj->entry->is_persistent) {
5051 		phar_archive_data *phar = entry_obj->entry->phar;
5052 
5053 		if (FAILURE == phar_copy_on_write(&phar)) {
5054 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
5055 			RETURN_THROWS();
5056 		}
5057 		/* re-populate after copy-on-write */
5058 		entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len);
5059 	}
5060 	switch (entry_obj->entry->flags & PHAR_ENT_COMPRESSION_MASK) {
5061 		case PHAR_ENT_COMPRESSED_GZ:
5062 			compression_type = "gzip";
5063 			break;
5064 		case PHAR_ENT_COMPRESSED_BZ2:
5065 			compression_type = "bz2";
5066 			break;
5067 		default:
5068 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5069 				"Cannot decompress file compressed with unknown compression type");
5070 			RETURN_THROWS();
5071 	}
5072 	/* decompress this file indirectly */
5073 	if (SUCCESS != phar_open_entry_fp(entry_obj->entry, &error, 1)) {
5074 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5075 			"Phar error: Cannot decompress %s-compressed file \"%s\" in phar \"%s\": %s", compression_type, entry_obj->entry->filename, entry_obj->entry->phar->fname, error);
5076 		efree(error);
5077 		RETURN_THROWS();
5078 	}
5079 
5080 	entry_obj->entry->old_flags = entry_obj->entry->flags;
5081 	entry_obj->entry->flags &= ~PHAR_ENT_COMPRESSION_MASK;
5082 	entry_obj->entry->phar->is_modified = 1;
5083 	entry_obj->entry->is_modified = 1;
5084 	phar_flush(entry_obj->entry->phar, &error);
5085 
5086 	if (error) {
5087 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
5088 		efree(error);
5089 		RETURN_THROWS();
5090 	}
5091 
5092 	RETURN_TRUE;
5093 }
5094 /* }}} */
5095 
5096 /* {{{ phar methods */
5097 
phar_object_init(void)5098 void phar_object_init(void) /* {{{ */
5099 {
5100 	phar_ce_PharException = register_class_PharException(zend_ce_exception);
5101 
5102 	phar_ce_archive = register_class_Phar(spl_ce_RecursiveDirectoryIterator, zend_ce_countable, zend_ce_arrayaccess);
5103 
5104 	phar_ce_data = register_class_PharData(spl_ce_RecursiveDirectoryIterator, zend_ce_countable, zend_ce_arrayaccess);
5105 
5106 	phar_ce_entry = register_class_PharFileInfo(spl_ce_SplFileInfo);
5107 }
5108 /* }}} */
5109