xref: /PHP-7.4/ext/phar/phar_object.c (revision 2ff853aa)
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   | http://www.php.net/license/3_01.txt.                                 |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: 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 
23 static zend_class_entry *phar_ce_archive;
24 static zend_class_entry *phar_ce_data;
25 static zend_class_entry *phar_ce_PharException;
26 static zend_class_entry *phar_ce_entry;
27 
phar_file_type(HashTable * mimes,char * file,char ** mime_type)28 static int phar_file_type(HashTable *mimes, char *file, char **mime_type) /* {{{ */
29 {
30 	char *ext;
31 	phar_mime_type *mime;
32 	ext = strrchr(file, '.');
33 	if (!ext) {
34 		*mime_type = "text/plain";
35 		/* no file extension = assume text/plain */
36 		return PHAR_MIME_OTHER;
37 	}
38 	++ext;
39 	if (NULL == (mime = zend_hash_str_find_ptr(mimes, ext, strlen(ext)))) {
40 		*mime_type = "application/octet-stream";
41 		return PHAR_MIME_OTHER;
42 	}
43 	*mime_type = mime->mime;
44 	return mime->type;
45 }
46 /* }}} */
47 
phar_mung_server_vars(char * fname,char * entry,size_t entry_len,char * basename,size_t request_uri_len)48 static void phar_mung_server_vars(char *fname, char *entry, size_t entry_len, char *basename, size_t request_uri_len) /* {{{ */
49 {
50 	HashTable *_SERVER;
51 	zval *stuff;
52 	char *path_info;
53 	size_t basename_len = strlen(basename);
54 	size_t code;
55 	zval temp;
56 
57 	/* "tweak" $_SERVER variables requested in earlier call to Phar::mungServer() */
58 	if (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_UNDEF) {
59 		return;
60 	}
61 
62 	_SERVER = Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]);
63 
64 	/* PATH_INFO and PATH_TRANSLATED should always be munged */
65 	if (NULL != (stuff = zend_hash_str_find(_SERVER, "PATH_INFO", sizeof("PATH_INFO")-1))) {
66 		path_info = Z_STRVAL_P(stuff);
67 		code = Z_STRLEN_P(stuff);
68 		if (code > (size_t)entry_len && !memcmp(path_info, entry, entry_len)) {
69 			ZVAL_STR(&temp, Z_STR_P(stuff));
70 			ZVAL_STRINGL(stuff, path_info + entry_len, request_uri_len);
71 			zend_hash_str_update(_SERVER, "PHAR_PATH_INFO", sizeof("PHAR_PATH_INFO")-1, &temp);
72 		}
73 	}
74 
75 	if (NULL != (stuff = zend_hash_str_find(_SERVER, "PATH_TRANSLATED", sizeof("PATH_TRANSLATED")-1))) {
76 		zend_string *str = strpprintf(4096, "phar://%s%s", fname, entry);
77 
78 		ZVAL_STR(&temp, Z_STR_P(stuff));
79 		ZVAL_NEW_STR(stuff, str);
80 
81 		zend_hash_str_update(_SERVER, "PHAR_PATH_TRANSLATED", sizeof("PHAR_PATH_TRANSLATED")-1, &temp);
82 	}
83 
84 	if (!PHAR_G(phar_SERVER_mung_list)) {
85 		return;
86 	}
87 
88 	if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_REQUEST_URI) {
89 		if (NULL != (stuff = zend_hash_str_find(_SERVER, "REQUEST_URI", sizeof("REQUEST_URI")-1))) {
90 			path_info = Z_STRVAL_P(stuff);
91 			code = Z_STRLEN_P(stuff);
92 			if (code > basename_len && !memcmp(path_info, basename, basename_len)) {
93 				ZVAL_STR(&temp, Z_STR_P(stuff));
94 				ZVAL_STRINGL(stuff, path_info + basename_len, code - basename_len);
95 				zend_hash_str_update(_SERVER, "PHAR_REQUEST_URI", sizeof("PHAR_REQUEST_URI")-1, &temp);
96 			}
97 		}
98 	}
99 
100 	if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_PHP_SELF) {
101 		if (NULL != (stuff = zend_hash_str_find(_SERVER, "PHP_SELF", sizeof("PHP_SELF")-1))) {
102 			path_info = Z_STRVAL_P(stuff);
103 			code = Z_STRLEN_P(stuff);
104 
105 			if (code > basename_len && !memcmp(path_info, basename, basename_len)) {
106 				ZVAL_STR(&temp, Z_STR_P(stuff));
107 				ZVAL_STRINGL(stuff, path_info + basename_len, code - basename_len);
108 				zend_hash_str_update(_SERVER, "PHAR_PHP_SELF", sizeof("PHAR_PHP_SELF")-1, &temp);
109 			}
110 		}
111 	}
112 
113 	if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_SCRIPT_NAME) {
114 		if (NULL != (stuff = zend_hash_str_find(_SERVER, "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1))) {
115 			ZVAL_STR(&temp, Z_STR_P(stuff));
116 			ZVAL_STRINGL(stuff, entry, entry_len);
117 			zend_hash_str_update(_SERVER, "PHAR_SCRIPT_NAME", sizeof("PHAR_SCRIPT_NAME")-1, &temp);
118 		}
119 	}
120 
121 	if (PHAR_G(phar_SERVER_mung_list) & PHAR_MUNG_SCRIPT_FILENAME) {
122 		if (NULL != (stuff = zend_hash_str_find(_SERVER, "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1))) {
123 			zend_string *str = strpprintf(4096, "phar://%s%s", fname, entry);
124 
125 			ZVAL_STR(&temp, Z_STR_P(stuff));
126 			ZVAL_NEW_STR(stuff, str);
127 
128 			zend_hash_str_update(_SERVER, "PHAR_SCRIPT_FILENAME", sizeof("PHAR_SCRIPT_FILENAME")-1, &temp);
129 		}
130 	}
131 }
132 /* }}} */
133 
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)134 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) /* {{{ */
135 {
136 	char *name = NULL, buf[8192];
137 	const char *cwd;
138 	zend_syntax_highlighter_ini syntax_highlighter_ini;
139 	sapi_header_line ctr = {0};
140 	size_t got;
141 	zval dummy;
142 	size_t name_len;
143 	zend_file_handle file_handle;
144 	zend_op_array *new_op_array;
145 	zval result;
146 	php_stream *fp;
147 	zend_off_t position;
148 
149 	switch (code) {
150 		case PHAR_MIME_PHPS:
151 			efree(basename);
152 			/* highlight source */
153 			if (entry[0] == '/') {
154 				spprintf(&name, 4096, "phar://%s%s", arch, entry);
155 			} else {
156 				spprintf(&name, 4096, "phar://%s/%s", arch, entry);
157 			}
158 			php_get_highlight_struct(&syntax_highlighter_ini);
159 
160 			highlight_file(name, &syntax_highlighter_ini);
161 
162 			efree(name);
163 #ifdef PHP_WIN32
164 			efree(arch);
165 #endif
166 			zend_bailout();
167 		case PHAR_MIME_OTHER:
168 			/* send headers, output file contents */
169 			efree(basename);
170 			ctr.line_len = spprintf(&(ctr.line), 0, "Content-type: %s", mime_type);
171 			sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
172 			efree(ctr.line);
173 			ctr.line_len = spprintf(&(ctr.line), 0, "Content-length: %u", info->uncompressed_filesize);
174 			sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
175 			efree(ctr.line);
176 
177 			if (FAILURE == sapi_send_headers()) {
178 				zend_bailout();
179 			}
180 
181 			/* prepare to output  */
182 			fp = phar_get_efp(info, 1);
183 
184 			if (!fp) {
185 				char *error;
186 				if (!phar_open_jit(phar, info, &error)) {
187 					if (error) {
188 						zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
189 						efree(error);
190 					}
191 					return -1;
192 				}
193 				fp = phar_get_efp(info, 1);
194 			}
195 			position = 0;
196 			phar_seek_efp(info, 0, SEEK_SET, 0, 1);
197 
198 			do {
199 				got = php_stream_read(fp, buf, MIN(8192, info->uncompressed_filesize - position));
200 				if (got > 0) {
201 					PHPWRITE(buf, got);
202 					position += got;
203 					if (position == (zend_off_t) info->uncompressed_filesize) {
204 						break;
205 					}
206 				}
207 			} while (1);
208 
209 			zend_bailout();
210 		case PHAR_MIME_PHP:
211 			if (basename) {
212 				phar_mung_server_vars(arch, entry, entry_len, basename, ru_len);
213 				efree(basename);
214 			}
215 
216 			if (entry[0] == '/') {
217 				name_len = spprintf(&name, 4096, "phar://%s%s", arch, entry);
218 			} else {
219 				name_len = spprintf(&name, 4096, "phar://%s/%s", arch, entry);
220 			}
221 
222 			zend_stream_init_filename(&file_handle, name);
223 
224 			PHAR_G(cwd) = NULL;
225 			PHAR_G(cwd_len) = 0;
226 
227 			ZVAL_NULL(&dummy);
228 			if (zend_hash_str_add(&EG(included_files), name, name_len, &dummy) != NULL) {
229 				if ((cwd = zend_memrchr(entry, '/', entry_len))) {
230 					PHAR_G(cwd_init) = 1;
231 					if (entry == cwd) {
232 						/* root directory */
233 						PHAR_G(cwd_len) = 0;
234 						PHAR_G(cwd) = NULL;
235 					} else if (entry[0] == '/') {
236 						PHAR_G(cwd_len) = (cwd - (entry + 1));
237 						PHAR_G(cwd) = estrndup(entry + 1, PHAR_G(cwd_len));
238 					} else {
239 						PHAR_G(cwd_len) = (cwd - entry);
240 						PHAR_G(cwd) = estrndup(entry, PHAR_G(cwd_len));
241 					}
242 				}
243 
244 				new_op_array = zend_compile_file(&file_handle, ZEND_REQUIRE);
245 
246 				if (!new_op_array) {
247 					zend_hash_str_del(&EG(included_files), name, name_len);
248 				}
249 
250 				zend_destroy_file_handle(&file_handle);
251 
252 			} else {
253 				efree(name);
254 				new_op_array = NULL;
255 			}
256 #ifdef PHP_WIN32
257 			efree(arch);
258 #endif
259 			if (new_op_array) {
260 				ZVAL_UNDEF(&result);
261 
262 				zend_try {
263 					zend_execute(new_op_array, &result);
264 					if (PHAR_G(cwd)) {
265 						efree(PHAR_G(cwd));
266 						PHAR_G(cwd) = NULL;
267 						PHAR_G(cwd_len) = 0;
268 					}
269 
270 					PHAR_G(cwd_init) = 0;
271 					efree(name);
272 					destroy_op_array(new_op_array);
273 					efree(new_op_array);
274 					zval_ptr_dtor(&result);
275 				} zend_catch {
276 					if (PHAR_G(cwd)) {
277 						efree(PHAR_G(cwd));
278 						PHAR_G(cwd) = NULL;
279 						PHAR_G(cwd_len) = 0;
280 					}
281 
282 					PHAR_G(cwd_init) = 0;
283 					efree(name);
284 				} zend_end_try();
285 
286 				zend_bailout();
287 			}
288 
289 			return PHAR_MIME_PHP;
290 	}
291 	return -1;
292 }
293 /* }}} */
294 
phar_do_403(char * entry,size_t entry_len)295 static void phar_do_403(char *entry, size_t entry_len) /* {{{ */
296 {
297 	sapi_header_line ctr = {0};
298 
299 	ctr.response_code = 403;
300 	ctr.line_len = sizeof("HTTP/1.0 403 Access Denied")-1;
301 	ctr.line = "HTTP/1.0 403 Access Denied";
302 	sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
303 	sapi_send_headers();
304 	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);
305 	PHPWRITE("Access Denied</h1>\n </body>\n</html>", sizeof("Access Denied</h1>\n </body>\n</html>") - 1);
306 }
307 /* }}} */
308 
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)309 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) /* {{{ */
310 {
311 	sapi_header_line ctr = {0};
312 	phar_entry_info	*info;
313 
314 	if (phar && f404_len) {
315 		info = phar_get_entry_info(phar, f404, f404_len, NULL, 1);
316 
317 		if (info) {
318 			phar_file_action(phar, info, "text/html", PHAR_MIME_PHP, f404, f404_len, fname, NULL, NULL, 0);
319 			return;
320 		}
321 	}
322 
323 	ctr.response_code = 404;
324 	ctr.line_len = sizeof("HTTP/1.0 404 Not Found")-1;
325 	ctr.line = "HTTP/1.0 404 Not Found";
326 	sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
327 	sapi_send_headers();
328 	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);
329 	PHPWRITE("Not Found</h1>\n </body>\n</html>",  sizeof("Not Found</h1>\n </body>\n</html>") - 1);
330 }
331 /* }}} */
332 
333 /* post-process REQUEST_URI and retrieve the actual request URI.  This is for
334    cases like http://localhost/blah.phar/path/to/file.php/extra/stuff
335    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)336 static void phar_postprocess_ru_web(char *fname, size_t fname_len, char **entry, size_t *entry_len, char **ru, size_t *ru_len) /* {{{ */
337 {
338 	char *e = *entry + 1, *u = NULL, *u1 = NULL, *saveu = NULL;
339 	size_t e_len = *entry_len - 1, u_len = 0;
340 	phar_archive_data *pphar;
341 
342 	/* we already know we can retrieve the phar if we reach here */
343 	pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len);
344 
345 	if (!pphar && PHAR_G(manifest_cached)) {
346 		pphar = zend_hash_str_find_ptr(&cached_phars, fname, fname_len);
347 	}
348 
349 	do {
350 		if (zend_hash_str_exists(&(pphar->manifest), e, e_len)) {
351 			if (u) {
352 				u[0] = '/';
353 				*ru = estrndup(u, u_len+1);
354 				++u_len;
355 				u[0] = '\0';
356 			} else {
357 				*ru = NULL;
358 			}
359 			*ru_len = u_len;
360 			*entry_len = e_len + 1;
361 			return;
362 		}
363 
364 		if (u) {
365 			u1 = strrchr(e, '/');
366 			u[0] = '/';
367 			saveu = u;
368 			e_len += u_len + 1;
369 			u = u1;
370 			if (!u) {
371 				return;
372 			}
373 		} else {
374 			u = strrchr(e, '/');
375 			if (!u) {
376 				if (saveu) {
377 					saveu[0] = '/';
378 				}
379 				return;
380 			}
381 		}
382 
383 		u[0] = '\0';
384 		u_len = strlen(u + 1);
385 		e_len -= u_len + 1;
386 	} while (1);
387 }
388 /* }}} */
389 
390 /* {{{ proto void Phar::running([bool retphar = true])
391  * return the name of the currently running phar archive.  If the optional parameter
392  * is set to true, return the phar:// URL to the currently running phar
393  */
PHP_METHOD(Phar,running)394 PHP_METHOD(Phar, running)
395 {
396 	char *fname, *arch, *entry;
397 	size_t fname_len, arch_len, entry_len;
398 	zend_bool retphar = 1;
399 
400 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &retphar) == FAILURE) {
401 		return;
402 	}
403 
404 	fname = (char*)zend_get_executed_filename();
405 	fname_len = strlen(fname);
406 
407 	if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
408 		efree(entry);
409 		if (retphar) {
410 			RETVAL_STRINGL(fname, arch_len + 7);
411 			efree(arch);
412 			return;
413 		} else {
414 			// TODO: avoid reallocation ???
415 			RETVAL_STRINGL(arch, arch_len);
416 			efree(arch);
417 			return;
418 		}
419 	}
420 
421 	RETURN_EMPTY_STRING();
422 }
423 /* }}} */
424 
425 /* {{{ proto void Phar::mount(string pharpath, string externalfile)
426  * mount an external file or path to a location within the phar.  This maps
427  * an external file or directory to a location within the phar archive, allowing
428  * reference to an external location as if it were within the phar archive.  This
429  * is useful for writable temp files like databases
430  */
PHP_METHOD(Phar,mount)431 PHP_METHOD(Phar, mount)
432 {
433 	char *fname, *arch = NULL, *entry = NULL, *path, *actual;
434 	size_t fname_len, arch_len, entry_len;
435 	size_t path_len, actual_len;
436 	phar_archive_data *pphar;
437 #ifdef PHP_WIN32
438 	char *save_fname;
439 	ALLOCA_FLAG(fname_use_heap)
440 #endif
441 
442 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &path, &path_len, &actual, &actual_len) == FAILURE) {
443 		return;
444 	}
445 
446 	fname = (char*)zend_get_executed_filename();
447 	fname_len = strlen(fname);
448 
449 #ifdef PHP_WIN32
450 	save_fname = fname;
451 	if (memchr(fname, '\\', fname_len)) {
452 		fname = do_alloca(fname_len + 1, fname_use_heap);
453 		memcpy(fname, save_fname, fname_len);
454 		fname[fname_len] = '\0';
455 		phar_unixify_path_separators(fname, fname_len);
456 	}
457 #endif
458 
459 	if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
460 		efree(entry);
461 		entry = NULL;
462 
463 		if (path_len > 7 && !memcmp(path, "phar://", 7)) {
464 			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);
465 			efree(arch);
466 			goto finish;
467 		}
468 carry_on2:
469 		if (NULL == (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), arch, arch_len))) {
470 			if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, arch, arch_len))) {
471 				if (SUCCESS == phar_copy_on_write(&pphar)) {
472 					goto carry_on;
473 				}
474 			}
475 
476 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s is not a phar archive, cannot mount", arch);
477 
478 			if (arch) {
479 				efree(arch);
480 			}
481 
482 			goto finish;
483 		}
484 carry_on:
485 		if (SUCCESS != phar_mount_entry(pphar, actual, actual_len, path, path_len)) {
486 			zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s within phar %s failed", path, actual, arch);
487 			if (path && path == entry) {
488 				efree(entry);
489 			}
490 
491 			if (arch) {
492 				efree(arch);
493 			}
494 
495 			goto finish;
496 		}
497 
498 		if (entry && path && path == entry) {
499 			efree(entry);
500 		}
501 
502 		if (arch) {
503 			efree(arch);
504 		}
505 
506 		goto finish;
507 	} 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))) {
508 		goto carry_on;
509 	} else if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, fname, fname_len))) {
510 		if (SUCCESS == phar_copy_on_write(&pphar)) {
511 			goto carry_on;
512 		}
513 
514 		goto carry_on;
515 	} else if (SUCCESS == phar_split_fname(path, path_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
516 		path = entry;
517 		path_len = entry_len;
518 		goto carry_on2;
519 	}
520 
521 	zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s failed", path, actual);
522 
523 finish: ;
524 #ifdef PHP_WIN32
525 	if (fname != save_fname) {
526 		free_alloca(fname, fname_use_heap);
527 		fname = save_fname;
528 	}
529 #endif
530 }
531 /* }}} */
532 
533 /* {{{ proto void Phar::webPhar([string alias, [string index, [string f404, [array mimetypes, [callback rewrites]]]]])
534  * mapPhar for web-based phars. Reads the currently executed file (a phar)
535  * and registers its manifest. When executed in the CLI or CGI command-line sapi,
536  * this works exactly like mapPhar().  When executed by a web-based sapi, this
537  * reads $_SERVER['REQUEST_URI'] (the actual original value) and parses out the
538  * intended internal file.
539  */
PHP_METHOD(Phar,webPhar)540 PHP_METHOD(Phar, webPhar)
541 {
542 	zval *mimeoverride = NULL, *rewrite = NULL;
543 	char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL;
544 	size_t alias_len = 0, f404_len = 0, free_pathinfo = 0;
545 	size_t ru_len = 0;
546 	char *fname, *path_info, *mime_type = NULL, *entry, *pt;
547 	const char *basename;
548 	size_t fname_len, index_php_len = 0;
549 	size_t entry_len;
550 	int code, not_cgi;
551 	phar_archive_data *phar = NULL;
552 	phar_entry_info *info = NULL;
553 	size_t sapi_mod_name_len = strlen(sapi_module.name);
554 
555 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!s!saz", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite) == FAILURE) {
556 		return;
557 	}
558 
559 	phar_request_initialize();
560 	fname = (char*)zend_get_executed_filename();
561 	fname_len = strlen(fname);
562 
563 	if (phar_open_executed_filename(alias, alias_len, &error) != SUCCESS) {
564 		if (error) {
565 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
566 			efree(error);
567 		}
568 		return;
569 	}
570 
571 	/* retrieve requested file within phar */
572 	if (!(SG(request_info).request_method
573           && SG(request_info).request_uri
574           && (!strcmp(SG(request_info).request_method, "GET")
575            || !strcmp(SG(request_info).request_method, "POST")
576            || !strcmp(SG(request_info).request_method, "DELETE")
577            || !strcmp(SG(request_info).request_method, "HEAD")
578            || !strcmp(SG(request_info).request_method, "OPTIONS")
579            || !strcmp(SG(request_info).request_method, "PATCH")
580            || !strcmp(SG(request_info).request_method, "PUT")
581           )
582          )
583       ) {
584 		return;
585 	}
586 
587 #ifdef PHP_WIN32
588 	if (memchr(fname, '\\', fname_len)) {
589 		fname = estrndup(fname, fname_len);
590 		phar_unixify_path_separators(fname, fname_len);
591 	}
592 #endif
593 	basename = zend_memrchr(fname, '/', fname_len);
594 
595 	if (!basename) {
596 		basename = fname;
597 	} else {
598 		++basename;
599 	}
600 
601 	if ((sapi_mod_name_len == sizeof("cgi-fcgi") - 1 && !strncmp(sapi_module.name, "cgi-fcgi", sizeof("cgi-fcgi") - 1))
602 		|| (sapi_mod_name_len == sizeof("fpm-fcgi") - 1 && !strncmp(sapi_module.name, "fpm-fcgi", sizeof("fpm-fcgi") - 1))
603 		|| (sapi_mod_name_len == sizeof("cgi") - 1 && !strncmp(sapi_module.name, "cgi", sizeof("cgi") - 1))) {
604 
605 		if (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) != IS_UNDEF) {
606 			HashTable *_server = Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]);
607 			zval *z_script_name, *z_path_info;
608 
609 			if (NULL == (z_script_name = zend_hash_str_find(_server, "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) ||
610 				IS_STRING != Z_TYPE_P(z_script_name) ||
611 				!strstr(Z_STRVAL_P(z_script_name), basename)) {
612 				goto finish;
613 			}
614 
615 			if (NULL != (z_path_info = zend_hash_str_find(_server, "PATH_INFO", sizeof("PATH_INFO")-1)) &&
616 				IS_STRING == Z_TYPE_P(z_path_info)) {
617 				entry_len = Z_STRLEN_P(z_path_info);
618 				entry = estrndup(Z_STRVAL_P(z_path_info), entry_len);
619 				path_info = emalloc(Z_STRLEN_P(z_script_name) + entry_len + 1);
620 				memcpy(path_info, Z_STRVAL_P(z_script_name), Z_STRLEN_P(z_script_name));
621 				memcpy(path_info + Z_STRLEN_P(z_script_name), entry, entry_len + 1);
622 				free_pathinfo = 1;
623 			} else {
624 				entry_len = 0;
625 				entry = estrndup("", 0);
626 				path_info = Z_STRVAL_P(z_script_name);
627 			}
628 
629 			pt = estrndup(Z_STRVAL_P(z_script_name), Z_STRLEN_P(z_script_name));
630 
631 		} else {
632 			char *testit;
633 
634 			testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1);
635 			if (!(pt = strstr(testit, basename))) {
636 				efree(testit);
637 				goto finish;
638 			}
639 
640 			path_info = sapi_getenv("PATH_INFO", sizeof("PATH_INFO")-1);
641 
642 			if (path_info) {
643 				entry = path_info;
644 				entry_len = strlen(entry);
645 				spprintf(&path_info, 0, "%s%s", testit, path_info);
646 				free_pathinfo = 1;
647 			} else {
648 				path_info = testit;
649 				free_pathinfo = 1;
650 				entry = estrndup("", 0);
651 				entry_len = 0;
652 			}
653 
654 			pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname)));
655 		}
656 		not_cgi = 0;
657 	} else {
658 		path_info = SG(request_info).request_uri;
659 
660 		if (!(pt = strstr(path_info, basename))) {
661 			/* this can happen with rewrite rules - and we have no idea what to do then, so return */
662 			goto finish;
663 		}
664 
665 		entry_len = strlen(path_info);
666 		entry_len -= (pt - path_info) + (fname_len - (basename - fname));
667 		entry = estrndup(pt + (fname_len - (basename - fname)), entry_len);
668 
669 		pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname)));
670 		not_cgi = 1;
671 	}
672 
673 	if (rewrite) {
674 		zend_fcall_info fci;
675 		zend_fcall_info_cache fcc;
676 		zval params, retval;
677 
678 		ZVAL_STRINGL(&params, entry, entry_len);
679 
680 		if (FAILURE == zend_fcall_info_init(rewrite, 0, &fci, &fcc, NULL, NULL)) {
681 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar error: invalid rewrite callback");
682 
683 			if (free_pathinfo) {
684 				efree(path_info);
685 			}
686 			efree(pt);
687 
688 			goto finish;
689 		}
690 
691 		fci.param_count = 1;
692 		fci.params = &params;
693 		Z_ADDREF(params);
694 		fci.retval = &retval;
695 
696 		if (FAILURE == zend_call_function(&fci, &fcc)) {
697 			if (!EG(exception)) {
698 				zend_throw_exception_ex(phar_ce_PharException, 0, "phar error: failed to call rewrite callback");
699 			}
700 
701 			if (free_pathinfo) {
702 				efree(path_info);
703 			}
704 			efree(pt);
705 
706 			goto finish;
707 		}
708 
709 		if (Z_TYPE_P(fci.retval) == IS_UNDEF || Z_TYPE(retval) == IS_UNDEF) {
710 			if (free_pathinfo) {
711 				efree(path_info);
712 			}
713 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar error: rewrite callback must return a string or false");
714 			efree(pt);
715 			goto finish;
716 		}
717 
718 		switch (Z_TYPE(retval)) {
719 			case IS_STRING:
720 				efree(entry);
721 				entry = estrndup(Z_STRVAL_P(fci.retval), Z_STRLEN_P(fci.retval));
722 				entry_len = Z_STRLEN_P(fci.retval);
723 				break;
724 			case IS_TRUE:
725 			case IS_FALSE:
726 				phar_do_403(entry, entry_len);
727 
728 				if (free_pathinfo) {
729 					efree(path_info);
730 				}
731 				efree(pt);
732 
733 				zend_bailout();
734 				goto finish;
735 			default:
736 				if (free_pathinfo) {
737 					efree(path_info);
738 				}
739 				efree(pt);
740 
741 				zend_throw_exception_ex(phar_ce_PharException, 0, "phar error: rewrite callback must return a string or false");
742 				goto finish;
743 		}
744 	}
745 
746 	if (entry_len) {
747 		phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len);
748 	}
749 
750 	if (!entry_len || (entry_len == 1 && entry[0] == '/')) {
751 		efree(entry);
752 		/* direct request */
753 		if (index_php_len) {
754 			entry = index_php;
755 			entry_len = index_php_len;
756 			if (entry[0] != '/') {
757 				spprintf(&entry, 0, "/%s", index_php);
758 				++entry_len;
759 			}
760 		} else {
761 			/* assume "index.php" is starting point */
762 			entry = estrndup("/index.php", sizeof("/index.php"));
763 			entry_len = sizeof("/index.php")-1;
764 		}
765 
766 		if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL) ||
767 			(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0)) == NULL) {
768 			phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len);
769 
770 			if (free_pathinfo) {
771 				efree(path_info);
772 			}
773 
774 			zend_bailout();
775 		} else {
776 			char *tmp = NULL, sa = '\0';
777 			sapi_header_line ctr = {0};
778 			ctr.response_code = 301;
779 			ctr.line_len = sizeof("HTTP/1.1 301 Moved Permanently")-1;
780 			ctr.line = "HTTP/1.1 301 Moved Permanently";
781 			sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
782 
783 			if (not_cgi) {
784 				tmp = strstr(path_info, basename) + fname_len;
785 				sa = *tmp;
786 				*tmp = '\0';
787 			}
788 
789 			ctr.response_code = 0;
790 
791 			if (path_info[strlen(path_info)-1] == '/') {
792 				ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry + 1);
793 			} else {
794 				ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry);
795 			}
796 
797 			if (not_cgi) {
798 				*tmp = sa;
799 			}
800 
801 			if (free_pathinfo) {
802 				efree(path_info);
803 			}
804 
805 			sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
806 			sapi_send_headers();
807 			efree(ctr.line);
808 			zend_bailout();
809 		}
810 	}
811 
812 	if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL) ||
813 		(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0)) == NULL) {
814 		phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len);
815 		zend_bailout();
816 	}
817 
818 	if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) {
819 		const char *ext = zend_memrchr(entry, '.', entry_len);
820 		zval *val;
821 
822 		if (ext) {
823 			++ext;
824 
825 			if (NULL != (val = zend_hash_str_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)))) {
826 				switch (Z_TYPE_P(val)) {
827 					case IS_LONG:
828 						if (Z_LVAL_P(val) == PHAR_MIME_PHP || Z_LVAL_P(val) == PHAR_MIME_PHPS) {
829 							mime_type = "";
830 							code = Z_LVAL_P(val);
831 						} else {
832 							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");
833 							if (free_pathinfo) {
834 								efree(path_info);
835 							}
836 							efree(pt);
837 							efree(entry);
838 							RETVAL_FALSE;
839 							goto finish;
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 						RETVAL_FALSE;
854 						goto finish;
855 				}
856 			}
857 		}
858 	}
859 
860 	if (!mime_type) {
861 		code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type);
862 	}
863 	phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len);
864 
865 finish: ;
866 #ifdef PHP_WIN32
867 	efree(fname);
868 #endif
869 }
870 /* }}} */
871 
872 /* {{{ proto void Phar::mungServer(array munglist)
873  * Defines a list of up to 4 $_SERVER variables that should be modified for execution
874  * to mask the presence of the phar archive.  This should be used in conjunction with
875  * Phar::webPhar(), and has no effect otherwise
876  * SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME
877  */
PHP_METHOD(Phar,mungServer)878 PHP_METHOD(Phar, mungServer)
879 {
880 	zval *mungvalues, *data;
881 
882 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "a", &mungvalues) == FAILURE) {
883 		return;
884 	}
885 
886 	if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) {
887 		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");
888 		return;
889 	}
890 
891 	if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) {
892 		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");
893 		return;
894 	}
895 
896 	phar_request_initialize();
897 
898 	ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(mungvalues), data) {
899 
900 		if (Z_TYPE_P(data) != IS_STRING) {
901 			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");
902 			return;
903 		}
904 
905 		if (Z_STRLEN_P(data) == sizeof("PHP_SELF")-1 && !strncmp(Z_STRVAL_P(data), "PHP_SELF", sizeof("PHP_SELF")-1)) {
906 			PHAR_G(phar_SERVER_mung_list) |= PHAR_MUNG_PHP_SELF;
907 		}
908 
909 		if (Z_STRLEN_P(data) == sizeof("REQUEST_URI")-1) {
910 			if (!strncmp(Z_STRVAL_P(data), "REQUEST_URI", sizeof("REQUEST_URI")-1)) {
911 				PHAR_G(phar_SERVER_mung_list) |= PHAR_MUNG_REQUEST_URI;
912 			}
913 			if (!strncmp(Z_STRVAL_P(data), "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) {
914 				PHAR_G(phar_SERVER_mung_list) |= PHAR_MUNG_SCRIPT_NAME;
915 			}
916 		}
917 
918 		if (Z_STRLEN_P(data) == sizeof("SCRIPT_FILENAME")-1 && !strncmp(Z_STRVAL_P(data), "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1)) {
919 			PHAR_G(phar_SERVER_mung_list) |= PHAR_MUNG_SCRIPT_FILENAME;
920 		}
921 	} ZEND_HASH_FOREACH_END();
922 }
923 /* }}} */
924 
925 /* {{{ proto void Phar::interceptFileFuncs()
926  * instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
927  * and return stat on files within the phar for relative paths
928  *
929  * Once called, this cannot be reversed, and continue until the end of the request.
930  *
931  * This allows legacy scripts to be pharred unmodified
932  */
PHP_METHOD(Phar,interceptFileFuncs)933 PHP_METHOD(Phar, interceptFileFuncs)
934 {
935 	if (zend_parse_parameters_none() == FAILURE) {
936 		return;
937 	}
938 	phar_intercept_functions();
939 }
940 /* }}} */
941 
942 /* {{{ proto array Phar::createDefaultStub([string indexfile[, string webindexfile]])
943  * Return a stub that can be used to run a phar-based archive without the phar extension
944  * indexfile is the CLI startup filename, which defaults to "index.php", webindexfile
945  * is the web startup filename, and also defaults to "index.php"
946  */
PHP_METHOD(Phar,createDefaultStub)947 PHP_METHOD(Phar, createDefaultStub)
948 {
949 	char *index = NULL, *webindex = NULL, *error;
950 	zend_string *stub;
951 	size_t index_len = 0, webindex_len = 0;
952 
953 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|pp", &index, &index_len, &webindex, &webindex_len) == FAILURE) {
954 		return;
955 	}
956 
957 	stub = phar_create_default_stub(index, webindex, &error);
958 
959 	if (error) {
960 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
961 		efree(error);
962 		return;
963 	}
964 	RETURN_NEW_STR(stub);
965 }
966 /* }}} */
967 
968 /* {{{ proto mixed Phar::mapPhar([string alias, [int dataoffset]])
969  * Reads the currently executed file (a phar) and registers its manifest */
PHP_METHOD(Phar,mapPhar)970 PHP_METHOD(Phar, mapPhar)
971 {
972 	char *alias = NULL, *error;
973 	size_t alias_len = 0;
974 	zend_long dataoffset = 0;
975 
976 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!l", &alias, &alias_len, &dataoffset) == FAILURE) {
977 		return;
978 	}
979 
980 	phar_request_initialize();
981 
982 	RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error) == SUCCESS);
983 
984 	if (error) {
985 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
986 		efree(error);
987 	}
988 } /* }}} */
989 
990 /* {{{ proto mixed Phar::loadPhar(string filename [, string alias])
991  * Loads any phar archive with an alias */
PHP_METHOD(Phar,loadPhar)992 PHP_METHOD(Phar, loadPhar)
993 {
994 	char *fname, *alias = NULL, *error;
995 	size_t fname_len, alias_len = 0;
996 
997 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) {
998 		return;
999 	}
1000 
1001 	phar_request_initialize();
1002 
1003 	RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS);
1004 
1005 	if (error) {
1006 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
1007 		efree(error);
1008 	}
1009 } /* }}} */
1010 
1011 /* {{{ proto string Phar::apiVersion()
1012  * Returns the api version */
PHP_METHOD(Phar,apiVersion)1013 PHP_METHOD(Phar, apiVersion)
1014 {
1015 	if (zend_parse_parameters_none() == FAILURE) {
1016 		return;
1017 	}
1018 	RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1);
1019 }
1020 /* }}}*/
1021 
1022 /* {{{ proto bool Phar::canCompress([int method])
1023  * Returns whether phar extension supports compression using zlib/bzip2 */
PHP_METHOD(Phar,canCompress)1024 PHP_METHOD(Phar, canCompress)
1025 {
1026 	zend_long method = 0;
1027 
1028 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &method) == FAILURE) {
1029 		return;
1030 	}
1031 
1032 	phar_request_initialize();
1033 	switch (method) {
1034 	case PHAR_ENT_COMPRESSED_GZ:
1035 		if (PHAR_G(has_zlib)) {
1036 			RETURN_TRUE;
1037 		} else {
1038 			RETURN_FALSE;
1039 		}
1040 	case PHAR_ENT_COMPRESSED_BZ2:
1041 		if (PHAR_G(has_bz2)) {
1042 			RETURN_TRUE;
1043 		} else {
1044 			RETURN_FALSE;
1045 		}
1046 	default:
1047 		if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) {
1048 			RETURN_TRUE;
1049 		} else {
1050 			RETURN_FALSE;
1051 		}
1052 	}
1053 }
1054 /* }}} */
1055 
1056 /* {{{ proto bool Phar::canWrite()
1057  * Returns whether phar extension supports writing and creating phars */
PHP_METHOD(Phar,canWrite)1058 PHP_METHOD(Phar, canWrite)
1059 {
1060 	if (zend_parse_parameters_none() == FAILURE) {
1061 		return;
1062 	}
1063 	RETURN_BOOL(!PHAR_G(readonly));
1064 }
1065 /* }}} */
1066 
1067 /* {{{ proto bool Phar::isValidPharFilename(string filename[, bool executable = true])
1068  * Returns whether the given filename is a valid phar filename */
PHP_METHOD(Phar,isValidPharFilename)1069 PHP_METHOD(Phar, isValidPharFilename)
1070 {
1071 	char *fname;
1072 	const char *ext_str;
1073 	size_t fname_len;
1074 	size_t ext_len;
1075 	int is_executable;
1076 	zend_bool executable = 1;
1077 
1078 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|b", &fname, &fname_len, &executable) == FAILURE) {
1079 		return;
1080 	}
1081 
1082 	is_executable = executable;
1083 	RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1) == SUCCESS);
1084 }
1085 /* }}} */
1086 
1087 /**
1088  * from spl_directory
1089  */
phar_spl_foreign_dtor(spl_filesystem_object * object)1090 static void phar_spl_foreign_dtor(spl_filesystem_object *object) /* {{{ */
1091 {
1092 	phar_archive_data *phar = (phar_archive_data *) object->oth;
1093 
1094 	if (!phar->is_persistent) {
1095 		phar_archive_delref(phar);
1096 	}
1097 
1098 	object->oth = NULL;
1099 }
1100 /* }}} */
1101 
1102 /**
1103  * from spl_directory
1104  */
phar_spl_foreign_clone(spl_filesystem_object * src,spl_filesystem_object * dst)1105 static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst) /* {{{ */
1106 {
1107 	phar_archive_data *phar_data = (phar_archive_data *) dst->oth;
1108 
1109 	if (!phar_data->is_persistent) {
1110 		++(phar_data->refcount);
1111 	}
1112 }
1113 /* }}} */
1114 
1115 static const spl_other_handler phar_spl_foreign_handler = {
1116 	phar_spl_foreign_dtor,
1117 	phar_spl_foreign_clone
1118 };
1119 
1120 /* {{{ proto Phar::__construct(string fname [, int flags [, string alias]])
1121  * Construct a Phar archive object
1122  *
1123  * proto PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR])
1124  * Construct a PharData archive object
1125  *
1126  * This function is used as the constructor for both the Phar and PharData
1127  * classes, hence the two prototypes above.
1128  */
PHP_METHOD(Phar,__construct)1129 PHP_METHOD(Phar, __construct)
1130 {
1131 	char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname;
1132 	size_t fname_len, alias_len = 0;
1133 	size_t arch_len, entry_len;
1134 	zend_bool is_data;
1135 	zend_long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS;
1136 	zend_long format = 0;
1137 	phar_archive_object *phar_obj;
1138 	phar_archive_data   *phar_data;
1139 	zval *zobj = ZEND_THIS, arg1, arg2;
1140 
1141 	phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset);
1142 
1143 	is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data);
1144 
1145 	if (is_data) {
1146 		if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) {
1147 			return;
1148 		}
1149 	} else {
1150 		if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) {
1151 			return;
1152 		}
1153 	}
1154 
1155 	if (phar_obj->archive) {
1156 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice");
1157 		return;
1158 	}
1159 
1160 	save_fname = fname;
1161 	if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2)) {
1162 		/* use arch (the basename for the archive) for fname instead of fname */
1163 		/* this allows support for RecursiveDirectoryIterator of subdirectories */
1164 #ifdef PHP_WIN32
1165 		phar_unixify_path_separators(arch, arch_len);
1166 #endif
1167 		fname = arch;
1168 		fname_len = arch_len;
1169 #ifdef PHP_WIN32
1170 	} else {
1171 		arch = estrndup(fname, fname_len);
1172 		arch_len = fname_len;
1173 		fname = arch;
1174 		phar_unixify_path_separators(arch, arch_len);
1175 #endif
1176 	}
1177 
1178 	if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error) == FAILURE) {
1179 
1180 		if (fname == arch && fname != save_fname) {
1181 			efree(arch);
1182 			fname = save_fname;
1183 		}
1184 
1185 		if (entry) {
1186 			efree(entry);
1187 		}
1188 
1189 		if (error) {
1190 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1191 				"%s", error);
1192 			efree(error);
1193 		} else {
1194 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1195 				"Phar creation or opening failed");
1196 		}
1197 
1198 		return;
1199 	}
1200 
1201 	if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) {
1202 		phar_data->is_zip = 1;
1203 		phar_data->is_tar = 0;
1204 	}
1205 
1206 	if (fname == arch) {
1207 		efree(arch);
1208 		fname = save_fname;
1209 	}
1210 
1211 	if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) {
1212 		if (is_data) {
1213 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1214 				"PharData class can only be used for non-executable tar and zip archives");
1215 		} else {
1216 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1217 				"Phar class can only be used for executable tar and zip archives");
1218 		}
1219 		efree(entry);
1220 		return;
1221 	}
1222 
1223 	is_data = phar_data->is_data;
1224 
1225 	if (!phar_data->is_persistent) {
1226 		++(phar_data->refcount);
1227 	}
1228 
1229 	phar_obj->archive = phar_data;
1230 	phar_obj->spl.oth_handler = &phar_spl_foreign_handler;
1231 
1232 	if (entry) {
1233 		fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry);
1234 		efree(entry);
1235 	} else {
1236 		fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname);
1237 	}
1238 
1239 	ZVAL_STRINGL(&arg1, fname, fname_len);
1240 	ZVAL_LONG(&arg2, flags);
1241 
1242 	zend_call_method_with_2_params(zobj, Z_OBJCE_P(zobj),
1243 		&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2);
1244 
1245 	zval_ptr_dtor(&arg1);
1246 
1247 	if (!phar_data->is_persistent) {
1248 		phar_obj->archive->is_data = is_data;
1249 	} else if (!EG(exception)) {
1250 		/* register this guy so we can modify if necessary */
1251 		zend_hash_str_add_ptr(&PHAR_G(phar_persist_map), (const char *) phar_obj->archive, sizeof(phar_obj->archive), phar_obj);
1252 	}
1253 
1254 	phar_obj->spl.info_class = phar_ce_entry;
1255 	efree(fname);
1256 }
1257 /* }}} */
1258 
1259 /* {{{ proto array Phar::getSupportedSignatures()
1260  * Return array of supported signature types
1261  */
PHP_METHOD(Phar,getSupportedSignatures)1262 PHP_METHOD(Phar, getSupportedSignatures)
1263 {
1264 	if (zend_parse_parameters_none() == FAILURE) {
1265 		return;
1266 	}
1267 
1268 	array_init(return_value);
1269 
1270 	add_next_index_stringl(return_value, "MD5", 3);
1271 	add_next_index_stringl(return_value, "SHA-1", 5);
1272 	add_next_index_stringl(return_value, "SHA-256", 7);
1273 	add_next_index_stringl(return_value, "SHA-512", 7);
1274 #if PHAR_HAVE_OPENSSL
1275 	add_next_index_stringl(return_value, "OpenSSL", 7);
1276 #else
1277 	if (zend_hash_str_exists(&module_registry, "openssl", sizeof("openssl")-1)) {
1278 		add_next_index_stringl(return_value, "OpenSSL", 7);
1279 	}
1280 #endif
1281 }
1282 /* }}} */
1283 
1284 /* {{{ proto array Phar::getSupportedCompression()
1285  * Return array of supported comparession algorithms
1286  */
PHP_METHOD(Phar,getSupportedCompression)1287 PHP_METHOD(Phar, getSupportedCompression)
1288 {
1289 	if (zend_parse_parameters_none() == FAILURE) {
1290 		return;
1291 	}
1292 
1293 	array_init(return_value);
1294 	phar_request_initialize();
1295 
1296 	if (PHAR_G(has_zlib)) {
1297 		add_next_index_stringl(return_value, "GZ", 2);
1298 	}
1299 
1300 	if (PHAR_G(has_bz2)) {
1301 		add_next_index_stringl(return_value, "BZIP2", 5);
1302 	}
1303 }
1304 /* }}} */
1305 
1306 /* {{{ proto array Phar::unlinkArchive(string archive)
1307  * Completely remove a phar archive from memory and disk
1308  */
PHP_METHOD(Phar,unlinkArchive)1309 PHP_METHOD(Phar, unlinkArchive)
1310 {
1311 	char *fname, *error, *zname, *arch, *entry;
1312 	size_t fname_len;
1313 	size_t zname_len, arch_len, entry_len;
1314 	phar_archive_data *phar;
1315 
1316 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
1317 		RETURN_FALSE;
1318 	}
1319 
1320 	if (!fname_len) {
1321 		zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"\"");
1322 		return;
1323 	}
1324 
1325 	if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) {
1326 		if (error) {
1327 			zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\": %s", fname, error);
1328 			efree(error);
1329 		} else {
1330 			zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown phar archive \"%s\"", fname);
1331 		}
1332 		return;
1333 	}
1334 
1335 	zname = (char*)zend_get_executed_filename();
1336 	zname_len = strlen(zname);
1337 
1338 	if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
1339 		if ((size_t)arch_len == fname_len && !memcmp(arch, fname, arch_len)) {
1340 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" cannot be unlinked from within itself", fname);
1341 			efree(arch);
1342 			efree(entry);
1343 			return;
1344 		}
1345 		efree(arch);
1346 		efree(entry);
1347 	}
1348 
1349 	if (phar->is_persistent) {
1350 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname);
1351 		return;
1352 	}
1353 
1354 	if (phar->refcount) {
1355 		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);
1356 		return;
1357 	}
1358 
1359 	fname = estrndup(phar->fname, phar->fname_len);
1360 
1361 	/* invalidate phar cache */
1362 	PHAR_G(last_phar) = NULL;
1363 	PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
1364 
1365 	phar_archive_delref(phar);
1366 	unlink(fname);
1367 	efree(fname);
1368 	RETURN_TRUE;
1369 }
1370 /* }}} */
1371 
1372 #define PHAR_ARCHIVE_OBJECT() \
1373 	zval *zobj = ZEND_THIS; \
1374 	phar_archive_object *phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); \
1375 	if (!phar_obj->archive) { \
1376 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
1377 			"Cannot call method on an uninitialized Phar object"); \
1378 		return; \
1379 	}
1380 
1381 /* {{{ proto Phar::__destruct()
1382  * if persistent, remove from the cache
1383  */
PHP_METHOD(Phar,__destruct)1384 PHP_METHOD(Phar, __destruct)
1385 {
1386 	zval *zobj = ZEND_THIS;
1387 	phar_archive_object *phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset);
1388 
1389 	if (phar_obj->archive && phar_obj->archive->is_persistent) {
1390 		zend_hash_str_del(&PHAR_G(phar_persist_map), (const char *) phar_obj->archive, sizeof(phar_obj->archive));
1391 	}
1392 }
1393 /* }}} */
1394 
1395 struct _phar_t {
1396 	phar_archive_object *p;
1397 	zend_class_entry *c;
1398 	char *b;
1399 	zval *ret;
1400 	php_stream *fp;
1401 	uint32_t l;
1402 	int count;
1403 };
1404 
phar_build(zend_object_iterator * iter,void * puser)1405 static int phar_build(zend_object_iterator *iter, void *puser) /* {{{ */
1406 {
1407 	zval *value;
1408 	zend_bool close_fp = 1;
1409 	struct _phar_t *p_obj = (struct _phar_t*) puser;
1410 	size_t str_key_len, base_len = p_obj->l;
1411 	phar_entry_data *data;
1412 	php_stream *fp;
1413 	size_t fname_len;
1414 	size_t contents_len;
1415 	char *fname, *error = NULL, *base = p_obj->b, *save = NULL, *temp = NULL;
1416 	zend_string *opened;
1417 	char *str_key;
1418 	zend_class_entry *ce = p_obj->c;
1419 	phar_archive_object *phar_obj = p_obj->p;
1420 	php_stream_statbuf ssb;
1421 	char ch;
1422 
1423 	value = iter->funcs->get_current_data(iter);
1424 
1425 	if (EG(exception)) {
1426 		return ZEND_HASH_APPLY_STOP;
1427 	}
1428 
1429 	if (!value) {
1430 		/* failure in get_current_data */
1431 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned no value", ZSTR_VAL(ce->name));
1432 		return ZEND_HASH_APPLY_STOP;
1433 	}
1434 
1435 	switch (Z_TYPE_P(value)) {
1436 		case IS_STRING:
1437 			break;
1438 		case IS_RESOURCE:
1439 			php_stream_from_zval_no_verify(fp, value);
1440 
1441 			if (!fp) {
1442 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Iterator %s returned an invalid stream handle", ZSTR_VAL(ce->name));
1443 				return ZEND_HASH_APPLY_STOP;
1444 			}
1445 
1446 			if (iter->funcs->get_current_key) {
1447 				zval key;
1448 				iter->funcs->get_current_key(iter, &key);
1449 
1450 				if (EG(exception)) {
1451 					return ZEND_HASH_APPLY_STOP;
1452 				}
1453 
1454 				if (Z_TYPE(key) != IS_STRING) {
1455 					zval_ptr_dtor(&key);
1456 					zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid key (must return a string)", ZSTR_VAL(ce->name));
1457 					return ZEND_HASH_APPLY_STOP;
1458 				}
1459 
1460 				str_key_len = Z_STRLEN(key);
1461 				str_key = estrndup(Z_STRVAL(key), str_key_len);
1462 
1463 				save = str_key;
1464 				zval_ptr_dtor_str(&key);
1465 			} else {
1466 				zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid key (must return a string)", ZSTR_VAL(ce->name));
1467 				return ZEND_HASH_APPLY_STOP;
1468 			}
1469 
1470 			close_fp = 0;
1471 			opened = zend_string_init("[stream]", sizeof("[stream]") - 1, 0);
1472 			goto after_open_fp;
1473 		case IS_OBJECT:
1474 			if (instanceof_function(Z_OBJCE_P(value), spl_ce_SplFileInfo)) {
1475 				char *test = NULL;
1476 				zval dummy;
1477 				spl_filesystem_object *intern = (spl_filesystem_object*)((char*)Z_OBJ_P(value) - Z_OBJ_P(value)->handlers->offset);
1478 
1479 				if (!base_len) {
1480 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Iterator %s returns an SplFileInfo object, so base directory must be specified", ZSTR_VAL(ce->name));
1481 					return ZEND_HASH_APPLY_STOP;
1482 				}
1483 
1484 				switch (intern->type) {
1485 					case SPL_FS_DIR:
1486 						test = spl_filesystem_object_get_path(intern, NULL);
1487 						fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name);
1488 						php_stat(fname, fname_len, FS_IS_DIR, &dummy);
1489 
1490 						if (Z_TYPE(dummy) == IS_TRUE) {
1491 							/* ignore directories */
1492 							efree(fname);
1493 							return ZEND_HASH_APPLY_KEEP;
1494 						}
1495 
1496 						test = expand_filepath(fname, NULL);
1497 						efree(fname);
1498 
1499 						if (test) {
1500 							fname = test;
1501 							fname_len = strlen(fname);
1502 						} else {
1503 							zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Could not resolve file path");
1504 							return ZEND_HASH_APPLY_STOP;
1505 						}
1506 
1507 						save = fname;
1508 						goto phar_spl_fileinfo;
1509 					case SPL_FS_INFO:
1510 					case SPL_FS_FILE:
1511 						fname = expand_filepath(intern->file_name, NULL);
1512 						if (!fname) {
1513 							zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Could not resolve file path");
1514 							return ZEND_HASH_APPLY_STOP;
1515 						}
1516 
1517 						fname_len = strlen(fname);
1518 						save = fname;
1519 						goto phar_spl_fileinfo;
1520 				}
1521 			}
1522 			/* fall-through */
1523 		default:
1524 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid value (must return a string)", ZSTR_VAL(ce->name));
1525 			return ZEND_HASH_APPLY_STOP;
1526 	}
1527 
1528 	fname = Z_STRVAL_P(value);
1529 	fname_len = Z_STRLEN_P(value);
1530 
1531 phar_spl_fileinfo:
1532 	if (base_len) {
1533 		temp = expand_filepath(base, NULL);
1534 		if (!temp) {
1535 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Could not resolve file path");
1536 			if (save) {
1537 				efree(save);
1538 			}
1539 			return ZEND_HASH_APPLY_STOP;
1540 		}
1541 
1542 		base = temp;
1543 		base_len = strlen(base);
1544 
1545 		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))) {
1546 			str_key_len = fname_len - base_len;
1547 
1548 			if (str_key_len <= 0) {
1549 				if (save) {
1550 					efree(save);
1551 					efree(temp);
1552 				}
1553 				return ZEND_HASH_APPLY_KEEP;
1554 			}
1555 
1556 			str_key = fname + base_len;
1557 
1558 			if (*str_key == '/' || *str_key == '\\') {
1559 				str_key++;
1560 				str_key_len--;
1561 			}
1562 
1563 		} else {
1564 			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);
1565 
1566 			if (save) {
1567 				efree(save);
1568 				efree(temp);
1569 			}
1570 
1571 			return ZEND_HASH_APPLY_STOP;
1572 		}
1573 	} else {
1574 		if (iter->funcs->get_current_key) {
1575 			zval key;
1576 			iter->funcs->get_current_key(iter, &key);
1577 
1578 			if (EG(exception)) {
1579 				return ZEND_HASH_APPLY_STOP;
1580 			}
1581 
1582 			if (Z_TYPE(key) != IS_STRING) {
1583 				zval_ptr_dtor(&key);
1584 				zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid key (must return a string)", ZSTR_VAL(ce->name));
1585 				return ZEND_HASH_APPLY_STOP;
1586 			}
1587 
1588 			str_key_len = Z_STRLEN(key);
1589 			str_key = estrndup(Z_STRVAL(key), str_key_len);
1590 
1591 			save = str_key;
1592 			zval_ptr_dtor_str(&key);
1593 		} else {
1594 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned an invalid key (must return a string)", ZSTR_VAL(ce->name));
1595 			return ZEND_HASH_APPLY_STOP;
1596 		}
1597 	}
1598 
1599 	if (php_check_open_basedir(fname)) {
1600 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned a path \"%s\" that open_basedir prevents opening", ZSTR_VAL(ce->name), fname);
1601 
1602 		if (save) {
1603 			efree(save);
1604 		}
1605 
1606 		if (temp) {
1607 			efree(temp);
1608 		}
1609 
1610 		return ZEND_HASH_APPLY_STOP;
1611 	}
1612 
1613 	/* try to open source file, then create internal phar file and copy contents */
1614 	fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened);
1615 
1616 	if (!fp) {
1617 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Iterator %s returned a file that could not be opened \"%s\"", ZSTR_VAL(ce->name), fname);
1618 
1619 		if (save) {
1620 			efree(save);
1621 		}
1622 
1623 		if (temp) {
1624 			efree(temp);
1625 		}
1626 
1627 		return ZEND_HASH_APPLY_STOP;
1628 	}
1629 after_open_fp:
1630 	if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) {
1631 		/* silently skip any files that would be added to the magic .phar directory */
1632 		if (save) {
1633 			efree(save);
1634 		}
1635 
1636 		if (temp) {
1637 			efree(temp);
1638 		}
1639 
1640 		if (opened) {
1641 			zend_string_release_ex(opened, 0);
1642 		}
1643 
1644 		if (close_fp) {
1645 			php_stream_close(fp);
1646 		}
1647 
1648 		return ZEND_HASH_APPLY_KEEP;
1649 	}
1650 
1651 	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))) {
1652 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s cannot be created: %s", str_key, error);
1653 		efree(error);
1654 
1655 		if (save) {
1656 			efree(save);
1657 		}
1658 
1659 		if (opened) {
1660 			zend_string_release_ex(opened, 0);
1661 		}
1662 
1663 		if (temp) {
1664 			efree(temp);
1665 		}
1666 
1667 		if (close_fp) {
1668 			php_stream_close(fp);
1669 		}
1670 
1671 		return ZEND_HASH_APPLY_STOP;
1672 
1673 	} else {
1674 		if (error) {
1675 			efree(error);
1676 		}
1677 		/* convert to PHAR_UFP */
1678 		if (data->internal_file->fp_type == PHAR_MOD) {
1679 			php_stream_close(data->internal_file->fp);
1680 		}
1681 
1682 		data->internal_file->fp = NULL;
1683 		data->internal_file->fp_type = PHAR_UFP;
1684 		data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp);
1685 		data->fp = NULL;
1686 		php_stream_copy_to_stream_ex(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len);
1687 		data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize =
1688 			php_stream_tell(p_obj->fp) - data->internal_file->offset;
1689 		if (php_stream_stat(fp, &ssb) != -1) {
1690 			data->internal_file->flags = ssb.sb.st_mode & PHAR_ENT_PERM_MASK ;
1691 		} else {
1692 #ifndef _WIN32
1693 			mode_t mask;
1694 			mask = umask(0);
1695 			umask(mask);
1696 			data->internal_file->flags &= ~mask;
1697 #endif
1698 		}
1699 	}
1700 
1701 	if (close_fp) {
1702 		php_stream_close(fp);
1703 	}
1704 
1705 	add_assoc_str(p_obj->ret, str_key, opened);
1706 
1707 	if (save) {
1708 		efree(save);
1709 	}
1710 
1711 	if (temp) {
1712 		efree(temp);
1713 	}
1714 
1715 	data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len;
1716 	phar_entry_delref(data);
1717 
1718 	return ZEND_HASH_APPLY_KEEP;
1719 }
1720 /* }}} */
1721 
1722 /* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex])
1723  * Construct a phar archive from an existing directory, recursively.
1724  * Optional second parameter is a regular expression for filtering directory contents.
1725  *
1726  * Return value is an array mapping phar index to actual files added.
1727  */
PHP_METHOD(Phar,buildFromDirectory)1728 PHP_METHOD(Phar, buildFromDirectory)
1729 {
1730 	char *dir, *error, *regex = NULL;
1731 	size_t dir_len, regex_len = 0;
1732 	zend_bool apply_reg = 0;
1733 	zval arg, arg2, iter, iteriter, regexiter;
1734 	struct _phar_t pass;
1735 
1736 	PHAR_ARCHIVE_OBJECT();
1737 
1738 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
1739 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1740 			"Cannot write to archive - write operations restricted by INI setting");
1741 		return;
1742 	}
1743 
1744 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s", &dir, &dir_len, &regex, &regex_len) == FAILURE) {
1745 		RETURN_FALSE;
1746 	}
1747 
1748 	if (ZEND_SIZE_T_UINT_OVFL(dir_len)) {
1749 		RETURN_FALSE;
1750 	}
1751 
1752 	if (SUCCESS != object_init_ex(&iter, spl_ce_RecursiveDirectoryIterator)) {
1753 		zval_ptr_dtor(&iter);
1754 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname);
1755 		RETURN_FALSE;
1756 	}
1757 
1758 	ZVAL_STRINGL(&arg, dir, dir_len);
1759 	ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
1760 
1761 	zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
1762 			&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
1763 
1764 	zval_ptr_dtor(&arg);
1765 	if (EG(exception)) {
1766 		zval_ptr_dtor(&iter);
1767 		RETURN_FALSE;
1768 	}
1769 
1770 	if (SUCCESS != object_init_ex(&iteriter, spl_ce_RecursiveIteratorIterator)) {
1771 		zval_ptr_dtor(&iter);
1772 		zval_ptr_dtor(&iteriter);
1773 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname);
1774 		RETURN_FALSE;
1775 	}
1776 
1777 	zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
1778 			&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, &iter);
1779 
1780 	if (EG(exception)) {
1781 		zval_ptr_dtor(&iter);
1782 		zval_ptr_dtor(&iteriter);
1783 		RETURN_FALSE;
1784 	}
1785 
1786 	zval_ptr_dtor(&iter);
1787 
1788 	if (regex_len > 0) {
1789 		apply_reg = 1;
1790 
1791 		if (SUCCESS != object_init_ex(&regexiter, spl_ce_RegexIterator)) {
1792 			zval_ptr_dtor(&iteriter);
1793 			zval_ptr_dtor(&regexiter);
1794 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate regex iterator for %s", phar_obj->archive->fname);
1795 			RETURN_FALSE;
1796 		}
1797 
1798 		ZVAL_STRINGL(&arg2, regex, regex_len);
1799 
1800 		zend_call_method_with_2_params(&regexiter, spl_ce_RegexIterator,
1801 			&spl_ce_RegexIterator->constructor, "__construct", NULL, &iteriter, &arg2);
1802 		zval_ptr_dtor(&arg2);
1803 	}
1804 
1805 	array_init(return_value);
1806 
1807 	pass.c = apply_reg ? Z_OBJCE(regexiter) : Z_OBJCE(iteriter);
1808 	pass.p = phar_obj;
1809 	pass.b = dir;
1810 	pass.l = (uint32_t)dir_len;
1811 	pass.count = 0;
1812 	pass.ret = return_value;
1813 	pass.fp = php_stream_fopen_tmpfile();
1814 	if (pass.fp == NULL) {
1815 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" unable to create temporary file", phar_obj->archive->fname);
1816 		return;
1817 	}
1818 
1819 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
1820 		zval_ptr_dtor(&iteriter);
1821 		if (apply_reg) {
1822 			zval_ptr_dtor(&regexiter);
1823 		}
1824 		php_stream_close(pass.fp);
1825 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
1826 		return;
1827 	}
1828 
1829 	if (SUCCESS == spl_iterator_apply((apply_reg ? &regexiter : &iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass)) {
1830 		zval_ptr_dtor(&iteriter);
1831 
1832 		if (apply_reg) {
1833 			zval_ptr_dtor(&regexiter);
1834 		}
1835 
1836 		phar_obj->archive->ufp = pass.fp;
1837 		phar_flush(phar_obj->archive, 0, 0, 0, &error);
1838 
1839 		if (error) {
1840 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
1841 			efree(error);
1842 		}
1843 
1844 	} else {
1845 		zval_ptr_dtor(&iteriter);
1846 		if (apply_reg) {
1847 			zval_ptr_dtor(&regexiter);
1848 		}
1849 		php_stream_close(pass.fp);
1850 	}
1851 }
1852 /* }}} */
1853 
1854 /* {{{ proto array Phar::buildFromIterator(Iterator iter[, string base_directory])
1855  * Construct a phar archive from an iterator.  The iterator must return a series of strings
1856  * that are full paths to files that should be added to the phar.  The iterator key should
1857  * be the path that the file will have within the phar archive.
1858  *
1859  * If base directory is specified, then the key will be ignored, and instead the portion of
1860  * the current value minus the base directory will be used
1861  *
1862  * Returned is an array mapping phar index to actual file added
1863  */
PHP_METHOD(Phar,buildFromIterator)1864 PHP_METHOD(Phar, buildFromIterator)
1865 {
1866 	zval *obj;
1867 	char *error;
1868 	size_t base_len = 0;
1869 	char *base = NULL;
1870 	struct _phar_t pass;
1871 
1872 	PHAR_ARCHIVE_OBJECT();
1873 
1874 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
1875 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1876 			"Cannot write out phar archive, phar is read-only");
1877 		return;
1878 	}
1879 
1880 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|s", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) {
1881 		RETURN_FALSE;
1882 	}
1883 
1884 	if (ZEND_SIZE_T_UINT_OVFL(base_len)) {
1885 		RETURN_FALSE;
1886 	}
1887 
1888 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
1889 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
1890 		return;
1891 	}
1892 
1893 	array_init(return_value);
1894 
1895 	pass.c = Z_OBJCE_P(obj);
1896 	pass.p = phar_obj;
1897 	pass.b = base;
1898 	pass.l = (uint32_t)base_len;
1899 	pass.ret = return_value;
1900 	pass.count = 0;
1901 	pass.fp = php_stream_fopen_tmpfile();
1902 	if (pass.fp == NULL) {
1903 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\": unable to create temporary file", phar_obj->archive->fname);
1904 		return;
1905 	}
1906 
1907 	if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass)) {
1908 		phar_obj->archive->ufp = pass.fp;
1909 		phar_flush(phar_obj->archive, 0, 0, 0, &error);
1910 		if (error) {
1911 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
1912 			efree(error);
1913 		}
1914 	} else {
1915 		php_stream_close(pass.fp);
1916 	}
1917 }
1918 /* }}} */
1919 
1920 /* {{{ proto int Phar::count()
1921  * Returns the number of entries in the Phar archive
1922  */
PHP_METHOD(Phar,count)1923 PHP_METHOD(Phar, count)
1924 {
1925 	/* mode can be ignored, maximum depth is 1 */
1926 	zend_long mode;
1927 	PHAR_ARCHIVE_OBJECT();
1928 
1929 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &mode) == FAILURE) {
1930 		RETURN_FALSE;
1931 	}
1932 
1933 	RETURN_LONG(zend_hash_num_elements(&phar_obj->archive->manifest));
1934 }
1935 /* }}} */
1936 
1937 /* {{{ proto bool Phar::isFileFormat(int format)
1938  * Returns true if the phar archive is based on the tar/zip/phar file format depending
1939  * on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in
1940  */
PHP_METHOD(Phar,isFileFormat)1941 PHP_METHOD(Phar, isFileFormat)
1942 {
1943 	zend_long type;
1944 	PHAR_ARCHIVE_OBJECT();
1945 
1946 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &type) == FAILURE) {
1947 		RETURN_FALSE;
1948 	}
1949 
1950 	switch (type) {
1951 		case PHAR_FORMAT_TAR:
1952 			RETURN_BOOL(phar_obj->archive->is_tar);
1953 		case PHAR_FORMAT_ZIP:
1954 			RETURN_BOOL(phar_obj->archive->is_zip);
1955 		case PHAR_FORMAT_PHAR:
1956 			RETURN_BOOL(!phar_obj->archive->is_tar && !phar_obj->archive->is_zip);
1957 		default:
1958 			zend_throw_exception_ex(phar_ce_PharException, 0, "Unknown file format specified");
1959 	}
1960 }
1961 /* }}} */
1962 
phar_copy_file_contents(phar_entry_info * entry,php_stream * fp)1963 static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp) /* {{{ */
1964 {
1965 	char *error;
1966 	zend_off_t offset;
1967 	phar_entry_info *link;
1968 
1969 	if (FAILURE == phar_open_entry_fp(entry, &error, 1)) {
1970 		if (error) {
1971 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1972 				"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents: %s", entry->phar->fname, entry->filename, error);
1973 			efree(error);
1974 		} else {
1975 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1976 				"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents", entry->phar->fname, entry->filename);
1977 		}
1978 		return FAILURE;
1979 	}
1980 
1981 	/* copy old contents in entirety */
1982 	phar_seek_efp(entry, 0, SEEK_SET, 0, 1);
1983 	offset = php_stream_tell(fp);
1984 	link = phar_get_link_source(entry);
1985 
1986 	if (!link) {
1987 		link = entry;
1988 	}
1989 
1990 	if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(link, 0), fp, link->uncompressed_filesize, NULL)) {
1991 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
1992 			"Cannot convert phar archive \"%s\", unable to copy entry \"%s\" contents", entry->phar->fname, entry->filename);
1993 		return FAILURE;
1994 	}
1995 
1996 	if (entry->fp_type == PHAR_MOD) {
1997 		/* save for potential restore on error */
1998 		entry->cfp = entry->fp;
1999 		entry->fp = NULL;
2000 	}
2001 
2002 	/* set new location of file contents */
2003 	entry->fp_type = PHAR_FP;
2004 	entry->offset = offset;
2005 	return SUCCESS;
2006 }
2007 /* }}} */
2008 
phar_rename_archive(phar_archive_data ** sphar,char * ext)2009 static zend_object *phar_rename_archive(phar_archive_data **sphar, char *ext) /* {{{ */
2010 {
2011 	const char *oldname = NULL;
2012 	phar_archive_data *phar = *sphar;
2013 	char *oldpath = NULL;
2014 	char *basename = NULL, *basepath = NULL;
2015 	char *newname = NULL, *newpath = NULL;
2016 	zval ret, arg1;
2017 	zend_class_entry *ce;
2018 	char *error = NULL;
2019 	const char *pcr_error;
2020 	size_t ext_len = ext ? strlen(ext) : 0;
2021 	size_t new_len, oldname_len, phar_ext_len;
2022 	phar_archive_data *pphar = NULL;
2023 	php_stream_statbuf ssb;
2024 
2025 	int phar_ext_list_len, i = 0;
2026 	char *ext_pos = NULL;
2027 	/* Array of PHAR extensions, Must be in order, starting with longest
2028 	 * ending with the shortest. */
2029 	char *phar_ext_list[] = {
2030 		".phar.tar.bz2",
2031 		".phar.tar.gz",
2032 		".phar.php",
2033 		".phar.bz2",
2034 		".phar.zip",
2035 		".phar.tar",
2036 		".phar.gz",
2037 		".tar.bz2",
2038 		".tar.gz",
2039 		".phar",
2040 		".tar",
2041 		".zip"
2042 	};
2043 
2044 	if (!ext) {
2045 		if (phar->is_zip) {
2046 
2047 			if (phar->is_data) {
2048 				ext = "zip";
2049 			} else {
2050 				ext = "phar.zip";
2051 			}
2052 
2053 		} else if (phar->is_tar) {
2054 
2055 			switch (phar->flags) {
2056 				case PHAR_FILE_COMPRESSED_GZ:
2057 					if (phar->is_data) {
2058 						ext = "tar.gz";
2059 					} else {
2060 						ext = "phar.tar.gz";
2061 					}
2062 					break;
2063 				case PHAR_FILE_COMPRESSED_BZ2:
2064 					if (phar->is_data) {
2065 						ext = "tar.bz2";
2066 					} else {
2067 						ext = "phar.tar.bz2";
2068 					}
2069 					break;
2070 				default:
2071 					if (phar->is_data) {
2072 						ext = "tar";
2073 					} else {
2074 						ext = "phar.tar";
2075 					}
2076 			}
2077 		} else {
2078 
2079 			switch (phar->flags) {
2080 				case PHAR_FILE_COMPRESSED_GZ:
2081 					ext = "phar.gz";
2082 					break;
2083 				case PHAR_FILE_COMPRESSED_BZ2:
2084 					ext = "phar.bz2";
2085 					break;
2086 				default:
2087 					ext = "phar";
2088 			}
2089 		}
2090 	} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {
2091 
2092 		if (phar->is_data) {
2093 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
2094 		} else {
2095 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
2096 		}
2097 		return NULL;
2098 	}
2099 
2100 
2101 	oldpath = estrndup(phar->fname, phar->fname_len);
2102 	if ((oldname = zend_memrchr(phar->fname, '/', phar->fname_len))) {
2103 		++oldname;
2104 	} else {
2105 		oldname = phar->fname;
2106 	}
2107 
2108 	oldname_len = strlen(oldname);
2109 	/* Copy the old name to create base for the new name */
2110 	basename = estrndup(oldname, oldname_len);
2111 
2112 	phar_ext_list_len = sizeof(phar_ext_list)/sizeof(phar_ext_list[0]);
2113 	/* Remove possible PHAR extensions */
2114 	/* phar_ext_list must be in order of longest extension to shortest */
2115 	for (i=0; i < phar_ext_list_len; i++) {
2116 		phar_ext_len = strlen(phar_ext_list[i]);
2117 		if (phar_ext_len && oldname_len > phar_ext_len) {
2118 			/* Check if the basename strings ends with the extension */
2119 			if (memcmp(phar_ext_list[i], basename + (oldname_len - phar_ext_len), phar_ext_len) == 0) {
2120 				ext_pos = basename + (oldname_len - phar_ext_len);
2121 				ext_pos[0] = '\0';
2122 				break;
2123 			}
2124 		}
2125 		ext_pos = NULL;
2126 	}
2127 
2128 	/* If no default PHAR extension found remove the last extension */
2129 	if (!ext_pos) {
2130 		ext_pos = strrchr(basename, '.');
2131 		if (ext_pos) {
2132 			ext_pos[0] = '\0';
2133 		}
2134 	}
2135 	ext_pos = NULL;
2136 
2137 	if (ext[0] == '.') {
2138 		++ext;
2139 	}
2140 	/* Append extension to the basename */
2141 	spprintf(&newname, 0, "%s.%s", basename, ext);
2142 	efree(basename);
2143 
2144 	basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));
2145 	new_len = spprintf(&newpath, 0, "%s%s", basepath, newname);
2146 	phar->fname_len = new_len;
2147 	phar->fname = newpath;
2148 	phar->ext = newpath + phar->fname_len - strlen(ext) - 1;
2149 	efree(basepath);
2150 	efree(newname);
2151 
2152 	if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, newpath, phar->fname_len))) {
2153 		efree(oldpath);
2154 		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);
2155 		return NULL;
2156 	}
2157 
2158 	if (NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), newpath, phar->fname_len))) {
2159 		if (pphar->fname_len == phar->fname_len && !memcmp(pphar->fname, phar->fname, phar->fname_len)) {
2160 			if (!zend_hash_num_elements(&phar->manifest)) {
2161 				pphar->is_tar = phar->is_tar;
2162 				pphar->is_zip = phar->is_zip;
2163 				pphar->is_data = phar->is_data;
2164 				pphar->flags = phar->flags;
2165 				pphar->fp = phar->fp;
2166 				phar->fp = NULL;
2167 				phar_destroy_phar_data(phar);
2168 				*sphar = NULL;
2169 				phar = pphar;
2170 				phar->refcount++;
2171 				newpath = oldpath;
2172 				goto its_ok;
2173 			}
2174 		}
2175 
2176 		efree(oldpath);
2177 		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);
2178 		return NULL;
2179 	}
2180 its_ok:
2181 	if (SUCCESS == php_stream_stat_path(newpath, &ssb)) {
2182 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar \"%s\" exists and must be unlinked prior to conversion", newpath);
2183 		efree(oldpath);
2184 		return NULL;
2185 	}
2186 	if (!phar->is_data) {
2187 		if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &ext_len, 1, 1, 1)) {
2188 			efree(oldpath);
2189 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "phar \"%s\" has invalid extension %s", phar->fname, ext);
2190 			return NULL;
2191 		}
2192 		phar->ext_len = ext_len;
2193 
2194 		if (phar->alias) {
2195 			if (phar->is_temporary_alias) {
2196 				phar->alias = NULL;
2197 				phar->alias_len = 0;
2198 			} else {
2199 				phar->alias = estrndup(newpath, strlen(newpath));
2200 				phar->alias_len = strlen(newpath);
2201 				phar->is_temporary_alias = 1;
2202 				zend_hash_str_update_ptr(&(PHAR_G(phar_alias_map)), newpath, phar->fname_len, phar);
2203 			}
2204 		}
2205 
2206 	} else {
2207 
2208 		if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &ext_len, 0, 1, 1)) {
2209 			efree(oldpath);
2210 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "data phar \"%s\" has invalid extension %s", phar->fname, ext);
2211 			return NULL;
2212 		}
2213 		phar->ext_len = ext_len;
2214 
2215 		phar->alias = NULL;
2216 		phar->alias_len = 0;
2217 	}
2218 
2219 	if ((!pphar || phar == pphar) && NULL == zend_hash_str_update_ptr(&(PHAR_G(phar_fname_map)), newpath, phar->fname_len, phar)) {
2220 		efree(oldpath);
2221 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname);
2222 		return NULL;
2223 	}
2224 
2225 	phar_flush(phar, 0, 0, 1, &error);
2226 
2227 	if (error) {
2228 		zend_hash_str_del(&(PHAR_G(phar_fname_map)), newpath, phar->fname_len);
2229 		*sphar = NULL;
2230 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "%s", error);
2231 		efree(error);
2232 		efree(oldpath);
2233 		return NULL;
2234 	}
2235 
2236 	efree(oldpath);
2237 
2238 	if (phar->is_data) {
2239 		ce = phar_ce_data;
2240 	} else {
2241 		ce = phar_ce_archive;
2242 	}
2243 
2244 	ZVAL_NULL(&ret);
2245 	if (SUCCESS != object_init_ex(&ret, ce)) {
2246 		zval_ptr_dtor(&ret);
2247 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname);
2248 		return NULL;
2249 	}
2250 
2251 	ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len);
2252 
2253 	zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1);
2254 	zval_ptr_dtor(&arg1);
2255 	return Z_OBJ(ret);
2256 }
2257 /* }}} */
2258 
phar_convert_to_other(phar_archive_data * source,int convert,char * ext,uint32_t flags)2259 static zend_object *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, uint32_t flags) /* {{{ */
2260 {
2261 	phar_archive_data *phar;
2262 	phar_entry_info *entry, newentry;
2263 	zend_object *ret;
2264 
2265 	/* invalidate phar cache */
2266 	PHAR_G(last_phar) = NULL;
2267 	PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
2268 
2269 	phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data));
2270 	/* set whole-archive compression and type from parameter */
2271 	phar->flags = flags;
2272 	phar->is_data = source->is_data;
2273 
2274 	switch (convert) {
2275 		case PHAR_FORMAT_TAR:
2276 			phar->is_tar = 1;
2277 			break;
2278 		case PHAR_FORMAT_ZIP:
2279 			phar->is_zip = 1;
2280 			break;
2281 		default:
2282 			phar->is_data = 0;
2283 			break;
2284 	}
2285 
2286 	zend_hash_init(&(phar->manifest), sizeof(phar_entry_info),
2287 		zend_get_hash_value, destroy_phar_manifest_entry, 0);
2288 	zend_hash_init(&phar->mounted_dirs, sizeof(char *),
2289 		zend_get_hash_value, NULL, 0);
2290 	zend_hash_init(&phar->virtual_dirs, sizeof(char *),
2291 		zend_get_hash_value, NULL, 0);
2292 
2293 	phar->fp = php_stream_fopen_tmpfile();
2294 	if (phar->fp == NULL) {
2295 		zend_throw_exception_ex(phar_ce_PharException, 0, "unable to create temporary file");
2296 		return NULL;
2297 	}
2298 	phar->fname = source->fname;
2299 	phar->fname_len = source->fname_len;
2300 	phar->is_temporary_alias = source->is_temporary_alias;
2301 	phar->alias = source->alias;
2302 
2303 	if (Z_TYPE(source->metadata) != IS_UNDEF) {
2304 		ZVAL_DUP(&phar->metadata, &source->metadata);
2305 		phar->metadata_len = 0;
2306 	}
2307 
2308 	/* first copy each file's uncompressed contents to a temporary file and set per-file flags */
2309 	ZEND_HASH_FOREACH_PTR(&source->manifest, entry) {
2310 
2311 		newentry = *entry;
2312 
2313 		if (newentry.link) {
2314 			newentry.link = estrdup(newentry.link);
2315 			goto no_copy;
2316 		}
2317 
2318 		if (newentry.tmp) {
2319 			newentry.tmp = estrdup(newentry.tmp);
2320 			goto no_copy;
2321 		}
2322 
2323 		newentry.metadata_str.s = NULL;
2324 
2325 		if (FAILURE == phar_copy_file_contents(&newentry, phar->fp)) {
2326 			zend_hash_destroy(&(phar->manifest));
2327 			php_stream_close(phar->fp);
2328 			efree(phar);
2329 			/* exception already thrown */
2330 			return NULL;
2331 		}
2332 no_copy:
2333 		newentry.filename = estrndup(newentry.filename, newentry.filename_len);
2334 
2335 		if (Z_TYPE(newentry.metadata) != IS_UNDEF) {
2336 			zval_copy_ctor(&newentry.metadata);
2337 			newentry.metadata_str.s = NULL;
2338 		}
2339 
2340 		newentry.is_zip = phar->is_zip;
2341 		newentry.is_tar = phar->is_tar;
2342 
2343 		if (newentry.is_tar) {
2344 			newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE);
2345 		}
2346 
2347 		newentry.is_modified = 1;
2348 		newentry.phar = phar;
2349 		newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; /* remove compression from old_flags */
2350 		phar_set_inode(&newentry);
2351 		zend_hash_str_add_mem(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info));
2352 		phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len);
2353 	} ZEND_HASH_FOREACH_END();
2354 
2355 	if ((ret = phar_rename_archive(&phar, ext))) {
2356 		return ret;
2357 	} else {
2358 		if(phar != NULL) {
2359 			zend_hash_destroy(&(phar->manifest));
2360 			zend_hash_destroy(&(phar->mounted_dirs));
2361 			zend_hash_destroy(&(phar->virtual_dirs));
2362 			if (phar->fp) {
2363 				php_stream_close(phar->fp);
2364 			}
2365 			efree(phar->fname);
2366 			efree(phar);
2367 		}
2368 		return NULL;
2369 	}
2370 }
2371 /* }}} */
2372 
2373 /* {{{ proto object Phar::convertToExecutable([int format[, int compression [, string file_ext]]])
2374  * Convert a phar.tar or phar.zip archive to the phar file format. The
2375  * optional parameter allows the user to determine the new
2376  * filename extension (default is phar).
2377  */
PHP_METHOD(Phar,convertToExecutable)2378 PHP_METHOD(Phar, convertToExecutable)
2379 {
2380 	char *ext = NULL;
2381 	int is_data;
2382 	size_t ext_len = 0;
2383 	uint32_t flags;
2384 	zend_object *ret;
2385 	/* a number that is not 0, 1 or 2 (Which is also Greg's birthday, so there) */
2386 	zend_long format = 9021976, method = 9021976;
2387 	PHAR_ARCHIVE_OBJECT();
2388 
2389 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|lls", &format, &method, &ext, &ext_len) == FAILURE) {
2390 		return;
2391 	}
2392 
2393 	if (PHAR_G(readonly)) {
2394 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2395 			"Cannot write out executable phar archive, phar is read-only");
2396 		return;
2397 	}
2398 
2399 	switch (format) {
2400 		case 9021976:
2401 		case PHAR_FORMAT_SAME: /* null is converted to 0 */
2402 			/* by default, use the existing format */
2403 			if (phar_obj->archive->is_tar) {
2404 				format = PHAR_FORMAT_TAR;
2405 			} else if (phar_obj->archive->is_zip) {
2406 				format = PHAR_FORMAT_ZIP;
2407 			} else {
2408 				format = PHAR_FORMAT_PHAR;
2409 			}
2410 			break;
2411 		case PHAR_FORMAT_PHAR:
2412 		case PHAR_FORMAT_TAR:
2413 		case PHAR_FORMAT_ZIP:
2414 			break;
2415 		default:
2416 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2417 				"Unknown file format specified, please pass one of Phar::PHAR, Phar::TAR or Phar::ZIP");
2418 			return;
2419 	}
2420 
2421 	switch (method) {
2422 		case 9021976:
2423 			flags = phar_obj->archive->flags & PHAR_FILE_COMPRESSION_MASK;
2424 			break;
2425 		case 0:
2426 			flags = PHAR_FILE_COMPRESSED_NONE;
2427 			break;
2428 		case PHAR_ENT_COMPRESSED_GZ:
2429 			if (format == PHAR_FORMAT_ZIP) {
2430 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2431 					"Cannot compress entire archive with gzip, zip archives do not support whole-archive compression");
2432 				return;
2433 			}
2434 
2435 			if (!PHAR_G(has_zlib)) {
2436 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2437 					"Cannot compress entire archive with gzip, enable ext/zlib in php.ini");
2438 				return;
2439 			}
2440 
2441 			flags = PHAR_FILE_COMPRESSED_GZ;
2442 			break;
2443 		case PHAR_ENT_COMPRESSED_BZ2:
2444 			if (format == PHAR_FORMAT_ZIP) {
2445 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2446 					"Cannot compress entire archive with bz2, zip archives do not support whole-archive compression");
2447 				return;
2448 			}
2449 
2450 			if (!PHAR_G(has_bz2)) {
2451 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2452 					"Cannot compress entire archive with bz2, enable ext/bz2 in php.ini");
2453 				return;
2454 			}
2455 
2456 			flags = PHAR_FILE_COMPRESSED_BZ2;
2457 			break;
2458 		default:
2459 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2460 				"Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2");
2461 			return;
2462 	}
2463 
2464 	is_data = phar_obj->archive->is_data;
2465 	phar_obj->archive->is_data = 0;
2466 	ret = phar_convert_to_other(phar_obj->archive, format, ext, flags);
2467 	phar_obj->archive->is_data = is_data;
2468 
2469 	if (ret) {
2470 		ZVAL_OBJ(return_value, ret);
2471 	} else {
2472 		RETURN_NULL();
2473 	}
2474 }
2475 /* }}} */
2476 
2477 /* {{{ proto object Phar::convertToData([int format[, int compression [, string file_ext]]])
2478  * Convert an archive to a non-executable .tar or .zip.
2479  * The optional parameter allows the user to determine the new
2480  * filename extension (default is .zip or .tar).
2481  */
PHP_METHOD(Phar,convertToData)2482 PHP_METHOD(Phar, convertToData)
2483 {
2484 	char *ext = NULL;
2485 	int is_data;
2486 	size_t ext_len = 0;
2487 	uint32_t flags;
2488 	zend_object *ret;
2489 	/* a number that is not 0, 1 or 2 (Which is also Greg's birthday so there) */
2490 	zend_long format = 9021976, method = 9021976;
2491 	PHAR_ARCHIVE_OBJECT();
2492 
2493 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|lls", &format, &method, &ext, &ext_len) == FAILURE) {
2494 		return;
2495 	}
2496 
2497 	switch (format) {
2498 		case 9021976:
2499 		case PHAR_FORMAT_SAME: /* null is converted to 0 */
2500 			/* by default, use the existing format */
2501 			if (phar_obj->archive->is_tar) {
2502 				format = PHAR_FORMAT_TAR;
2503 			} else if (phar_obj->archive->is_zip) {
2504 				format = PHAR_FORMAT_ZIP;
2505 			} else {
2506 				zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2507 					"Cannot write out data phar archive, use Phar::TAR or Phar::ZIP");
2508 				return;
2509 			}
2510 			break;
2511 		case PHAR_FORMAT_PHAR:
2512 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2513 				"Cannot write out data phar archive, use Phar::TAR or Phar::ZIP");
2514 			return;
2515 		case PHAR_FORMAT_TAR:
2516 		case PHAR_FORMAT_ZIP:
2517 			break;
2518 		default:
2519 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2520 				"Unknown file format specified, please pass one of Phar::TAR or Phar::ZIP");
2521 			return;
2522 	}
2523 
2524 	switch (method) {
2525 		case 9021976:
2526 			flags = phar_obj->archive->flags & PHAR_FILE_COMPRESSION_MASK;
2527 			break;
2528 		case 0:
2529 			flags = PHAR_FILE_COMPRESSED_NONE;
2530 			break;
2531 		case PHAR_ENT_COMPRESSED_GZ:
2532 			if (format == PHAR_FORMAT_ZIP) {
2533 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2534 					"Cannot compress entire archive with gzip, zip archives do not support whole-archive compression");
2535 				return;
2536 			}
2537 
2538 			if (!PHAR_G(has_zlib)) {
2539 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2540 					"Cannot compress entire archive with gzip, enable ext/zlib in php.ini");
2541 				return;
2542 			}
2543 
2544 			flags = PHAR_FILE_COMPRESSED_GZ;
2545 			break;
2546 		case PHAR_ENT_COMPRESSED_BZ2:
2547 			if (format == PHAR_FORMAT_ZIP) {
2548 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2549 					"Cannot compress entire archive with bz2, zip archives do not support whole-archive compression");
2550 				return;
2551 			}
2552 
2553 			if (!PHAR_G(has_bz2)) {
2554 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2555 					"Cannot compress entire archive with bz2, enable ext/bz2 in php.ini");
2556 				return;
2557 			}
2558 
2559 			flags = PHAR_FILE_COMPRESSED_BZ2;
2560 			break;
2561 		default:
2562 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
2563 				"Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2");
2564 			return;
2565 	}
2566 
2567 	is_data = phar_obj->archive->is_data;
2568 	phar_obj->archive->is_data = 1;
2569 	ret = phar_convert_to_other(phar_obj->archive, (int)format, ext, flags);
2570 	phar_obj->archive->is_data = is_data;
2571 
2572 	if (ret) {
2573 		ZVAL_OBJ(return_value, ret);
2574 	} else {
2575 		RETURN_NULL();
2576 	}
2577 }
2578 /* }}} */
2579 
2580 /* {{{ proto int|false Phar::isCompressed()
2581  * Returns Phar::GZ or PHAR::BZ2 if the entire archive is compressed
2582  * (.tar.gz/tar.bz2 and so on), or FALSE otherwise.
2583  */
PHP_METHOD(Phar,isCompressed)2584 PHP_METHOD(Phar, isCompressed)
2585 {
2586 	PHAR_ARCHIVE_OBJECT();
2587 
2588 	if (zend_parse_parameters_none() == FAILURE) {
2589 		return;
2590 	}
2591 
2592 	if (phar_obj->archive->flags & PHAR_FILE_COMPRESSED_GZ) {
2593 		RETURN_LONG(PHAR_ENT_COMPRESSED_GZ);
2594 	}
2595 
2596 	if (phar_obj->archive->flags & PHAR_FILE_COMPRESSED_BZ2) {
2597 		RETURN_LONG(PHAR_ENT_COMPRESSED_BZ2);
2598 	}
2599 
2600 	RETURN_FALSE;
2601 }
2602 /* }}} */
2603 
2604 /* {{{ proto bool Phar::isWritable()
2605  * Returns true if phar.readonly=0 or phar is a PharData AND the actual file is writable.
2606  */
PHP_METHOD(Phar,isWritable)2607 PHP_METHOD(Phar, isWritable)
2608 {
2609 	php_stream_statbuf ssb;
2610 	PHAR_ARCHIVE_OBJECT();
2611 
2612 	if (zend_parse_parameters_none() == FAILURE) {
2613 		return;
2614 	}
2615 
2616 	if (!phar_obj->archive->is_writeable) {
2617 		RETURN_FALSE;
2618 	}
2619 
2620 	if (SUCCESS != php_stream_stat_path(phar_obj->archive->fname, &ssb)) {
2621 		if (phar_obj->archive->is_brandnew) {
2622 			/* assume it works if the file doesn't exist yet */
2623 			RETURN_TRUE;
2624 		}
2625 		RETURN_FALSE;
2626 	}
2627 
2628 	RETURN_BOOL((ssb.sb.st_mode & (S_IWOTH | S_IWGRP | S_IWUSR)) != 0);
2629 }
2630 /* }}} */
2631 
2632 /* {{{ proto bool Phar::delete(string entry)
2633  * Deletes a named file within the archive.
2634  */
PHP_METHOD(Phar,delete)2635 PHP_METHOD(Phar, delete)
2636 {
2637 	char *fname;
2638 	size_t fname_len;
2639 	char *error;
2640 	phar_entry_info *entry;
2641 	PHAR_ARCHIVE_OBJECT();
2642 
2643 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
2644 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2645 			"Cannot write out phar archive, phar is read-only");
2646 		return;
2647 	}
2648 
2649 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
2650 		RETURN_FALSE;
2651 	}
2652 
2653 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
2654 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
2655 		return;
2656 	}
2657 	if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint32_t) fname_len)) {
2658 		if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint32_t) fname_len))) {
2659 			if (entry->is_deleted) {
2660 				/* entry is deleted, but has not been flushed to disk yet */
2661 				RETURN_TRUE;
2662 			} else {
2663 				entry->is_deleted = 1;
2664 				entry->is_modified = 1;
2665 				phar_obj->archive->is_modified = 1;
2666 			}
2667 		}
2668 	} else {
2669 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname);
2670 		RETURN_FALSE;
2671 	}
2672 
2673 	phar_flush(phar_obj->archive, NULL, 0, 0, &error);
2674 	if (error) {
2675 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
2676 		efree(error);
2677 	}
2678 
2679 	RETURN_TRUE;
2680 }
2681 /* }}} */
2682 
2683 /* {{{ proto int Phar::getAlias()
2684  * Returns the alias for the Phar or NULL.
2685  */
PHP_METHOD(Phar,getAlias)2686 PHP_METHOD(Phar, getAlias)
2687 {
2688 	PHAR_ARCHIVE_OBJECT();
2689 
2690 	if (zend_parse_parameters_none() == FAILURE) {
2691 		return;
2692 	}
2693 
2694 	if (phar_obj->archive->alias && phar_obj->archive->alias != phar_obj->archive->fname) {
2695 		RETURN_STRINGL(phar_obj->archive->alias, phar_obj->archive->alias_len);
2696 	}
2697 }
2698 /* }}} */
2699 
2700 /* {{{ proto int Phar::getPath()
2701  * Returns the real path to the phar archive on disk
2702  */
PHP_METHOD(Phar,getPath)2703 PHP_METHOD(Phar, getPath)
2704 {
2705 	PHAR_ARCHIVE_OBJECT();
2706 
2707 	if (zend_parse_parameters_none() == FAILURE) {
2708 		return;
2709 	}
2710 
2711 	RETURN_STRINGL(phar_obj->archive->fname, phar_obj->archive->fname_len);
2712 }
2713 /* }}} */
2714 
2715 /* {{{ proto bool Phar::setAlias(string alias)
2716  * Sets the alias for a Phar archive. The default value is the full path
2717  * to the archive.
2718  */
PHP_METHOD(Phar,setAlias)2719 PHP_METHOD(Phar, setAlias)
2720 {
2721 	char *alias, *error, *oldalias;
2722 	phar_archive_data *fd_ptr;
2723 	size_t alias_len, oldalias_len;
2724 	int old_temp, readd = 0;
2725 
2726 	PHAR_ARCHIVE_OBJECT();
2727 
2728 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
2729 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2730 			"Cannot write out phar archive, phar is read-only");
2731 		RETURN_FALSE;
2732 	}
2733 
2734 	/* invalidate phar cache */
2735 	PHAR_G(last_phar) = NULL;
2736 	PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
2737 
2738 	if (phar_obj->archive->is_data) {
2739 		if (phar_obj->archive->is_tar) {
2740 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2741 				"A Phar alias cannot be set in a plain tar archive");
2742 		} else {
2743 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2744 				"A Phar alias cannot be set in a plain zip archive");
2745 		}
2746 		RETURN_FALSE;
2747 	}
2748 
2749 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &alias, &alias_len) == SUCCESS) {
2750 		if (alias_len == phar_obj->archive->alias_len && memcmp(phar_obj->archive->alias, alias, alias_len) == 0) {
2751 			RETURN_TRUE;
2752 		}
2753 		if (alias_len && NULL != (fd_ptr = zend_hash_str_find_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len))) {
2754 			spprintf(&error, 0, "alias \"%s\" is already used for archive \"%s\" and cannot be used for other archives", alias, fd_ptr->fname);
2755 			if (SUCCESS == phar_free_alias(fd_ptr, alias, alias_len)) {
2756 				efree(error);
2757 				goto valid_alias;
2758 			}
2759 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
2760 			efree(error);
2761 			RETURN_FALSE;
2762 		}
2763 		if (!phar_validate_alias(alias, alias_len)) {
2764 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2765 				"Invalid alias \"%s\" specified for phar \"%s\"", alias, phar_obj->archive->fname);
2766 			RETURN_FALSE;
2767 		}
2768 valid_alias:
2769 		if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
2770 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
2771 			return;
2772 		}
2773 		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))) {
2774 			zend_hash_str_del(&(PHAR_G(phar_alias_map)), phar_obj->archive->alias, phar_obj->archive->alias_len);
2775 			readd = 1;
2776 		}
2777 
2778 		oldalias = phar_obj->archive->alias;
2779 		oldalias_len = phar_obj->archive->alias_len;
2780 		old_temp = phar_obj->archive->is_temporary_alias;
2781 
2782 		if (alias_len) {
2783 			phar_obj->archive->alias = estrndup(alias, alias_len);
2784 		} else {
2785 			phar_obj->archive->alias = NULL;
2786 		}
2787 
2788 		phar_obj->archive->alias_len = alias_len;
2789 		phar_obj->archive->is_temporary_alias = 0;
2790 		phar_flush(phar_obj->archive, NULL, 0, 0, &error);
2791 
2792 		if (error) {
2793 			phar_obj->archive->alias = oldalias;
2794 			phar_obj->archive->alias_len = oldalias_len;
2795 			phar_obj->archive->is_temporary_alias = old_temp;
2796 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
2797 			if (readd) {
2798 				zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), oldalias, oldalias_len, phar_obj->archive);
2799 			}
2800 			efree(error);
2801 			RETURN_FALSE;
2802 		}
2803 
2804 		zend_hash_str_add_ptr(&(PHAR_G(phar_alias_map)), alias, alias_len, phar_obj->archive);
2805 
2806 		if (oldalias) {
2807 			efree(oldalias);
2808 		}
2809 
2810 		RETURN_TRUE;
2811 	}
2812 
2813 	RETURN_FALSE;
2814 }
2815 /* }}} */
2816 
2817 /* {{{ proto string Phar::getVersion()
2818  * Return version info of Phar archive
2819  */
PHP_METHOD(Phar,getVersion)2820 PHP_METHOD(Phar, getVersion)
2821 {
2822 	PHAR_ARCHIVE_OBJECT();
2823 
2824 	if (zend_parse_parameters_none() == FAILURE) {
2825 		return;
2826 	}
2827 
2828 	RETURN_STRING(phar_obj->archive->version);
2829 }
2830 /* }}} */
2831 
2832 /* {{{ proto void Phar::startBuffering()
2833  * Do not flush a writeable phar (save its contents) until explicitly requested
2834  */
PHP_METHOD(Phar,startBuffering)2835 PHP_METHOD(Phar, startBuffering)
2836 {
2837 	PHAR_ARCHIVE_OBJECT();
2838 
2839 	if (zend_parse_parameters_none() == FAILURE) {
2840 		return;
2841 	}
2842 
2843 	phar_obj->archive->donotflush = 1;
2844 }
2845 /* }}} */
2846 
2847 /* {{{ proto bool Phar::isBuffering()
2848  * Returns whether write operations are flushing to disk immediately.
2849  */
PHP_METHOD(Phar,isBuffering)2850 PHP_METHOD(Phar, isBuffering)
2851 {
2852 	PHAR_ARCHIVE_OBJECT();
2853 
2854 	if (zend_parse_parameters_none() == FAILURE) {
2855 		return;
2856 	}
2857 
2858 	RETURN_BOOL(phar_obj->archive->donotflush);
2859 }
2860 /* }}} */
2861 
2862 /* {{{ proto bool Phar::stopBuffering()
2863  * Saves the contents of a modified archive to disk.
2864  */
PHP_METHOD(Phar,stopBuffering)2865 PHP_METHOD(Phar, stopBuffering)
2866 {
2867 	char *error;
2868 
2869 	PHAR_ARCHIVE_OBJECT();
2870 
2871 	if (zend_parse_parameters_none() == FAILURE) {
2872 		return;
2873 	}
2874 
2875 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
2876 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2877 			"Cannot write out phar archive, phar is read-only");
2878 		return;
2879 	}
2880 
2881 	phar_obj->archive->donotflush = 0;
2882 	phar_flush(phar_obj->archive, 0, 0, 0, &error);
2883 
2884 	if (error) {
2885 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
2886 		efree(error);
2887 	}
2888 }
2889 /* }}} */
2890 
2891 /* {{{ proto bool Phar::setStub(string|stream stub [, int len])
2892  * Change the stub in a phar, phar.tar or phar.zip archive to something other
2893  * than the default. The stub *must* end with a call to __HALT_COMPILER().
2894  */
PHP_METHOD(Phar,setStub)2895 PHP_METHOD(Phar, setStub)
2896 {
2897 	zval *zstub;
2898 	char *stub, *error;
2899 	size_t stub_len;
2900 	zend_long len = -1;
2901 	php_stream *stream;
2902 	PHAR_ARCHIVE_OBJECT();
2903 
2904 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
2905 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2906 			"Cannot change stub, phar is read-only");
2907 		return;
2908 	}
2909 
2910 	if (phar_obj->archive->is_data) {
2911 		if (phar_obj->archive->is_tar) {
2912 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2913 				"A Phar stub cannot be set in a plain tar archive");
2914 		} else {
2915 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2916 				"A Phar stub cannot be set in a plain zip archive");
2917 		}
2918 		return;
2919 	}
2920 
2921 	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r|l", &zstub, &len) == SUCCESS) {
2922 		if ((php_stream_from_zval_no_verify(stream, zstub)) != NULL) {
2923 			if (len > 0) {
2924 				len = -len;
2925 			} else {
2926 				len = -1;
2927 			}
2928 			if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
2929 				zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
2930 				return;
2931 			}
2932 			phar_flush(phar_obj->archive, (char *) zstub, len, 0, &error);
2933 			if (error) {
2934 				zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
2935 				efree(error);
2936 			}
2937 			RETURN_TRUE;
2938 		} else {
2939 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2940 				"Cannot change stub, unable to read from input stream");
2941 		}
2942 	} else if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &stub, &stub_len) == SUCCESS) {
2943 		if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
2944 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
2945 			return;
2946 		}
2947 		phar_flush(phar_obj->archive, stub, stub_len, 0, &error);
2948 
2949 		if (error) {
2950 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
2951 			efree(error);
2952 		}
2953 
2954 		RETURN_TRUE;
2955 	}
2956 
2957 	RETURN_FALSE;
2958 }
2959 /* }}} */
2960 
2961 /* {{{ proto bool Phar::setDefaultStub([string index[, string webindex]])
2962  * In a pure phar archive, sets a stub that can be used to run the archive
2963  * regardless of whether the phar extension is available. The first parameter
2964  * is the CLI startup filename, which defaults to "index.php". The second
2965  * parameter is the web startup filename and also defaults to "index.php"
2966  * (falling back to CLI behaviour).
2967  * Both parameters are optional.
2968  * In a phar.zip or phar.tar archive, the default stub is used only to
2969  * identify the archive to the extension as a Phar object. This allows the
2970  * extension to treat phar.zip and phar.tar types as honorary phars. Since
2971  * files cannot be loaded via this kind of stub, no parameters are accepted
2972  * when the Phar object is zip- or tar-based.
2973  */
PHP_METHOD(Phar,setDefaultStub)2974 PHP_METHOD(Phar, setDefaultStub)
2975 {
2976 	char *index = NULL, *webindex = NULL, *error = NULL;
2977 	zend_string *stub = NULL;
2978 	size_t index_len = 0, webindex_len = 0;
2979 	int created_stub = 0;
2980 	PHAR_ARCHIVE_OBJECT();
2981 
2982 	if (phar_obj->archive->is_data) {
2983 		if (phar_obj->archive->is_tar) {
2984 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2985 				"A Phar stub cannot be set in a plain tar archive");
2986 		} else {
2987 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
2988 				"A Phar stub cannot be set in a plain zip archive");
2989 		}
2990 		return;
2991 	}
2992 
2993 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!s", &index, &index_len, &webindex, &webindex_len) == FAILURE) {
2994 		RETURN_FALSE;
2995 	}
2996 
2997 	if (ZEND_NUM_ARGS() > 0 && (phar_obj->archive->is_tar || phar_obj->archive->is_zip)) {
2998 		php_error_docref(NULL, E_WARNING, "method accepts no arguments for a tar- or zip-based phar stub, %d given", ZEND_NUM_ARGS());
2999 		RETURN_FALSE;
3000 	}
3001 
3002 	if (PHAR_G(readonly)) {
3003 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3004 			"Cannot change stub: phar.readonly=1");
3005 		RETURN_FALSE;
3006 	}
3007 
3008 	if (!phar_obj->archive->is_tar && !phar_obj->archive->is_zip) {
3009 		stub = phar_create_default_stub(index, webindex, &error);
3010 
3011 		if (error) {
3012 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "%s", error);
3013 			efree(error);
3014 			if (stub) {
3015 				zend_string_free(stub);
3016 			}
3017 			RETURN_FALSE;
3018 		}
3019 
3020 		created_stub = 1;
3021 	}
3022 
3023 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
3024 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
3025 		return;
3026 	}
3027 	phar_flush(phar_obj->archive, stub ? ZSTR_VAL(stub) : 0, stub ? ZSTR_LEN(stub) : 0, 1, &error);
3028 
3029 	if (created_stub) {
3030 		zend_string_free(stub);
3031 	}
3032 
3033 	if (error) {
3034 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3035 		efree(error);
3036 		RETURN_FALSE;
3037 	}
3038 
3039 	RETURN_TRUE;
3040 }
3041 /* }}} */
3042 
3043 /* {{{ proto array Phar::setSignatureAlgorithm(int sigtype[, string privatekey])
3044  * Sets the signature algorithm for a phar and applies it. The signature
3045  * algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256,
3046  * Phar::SHA512, or Phar::OPENSSL. Note that zip- based phar archives
3047  * cannot support signatures.
3048  */
PHP_METHOD(Phar,setSignatureAlgorithm)3049 PHP_METHOD(Phar, setSignatureAlgorithm)
3050 {
3051 	zend_long algo;
3052 	char *error, *key = NULL;
3053 	size_t key_len = 0;
3054 
3055 	PHAR_ARCHIVE_OBJECT();
3056 
3057 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3058 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3059 			"Cannot set signature algorithm, phar is read-only");
3060 		return;
3061 	}
3062 
3063 	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "l|s", &algo, &key, &key_len) != SUCCESS) {
3064 		return;
3065 	}
3066 
3067 	switch (algo) {
3068 		case PHAR_SIG_SHA256:
3069 		case PHAR_SIG_SHA512:
3070 		case PHAR_SIG_MD5:
3071 		case PHAR_SIG_SHA1:
3072 		case PHAR_SIG_OPENSSL:
3073 			if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
3074 				zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
3075 				return;
3076 			}
3077 			phar_obj->archive->sig_flags = (php_uint32)algo;
3078 			phar_obj->archive->is_modified = 1;
3079 			PHAR_G(openssl_privatekey) = key;
3080 			PHAR_G(openssl_privatekey_len) = key_len;
3081 
3082 			phar_flush(phar_obj->archive, 0, 0, 0, &error);
3083 			if (error) {
3084 				zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3085 				efree(error);
3086 			}
3087 			break;
3088 		default:
3089 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3090 				"Unknown signature algorithm specified");
3091 	}
3092 }
3093 /* }}} */
3094 
3095 /* {{{ proto array|false Phar::getSignature()
3096  * Returns a hash signature, or FALSE if the archive is unsigned.
3097  */
PHP_METHOD(Phar,getSignature)3098 PHP_METHOD(Phar, getSignature)
3099 {
3100 	PHAR_ARCHIVE_OBJECT();
3101 
3102 	if (zend_parse_parameters_none() == FAILURE) {
3103 		return;
3104 	}
3105 
3106 	if (phar_obj->archive->signature) {
3107 		zend_string *unknown;
3108 
3109 		array_init(return_value);
3110 		add_assoc_stringl(return_value, "hash", phar_obj->archive->signature, phar_obj->archive->sig_len);
3111 		switch(phar_obj->archive->sig_flags) {
3112 			case PHAR_SIG_MD5:
3113 				add_assoc_stringl(return_value, "hash_type", "MD5", 3);
3114 				break;
3115 			case PHAR_SIG_SHA1:
3116 				add_assoc_stringl(return_value, "hash_type", "SHA-1", 5);
3117 				break;
3118 			case PHAR_SIG_SHA256:
3119 				add_assoc_stringl(return_value, "hash_type", "SHA-256", 7);
3120 				break;
3121 			case PHAR_SIG_SHA512:
3122 				add_assoc_stringl(return_value, "hash_type", "SHA-512", 7);
3123 				break;
3124 			case PHAR_SIG_OPENSSL:
3125 				add_assoc_stringl(return_value, "hash_type", "OpenSSL", 7);
3126 				break;
3127 			default:
3128 				unknown = strpprintf(0, "Unknown (%u)", phar_obj->archive->sig_flags);
3129 				add_assoc_str(return_value, "hash_type", unknown);
3130 				break;
3131 		}
3132 	} else {
3133 		RETURN_FALSE;
3134 	}
3135 }
3136 /* }}} */
3137 
3138 /* {{{ proto bool Phar::getModified()
3139  * Return whether phar was modified
3140  */
PHP_METHOD(Phar,getModified)3141 PHP_METHOD(Phar, getModified)
3142 {
3143 	PHAR_ARCHIVE_OBJECT();
3144 
3145 	if (zend_parse_parameters_none() == FAILURE) {
3146 		return;
3147 	}
3148 
3149 	RETURN_BOOL(phar_obj->archive->is_modified);
3150 }
3151 /* }}} */
3152 
phar_set_compression(zval * zv,void * argument)3153 static int phar_set_compression(zval *zv, void *argument) /* {{{ */
3154 {
3155 	phar_entry_info *entry = (phar_entry_info *)Z_PTR_P(zv);
3156 	uint32_t compress = *(uint32_t *)argument;
3157 
3158 	if (entry->is_deleted) {
3159 		return ZEND_HASH_APPLY_KEEP;
3160 	}
3161 
3162 	entry->old_flags = entry->flags;
3163 	entry->flags &= ~PHAR_ENT_COMPRESSION_MASK;
3164 	entry->flags |= compress;
3165 	entry->is_modified = 1;
3166 	return ZEND_HASH_APPLY_KEEP;
3167 }
3168 /* }}} */
3169 
phar_test_compression(zval * zv,void * argument)3170 static int phar_test_compression(zval *zv, void *argument) /* {{{ */
3171 {
3172 	phar_entry_info *entry = (phar_entry_info *)Z_PTR_P(zv);
3173 
3174 	if (entry->is_deleted) {
3175 		return ZEND_HASH_APPLY_KEEP;
3176 	}
3177 
3178 	if (!PHAR_G(has_bz2)) {
3179 		if (entry->flags & PHAR_ENT_COMPRESSED_BZ2) {
3180 			*(int *) argument = 0;
3181 		}
3182 	}
3183 
3184 	if (!PHAR_G(has_zlib)) {
3185 		if (entry->flags & PHAR_ENT_COMPRESSED_GZ) {
3186 			*(int *) argument = 0;
3187 		}
3188 	}
3189 
3190 	return ZEND_HASH_APPLY_KEEP;
3191 }
3192 /* }}} */
3193 
pharobj_set_compression(HashTable * manifest,uint32_t compress)3194 static void pharobj_set_compression(HashTable *manifest, uint32_t compress) /* {{{ */
3195 {
3196 	zend_hash_apply_with_argument(manifest, phar_set_compression, &compress);
3197 }
3198 /* }}} */
3199 
pharobj_cancompress(HashTable * manifest)3200 static int pharobj_cancompress(HashTable *manifest) /* {{{ */
3201 {
3202 	int test;
3203 
3204 	test = 1;
3205 	zend_hash_apply_with_argument(manifest, phar_test_compression, &test);
3206 	return test;
3207 }
3208 /* }}} */
3209 
3210 /* {{{ proto object Phar::compress(int method[, string extension])
3211  * Compress a .tar, or .phar.tar with whole-file compression
3212  * The parameter can be one of Phar::GZ or Phar::BZ2 to specify
3213  * the kind of compression desired
3214  */
PHP_METHOD(Phar,compress)3215 PHP_METHOD(Phar, compress)
3216 {
3217 	zend_long method;
3218 	char *ext = NULL;
3219 	size_t ext_len = 0;
3220 	uint32_t flags;
3221 	zend_object *ret;
3222 	PHAR_ARCHIVE_OBJECT();
3223 
3224 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|s", &method, &ext, &ext_len) == FAILURE) {
3225 		return;
3226 	}
3227 
3228 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3229 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3230 			"Cannot compress phar archive, phar is read-only");
3231 		return;
3232 	}
3233 
3234 	if (phar_obj->archive->is_zip) {
3235 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3236 			"Cannot compress zip-based archives with whole-archive compression");
3237 		return;
3238 	}
3239 
3240 	switch (method) {
3241 		case 0:
3242 			flags = PHAR_FILE_COMPRESSED_NONE;
3243 			break;
3244 		case PHAR_ENT_COMPRESSED_GZ:
3245 			if (!PHAR_G(has_zlib)) {
3246 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3247 					"Cannot compress entire archive with gzip, enable ext/zlib in php.ini");
3248 				return;
3249 			}
3250 			flags = PHAR_FILE_COMPRESSED_GZ;
3251 			break;
3252 
3253 		case PHAR_ENT_COMPRESSED_BZ2:
3254 			if (!PHAR_G(has_bz2)) {
3255 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3256 					"Cannot compress entire archive with bz2, enable ext/bz2 in php.ini");
3257 				return;
3258 			}
3259 			flags = PHAR_FILE_COMPRESSED_BZ2;
3260 			break;
3261 		default:
3262 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3263 				"Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2");
3264 			return;
3265 	}
3266 
3267 	if (phar_obj->archive->is_tar) {
3268 		ret = phar_convert_to_other(phar_obj->archive, PHAR_FORMAT_TAR, ext, flags);
3269 	} else {
3270 		ret = phar_convert_to_other(phar_obj->archive, PHAR_FORMAT_PHAR, ext, flags);
3271 	}
3272 
3273 	if (ret) {
3274 		ZVAL_OBJ(return_value, ret);
3275 	} else {
3276 		RETURN_NULL();
3277 	}
3278 }
3279 /* }}} */
3280 
3281 /* {{{ proto object Phar::decompress([string extension])
3282  * Decompress a .tar, or .phar.tar with whole-file compression
3283  */
PHP_METHOD(Phar,decompress)3284 PHP_METHOD(Phar, decompress)
3285 {
3286 	char *ext = NULL;
3287 	size_t ext_len = 0;
3288 	zend_object *ret;
3289 	PHAR_ARCHIVE_OBJECT();
3290 
3291 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s", &ext, &ext_len) == FAILURE) {
3292 		return;
3293 	}
3294 
3295 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3296 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3297 			"Cannot decompress phar archive, phar is read-only");
3298 		return;
3299 	}
3300 
3301 	if (phar_obj->archive->is_zip) {
3302 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3303 			"Cannot decompress zip-based archives with whole-archive compression");
3304 		return;
3305 	}
3306 
3307 	if (phar_obj->archive->is_tar) {
3308 		ret = phar_convert_to_other(phar_obj->archive, PHAR_FORMAT_TAR, ext, PHAR_FILE_COMPRESSED_NONE);
3309 	} else {
3310 		ret = phar_convert_to_other(phar_obj->archive, PHAR_FORMAT_PHAR, ext, PHAR_FILE_COMPRESSED_NONE);
3311 	}
3312 
3313 	if (ret) {
3314 		ZVAL_OBJ(return_value, ret);
3315 	} else {
3316 		RETURN_NULL();
3317 	}
3318 }
3319 /* }}} */
3320 
3321 /* {{{ proto object Phar::compressFiles(int method)
3322  * Compress all files within a phar or zip archive using the specified compression
3323  * The parameter can be one of Phar::GZ or Phar::BZ2 to specify
3324  * the kind of compression desired
3325  */
PHP_METHOD(Phar,compressFiles)3326 PHP_METHOD(Phar, compressFiles)
3327 {
3328 	char *error;
3329 	uint32_t flags;
3330 	zend_long method;
3331 	PHAR_ARCHIVE_OBJECT();
3332 
3333 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &method) == FAILURE) {
3334 		return;
3335 	}
3336 
3337 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3338 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3339 			"Phar is readonly, cannot change compression");
3340 		return;
3341 	}
3342 
3343 	switch (method) {
3344 		case PHAR_ENT_COMPRESSED_GZ:
3345 			if (!PHAR_G(has_zlib)) {
3346 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3347 					"Cannot compress files within archive with gzip, enable ext/zlib in php.ini");
3348 				return;
3349 			}
3350 			flags = PHAR_ENT_COMPRESSED_GZ;
3351 			break;
3352 
3353 		case PHAR_ENT_COMPRESSED_BZ2:
3354 			if (!PHAR_G(has_bz2)) {
3355 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3356 					"Cannot compress files within archive with bz2, enable ext/bz2 in php.ini");
3357 				return;
3358 			}
3359 			flags = PHAR_ENT_COMPRESSED_BZ2;
3360 			break;
3361 		default:
3362 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3363 				"Unknown compression specified, please pass one of Phar::GZ or Phar::BZ2");
3364 			return;
3365 	}
3366 
3367 	if (phar_obj->archive->is_tar) {
3368 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3369 			"Cannot compress with Gzip compression, tar archives cannot compress individual files, use compress() to compress the whole archive");
3370 		return;
3371 	}
3372 
3373 	if (!pharobj_cancompress(&phar_obj->archive->manifest)) {
3374 		if (flags == PHAR_FILE_COMPRESSED_GZ) {
3375 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3376 				"Cannot compress all files as Gzip, some are compressed as bzip2 and cannot be decompressed");
3377 		} else {
3378 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3379 				"Cannot compress all files as Bzip2, some are compressed as gzip and cannot be decompressed");
3380 		}
3381 		return;
3382 	}
3383 
3384 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
3385 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
3386 		return;
3387 	}
3388 	pharobj_set_compression(&phar_obj->archive->