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->manifest, flags);
3389 	phar_obj->archive->is_modified = 1;
3390 	phar_flush(phar_obj->archive, 0, 0, 0, &error);
3391 
3392 	if (error) {
3393 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "%s", error);
3394 		efree(error);
3395 	}
3396 }
3397 /* }}} */
3398 
3399 /* {{{ proto bool Phar::decompressFiles()
3400  * decompress every file
3401  */
PHP_METHOD(Phar,decompressFiles)3402 PHP_METHOD(Phar, decompressFiles)
3403 {
3404 	char *error;
3405 	PHAR_ARCHIVE_OBJECT();
3406 
3407 	if (zend_parse_parameters_none() == FAILURE) {
3408 		return;
3409 	}
3410 
3411 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3412 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3413 			"Phar is readonly, cannot change compression");
3414 		return;
3415 	}
3416 
3417 	if (!pharobj_cancompress(&phar_obj->archive->manifest)) {
3418 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
3419 			"Cannot decompress all files, some are compressed as bzip2 or gzip and cannot be decompressed");
3420 		return;
3421 	}
3422 
3423 	if (phar_obj->archive->is_tar) {
3424 		RETURN_TRUE;
3425 	} else {
3426 		if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
3427 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
3428 			return;
3429 		}
3430 		pharobj_set_compression(&phar_obj->archive->manifest, PHAR_ENT_COMPRESSED_NONE);
3431 	}
3432 
3433 	phar_obj->archive->is_modified = 1;
3434 	phar_flush(phar_obj->archive, 0, 0, 0, &error);
3435 
3436 	if (error) {
3437 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "%s", error);
3438 		efree(error);
3439 	}
3440 
3441 	RETURN_TRUE;
3442 }
3443 /* }}} */
3444 
3445 /* {{{ proto bool Phar::copy(string oldfile, string newfile)
3446  * copy a file internal to the phar archive to another new file within the phar
3447  */
PHP_METHOD(Phar,copy)3448 PHP_METHOD(Phar, copy)
3449 {
3450 	char *oldfile, *newfile, *error;
3451 	const char *pcr_error;
3452 	size_t oldfile_len, newfile_len;
3453 	phar_entry_info *oldentry, newentry = {0}, *temp;
3454 	size_t tmp_len = 0;
3455 
3456 	PHAR_ARCHIVE_OBJECT();
3457 
3458 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &oldfile, &oldfile_len, &newfile, &newfile_len) == FAILURE) {
3459 		return;
3460 	}
3461 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3462 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3463 			"Cannot copy \"%s\" to \"%s\", phar is read-only", oldfile, newfile);
3464 		RETURN_FALSE;
3465 	}
3466 
3467 	if (oldfile_len >= sizeof(".phar")-1 && !memcmp(oldfile, ".phar", sizeof(".phar")-1)) {
3468 		/* can't copy a meta file */
3469 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3470 			"file \"%s\" cannot be copied to file \"%s\", cannot copy Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname);
3471 		RETURN_FALSE;
3472 	}
3473 
3474 	if (newfile_len >= sizeof(".phar")-1 && !memcmp(newfile, ".phar", sizeof(".phar")-1)) {
3475 		/* can't copy a meta file */
3476 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3477 			"file \"%s\" cannot be copied to file \"%s\", cannot copy to Phar meta-file in %s", oldfile, newfile, phar_obj->archive->fname);
3478 		RETURN_FALSE;
3479 	}
3480 
3481 	if (!zend_hash_str_exists(&phar_obj->archive->manifest, oldfile, (uint32_t) oldfile_len) || NULL == (oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint32_t) oldfile_len)) || oldentry->is_deleted) {
3482 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3483 			"file \"%s\" cannot be copied to file \"%s\", file does not exist in %s", oldfile, newfile, phar_obj->archive->fname);
3484 		RETURN_FALSE;
3485 	}
3486 
3487 	if (zend_hash_str_exists(&phar_obj->archive->manifest, newfile, (uint32_t) newfile_len)) {
3488 		if (NULL != (temp = zend_hash_str_find_ptr(&phar_obj->archive->manifest, newfile, (uint32_t) newfile_len)) || !temp->is_deleted) {
3489 			zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3490 				"file \"%s\" cannot be copied to file \"%s\", file must not already exist in phar %s", oldfile, newfile, phar_obj->archive->fname);
3491 			RETURN_FALSE;
3492 		}
3493 	}
3494 
3495 	tmp_len = newfile_len;
3496 	if (phar_path_check(&newfile, &tmp_len, &pcr_error) > pcr_is_ok) {
3497 		zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
3498 				"file \"%s\" contains invalid characters %s, cannot be copied from \"%s\" in phar %s", newfile, pcr_error, oldfile, phar_obj->archive->fname);
3499 		RETURN_FALSE;
3500 	}
3501 	newfile_len = tmp_len;
3502 
3503 	if (phar_obj->archive->is_persistent) {
3504 		if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
3505 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
3506 			return;
3507 		}
3508 		/* re-populate with copied-on-write entry */
3509 		oldentry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, oldfile, (uint32_t) oldfile_len);
3510 	}
3511 
3512 	memcpy((void *) &newentry, oldentry, sizeof(phar_entry_info));
3513 
3514 	if (Z_TYPE(newentry.metadata) != IS_UNDEF) {
3515 		zval_copy_ctor(&newentry.metadata);
3516 		newentry.metadata_str.s = NULL;
3517 	}
3518 
3519 	newentry.filename = estrndup(newfile, newfile_len);
3520 	newentry.filename_len = newfile_len;
3521 	newentry.fp_refcount = 0;
3522 
3523 	if (oldentry->fp_type != PHAR_FP) {
3524 		if (FAILURE == phar_copy_entry_fp(oldentry, &newentry, &error)) {
3525 			efree(newentry.filename);
3526 			php_stream_close(newentry.fp);
3527 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3528 			efree(error);
3529 			return;
3530 		}
3531 	}
3532 
3533 	zend_hash_str_add_mem(&oldentry->phar->manifest, newfile, newfile_len, &newentry, sizeof(phar_entry_info));
3534 	phar_obj->archive->is_modified = 1;
3535 	phar_flush(phar_obj->archive, 0, 0, 0, &error);
3536 
3537 	if (error) {
3538 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3539 		efree(error);
3540 	}
3541 
3542 	RETURN_TRUE;
3543 }
3544 /* }}} */
3545 
3546 /* {{{ proto int Phar::offsetExists(string entry)
3547  * determines whether a file exists in the phar
3548  */
PHP_METHOD(Phar,offsetExists)3549 PHP_METHOD(Phar, offsetExists)
3550 {
3551 	char *fname;
3552 	size_t fname_len;
3553 	phar_entry_info *entry;
3554 
3555 	PHAR_ARCHIVE_OBJECT();
3556 
3557 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
3558 		return;
3559 	}
3560 
3561 	if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint32_t) fname_len)) {
3562 		if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint32_t) fname_len))) {
3563 			if (entry->is_deleted) {
3564 				/* entry is deleted, but has not been flushed to disk yet */
3565 				RETURN_FALSE;
3566 			}
3567 		}
3568 
3569 		if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
3570 			/* none of these are real files, so they don't exist */
3571 			RETURN_FALSE;
3572 		}
3573 		RETURN_TRUE;
3574 	} else {
3575 		if (zend_hash_str_exists(&phar_obj->archive->virtual_dirs, fname, (uint32_t) fname_len)) {
3576 			RETURN_TRUE;
3577 		}
3578 		RETURN_FALSE;
3579 	}
3580 }
3581 /* }}} */
3582 
3583 /* {{{ proto int Phar::offsetGet(string entry)
3584  * get a PharFileInfo object for a specific file
3585  */
PHP_METHOD(Phar,offsetGet)3586 PHP_METHOD(Phar, offsetGet)
3587 {
3588 	char *fname, *error;
3589 	size_t fname_len;
3590 	zval zfname;
3591 	phar_entry_info *entry;
3592 	zend_string *sfname;
3593 	PHAR_ARCHIVE_OBJECT();
3594 
3595 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
3596 		return;
3597 	}
3598 
3599 	/* security is 0 here so that we can get a better error message than "entry doesn't exist" */
3600 	if (!(entry = phar_get_entry_info_dir(phar_obj->archive, fname, fname_len, 1, &error, 0))) {
3601 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist%s%s", fname, error?", ":"", error?error:"");
3602 	} else {
3603 		if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
3604 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get stub \".phar/stub.php\" directly in phar \"%s\", use getStub", phar_obj->archive->fname);
3605 			return;
3606 		}
3607 
3608 		if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
3609 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get alias \".phar/alias.txt\" directly in phar \"%s\", use getAlias", phar_obj->archive->fname);
3610 			return;
3611 		}
3612 
3613 		if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
3614 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot directly get any files or directories in magic \".phar\" directory");
3615 			return;
3616 		}
3617 
3618 		if (entry->is_temp_dir) {
3619 			efree(entry->filename);
3620 			efree(entry);
3621 		}
3622 
3623 		sfname = strpprintf(0, "phar://%s/%s", phar_obj->archive->fname, fname);
3624 		ZVAL_NEW_STR(&zfname, sfname);
3625 		spl_instantiate_arg_ex1(phar_obj->spl.info_class, return_value, &zfname);
3626 		zval_ptr_dtor(&zfname);
3627 	}
3628 }
3629 /* }}} */
3630 
3631 /* {{{ add a file within the phar archive from a string or resource
3632  */
phar_add_file(phar_archive_data ** pphar,char * filename,size_t filename_len,char * cont_str,size_t cont_len,zval * zresource)3633 static void phar_add_file(phar_archive_data **pphar, char *filename, size_t filename_len, char *cont_str, size_t cont_len, zval *zresource)
3634 {
3635 	size_t start_pos=0;
3636 	char *error;
3637 	size_t contents_len;
3638 	phar_entry_data *data;
3639 	php_stream *contents_file = NULL;
3640 	php_stream_statbuf ssb;
3641 #ifdef PHP_WIN32
3642 	char *save_filename;
3643 	ALLOCA_FLAG(filename_use_heap)
3644 #endif
3645 
3646 	if (filename_len >= sizeof(".phar")-1) {
3647 		start_pos = '/' == filename[0]; /* account for any leading slash: multiple-leads handled elsewhere */
3648 		if (!memcmp(&filename[start_pos], ".phar", sizeof(".phar")-1) && (filename[start_pos+5] == '/' || filename[start_pos+5] == '\\' || filename[start_pos+5] == '\0')) {
3649 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot create any files in magic \".phar\" directory");
3650 			return;
3651 		}
3652 	}
3653 
3654 #ifdef PHP_WIN32
3655 	save_filename = filename;
3656 	if (memchr(filename, '\\', filename_len)) {
3657 		filename = do_alloca(filename_len + 1, filename_use_heap);
3658 		memcpy(filename, save_filename, filename_len);
3659 		filename[filename_len] = '\0';
3660 	}
3661 #endif
3662 
3663 	if (!(data = phar_get_or_create_entry_data((*pphar)->fname, (*pphar)->fname_len, filename, filename_len, "w+b", 0, &error, 1))) {
3664 		if (error) {
3665 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be created: %s", filename, error);
3666 			efree(error);
3667 		} else {
3668 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be created", filename);
3669 		}
3670 		goto finish;
3671 	} else {
3672 		if (error) {
3673 			efree(error);
3674 		}
3675 
3676 		if (!data->internal_file->is_dir) {
3677 			if (cont_str) {
3678 				contents_len = php_stream_write(data->fp, cont_str, cont_len);
3679 				if (contents_len != cont_len) {
3680 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s could not be written to", filename);
3681 					goto finish;
3682 				}
3683 			} else {
3684 				if (!(php_stream_from_zval_no_verify(contents_file, zresource))) {
3685 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s could not be written to", filename);
3686 					goto finish;
3687 				}
3688 				php_stream_copy_to_stream_ex(contents_file, data->fp, PHP_STREAM_COPY_ALL, &contents_len);
3689 			}
3690 			data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len;
3691 		}
3692 
3693 		if (contents_file != NULL && php_stream_stat(contents_file, &ssb) != -1) {
3694 			data->internal_file->flags = ssb.sb.st_mode & PHAR_ENT_PERM_MASK ;
3695 		} else {
3696 #ifndef _WIN32
3697 			mode_t mask;
3698 			mask = umask(0);
3699 			umask(mask);
3700 			data->internal_file->flags &= ~mask;
3701 #endif
3702 		}
3703 
3704 		/* check for copy-on-write */
3705 		if (pphar[0] != data->phar) {
3706 			*pphar = data->phar;
3707 		}
3708 		phar_entry_delref(data);
3709 		phar_flush(*pphar, 0, 0, 0, &error);
3710 
3711 		if (error) {
3712 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3713 			efree(error);
3714 		}
3715 	}
3716 
3717 finish: ;
3718 #ifdef PHP_WIN32
3719 	if (filename != save_filename) {
3720 		free_alloca(filename, filename_use_heap);
3721 		filename = save_filename;
3722 	}
3723 #endif
3724 }
3725 /* }}} */
3726 
3727 /* {{{ create a directory within the phar archive
3728  */
phar_mkdir(phar_archive_data ** pphar,char * dirname,size_t dirname_len)3729 static void phar_mkdir(phar_archive_data **pphar, char *dirname, size_t dirname_len)
3730 {
3731 	char *error;
3732 	phar_entry_data *data;
3733 
3734 	if (!(data = phar_get_or_create_entry_data((*pphar)->fname, (*pphar)->fname_len, dirname, dirname_len, "w+b", 2, &error, 1))) {
3735 		if (error) {
3736 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Directory %s does not exist and cannot be created: %s", dirname, error);
3737 			efree(error);
3738 		} else {
3739 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Directory %s does not exist and cannot be created", dirname);
3740 		}
3741 
3742 		return;
3743 	} else {
3744 		if (error) {
3745 			efree(error);
3746 		}
3747 
3748 		/* check for copy on write */
3749 		if (data->phar != *pphar) {
3750 			*pphar = data->phar;
3751 		}
3752 		phar_entry_delref(data);
3753 		phar_flush(*pphar, 0, 0, 0, &error);
3754 
3755 		if (error) {
3756 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3757 			efree(error);
3758 		}
3759 	}
3760 }
3761 /* }}} */
3762 
3763 /* {{{ proto int Phar::offsetSet(string entry, string value)
3764  * set the contents of an internal file to those of an external file
3765  */
PHP_METHOD(Phar,offsetSet)3766 PHP_METHOD(Phar, offsetSet)
3767 {
3768 	char *fname, *cont_str = NULL;
3769 	size_t fname_len, cont_len;
3770 	zval *zresource;
3771 	PHAR_ARCHIVE_OBJECT();
3772 
3773 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3774 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
3775 		return;
3776 	}
3777 
3778 	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "pr", &fname, &fname_len, &zresource) == FAILURE
3779 	&& zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) {
3780 		return;
3781 	}
3782 	if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
3783 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname);
3784 		return;
3785 	}
3786 
3787 	if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
3788 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname);
3789 		return;
3790 	}
3791 
3792 	if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
3793 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory");
3794 		return;
3795 	}
3796 
3797 	phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource);
3798 }
3799 /* }}} */
3800 
3801 /* {{{ proto int Phar::offsetUnset(string entry)
3802  * remove a file from a phar
3803  */
PHP_METHOD(Phar,offsetUnset)3804 PHP_METHOD(Phar, offsetUnset)
3805 {
3806 	char *fname, *error;
3807 	size_t fname_len;
3808 	phar_entry_info *entry;
3809 	PHAR_ARCHIVE_OBJECT();
3810 
3811 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
3812 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
3813 		return;
3814 	}
3815 
3816 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
3817 		return;
3818 	}
3819 
3820 	if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint32_t) fname_len)) {
3821 		if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint32_t) fname_len))) {
3822 			if (entry->is_deleted) {
3823 				/* entry is deleted, but has not been flushed to disk yet */
3824 				return;
3825 			}
3826 
3827 			if (phar_obj->archive->is_persistent) {
3828 				if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
3829 					zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
3830 					return;
3831 				}
3832 				/* re-populate entry after copy on write */
3833 				entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint32_t) fname_len);
3834 			}
3835 			entry->is_modified = 0;
3836 			entry->is_deleted = 1;
3837 			/* we need to "flush" the stream to save the newly deleted file on disk */
3838 			phar_flush(phar_obj->archive, 0, 0, 0, &error);
3839 
3840 			if (error) {
3841 				zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
3842 				efree(error);
3843 			}
3844 
3845 			RETURN_TRUE;
3846 		}
3847 	} else {
3848 		RETURN_FALSE;
3849 	}
3850 }
3851 /* }}} */
3852 
3853 /* {{{ proto string Phar::addEmptyDir(string dirname)
3854  * Adds an empty directory to the phar archive
3855  */
PHP_METHOD(Phar,addEmptyDir)3856 PHP_METHOD(Phar, addEmptyDir)
3857 {
3858 	char *dirname;
3859 	size_t dirname_len;
3860 
3861 	PHAR_ARCHIVE_OBJECT();
3862 
3863 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &dirname, &dirname_len) == FAILURE) {
3864 		return;
3865 	}
3866 
3867 	if (dirname_len >= sizeof(".phar")-1 && !memcmp(dirname, ".phar", sizeof(".phar")-1)) {
3868 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot create a directory in magic \".phar\" directory");
3869 		return;
3870 	}
3871 
3872 	phar_mkdir(&phar_obj->archive, dirname, dirname_len);
3873 }
3874 /* }}} */
3875 
3876 /* {{{ proto string Phar::addFile(string filename[, string localname])
3877  * Adds a file to the archive using the filename, or the second parameter as the name within the archive
3878  */
PHP_METHOD(Phar,addFile)3879 PHP_METHOD(Phar, addFile)
3880 {
3881 	char *fname, *localname = NULL;
3882 	size_t fname_len, localname_len = 0;
3883 	php_stream *resource;
3884 	zval zresource;
3885 
3886 	PHAR_ARCHIVE_OBJECT();
3887 
3888 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s", &fname, &fname_len, &localname, &localname_len) == FAILURE) {
3889 		return;
3890 	}
3891 
3892 	if (!strstr(fname, "://") && php_check_open_basedir(fname)) {
3893 		zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive, open_basedir restrictions prevent this", fname);
3894 		return;
3895 	}
3896 
3897 	if (!(resource = php_stream_open_wrapper(fname, "rb", 0, NULL))) {
3898 		zend_throw_exception_ex(spl_ce_RuntimeException, 0, "phar error: unable to open file \"%s\" to add to phar archive", fname);
3899 		return;
3900 	}
3901 
3902 	if (localname) {
3903 		fname = localname;
3904 		fname_len = localname_len;
3905 	}
3906 
3907 	php_stream_to_zval(resource, &zresource);
3908 	phar_add_file(&(phar_obj->archive), fname, fname_len, NULL, 0, &zresource);
3909 	zval_ptr_dtor(&zresource);
3910 }
3911 /* }}} */
3912 
3913 /* {{{ proto string Phar::addFromString(string localname, string contents)
3914  * Adds a file to the archive using its contents as a string
3915  */
PHP_METHOD(Phar,addFromString)3916 PHP_METHOD(Phar, addFromString)
3917 {
3918 	char *localname, *cont_str;
3919 	size_t localname_len, cont_len;
3920 
3921 	PHAR_ARCHIVE_OBJECT();
3922 
3923 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) {
3924 		return;
3925 	}
3926 
3927 	phar_add_file(&(phar_obj->archive), localname, localname_len, cont_str, cont_len, NULL);
3928 }
3929 /* }}} */
3930 
3931 /* {{{ proto string Phar::getStub()
3932  * Returns the stub at the head of a phar archive as a string.
3933  */
PHP_METHOD(Phar,getStub)3934 PHP_METHOD(Phar, getStub)
3935 {
3936 	size_t len;
3937 	zend_string *buf;
3938 	php_stream *fp;
3939 	php_stream_filter *filter = NULL;
3940 	phar_entry_info *stub;
3941 
3942 	PHAR_ARCHIVE_OBJECT();
3943 
3944 	if (zend_parse_parameters_none() == FAILURE) {
3945 		return;
3946 	}
3947 
3948 	if (phar_obj->archive->is_tar || phar_obj->archive->is_zip) {
3949 
3950 		if (NULL != (stub = zend_hash_str_find_ptr(&(phar_obj->archive->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1))) {
3951 			if (phar_obj->archive->fp && !phar_obj->archive->is_brandnew && !(stub->flags & PHAR_ENT_COMPRESSION_MASK)) {
3952 				fp = phar_obj->archive->fp;
3953 			} else {
3954 				if (!(fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", 0, NULL))) {
3955 					zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "phar error: unable to open phar \"%s\"", phar_obj->archive->fname);
3956 					return;
3957 				}
3958 				if (stub->flags & PHAR_ENT_COMPRESSION_MASK) {
3959 					char *filter_name;
3960 
3961 					if ((filter_name = phar_decompress_filter(stub, 0)) != NULL) {
3962 						filter = php_stream_filter_create(filter_name, NULL, php_stream_is_persistent(fp));
3963 					} else {
3964 						filter = NULL;
3965 					}
3966 					if (!filter) {
3967 						zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "phar error: unable to read stub of phar \"%s\" (cannot create %s filter)", phar_obj->archive->fname, phar_decompress_filter(stub, 1));
3968 						return;
3969 					}
3970 					php_stream_filter_append(&fp->readfilters, filter);
3971 				}
3972 			}
3973 
3974 			if (!fp)  {
3975 				zend_throw_exception_ex(spl_ce_RuntimeException, 0,
3976 					"Unable to read stub");
3977 				return;
3978 			}
3979 
3980 			php_stream_seek(fp, stub->offset_abs, SEEK_SET);
3981 			len = stub->uncompressed_filesize;
3982 			goto carry_on;
3983 		} else {
3984 			RETURN_EMPTY_STRING();
3985 		}
3986 	}
3987 	len = phar_obj->archive->halt_offset;
3988 
3989 	if (phar_obj->archive->fp && !phar_obj->archive->is_brandnew) {
3990 		fp = phar_obj->archive->fp;
3991 	} else {
3992 		fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", 0, NULL);
3993 	}
3994 
3995 	if (!fp)  {
3996 		zend_throw_exception_ex(spl_ce_RuntimeException, 0,
3997 			"Unable to read stub");
3998 		return;
3999 	}
4000 
4001 	php_stream_rewind(fp);
4002 carry_on:
4003 	buf = zend_string_alloc(len, 0);
4004 
4005 	if (len != php_stream_read(fp, ZSTR_VAL(buf), len)) {
4006 		if (fp != phar_obj->archive->fp) {
4007 			php_stream_close(fp);
4008 		}
4009 		zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4010 			"Unable to read stub");
4011 		zend_string_release_ex(buf, 0);
4012 		return;
4013 	}
4014 
4015 	if (filter) {
4016 		php_stream_filter_flush(filter, 1);
4017 		php_stream_filter_remove(filter, 1);
4018 	}
4019 
4020 	if (fp != phar_obj->archive->fp) {
4021 		php_stream_close(fp);
4022 	}
4023 
4024 	ZSTR_VAL(buf)[len] = '\0';
4025 	ZSTR_LEN(buf) = len;
4026 	RETVAL_STR(buf);
4027 }
4028 /* }}}*/
4029 
4030 /* {{{ proto int Phar::hasMetaData()
4031  * Returns TRUE if the phar has global metadata, FALSE otherwise.
4032  */
PHP_METHOD(Phar,hasMetadata)4033 PHP_METHOD(Phar, hasMetadata)
4034 {
4035 	PHAR_ARCHIVE_OBJECT();
4036 
4037 	RETURN_BOOL(Z_TYPE(phar_obj->archive->metadata) != IS_UNDEF);
4038 }
4039 /* }}} */
4040 
4041 /* {{{ proto int Phar::getMetaData()
4042  * Returns the global metadata of the phar
4043  */
PHP_METHOD(Phar,getMetadata)4044 PHP_METHOD(Phar, getMetadata)
4045 {
4046 	PHAR_ARCHIVE_OBJECT();
4047 
4048 	if (zend_parse_parameters_none() == FAILURE) {
4049 		return;
4050 	}
4051 
4052 	if (Z_TYPE(phar_obj->archive->metadata) != IS_UNDEF) {
4053 		if (phar_obj->archive->is_persistent) {
4054 			char *buf = estrndup((char *) Z_PTR(phar_obj->archive->metadata), phar_obj->archive->metadata_len);
4055 			/* assume success, we would have failed before */
4056 			phar_parse_metadata(&buf, return_value, phar_obj->archive->metadata_len);
4057 			efree(buf);
4058 		} else {
4059 			ZVAL_COPY(return_value, &phar_obj->archive->metadata);
4060 		}
4061 	}
4062 }
4063 /* }}} */
4064 
4065 /* {{{ proto int Phar::setMetaData(mixed $metadata)
4066  * Sets the global metadata of the phar
4067  */
PHP_METHOD(Phar,setMetadata)4068 PHP_METHOD(Phar, setMetadata)
4069 {
4070 	char *error;
4071 	zval *metadata;
4072 
4073 	PHAR_ARCHIVE_OBJECT();
4074 
4075 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
4076 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
4077 		return;
4078 	}
4079 
4080 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &metadata) == FAILURE) {
4081 		return;
4082 	}
4083 
4084 	if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
4085 		zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
4086 		return;
4087 	}
4088 	if (Z_TYPE(phar_obj->archive->metadata) != IS_UNDEF) {
4089 		zval_ptr_dtor(&phar_obj->archive->metadata);
4090 		ZVAL_UNDEF(&phar_obj->archive->metadata);
4091 	}
4092 
4093 	ZVAL_COPY(&phar_obj->archive->metadata, metadata);
4094 	phar_obj->archive->is_modified = 1;
4095 	phar_flush(phar_obj->archive, 0, 0, 0, &error);
4096 
4097 	if (error) {
4098 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
4099 		efree(error);
4100 	}
4101 }
4102 /* }}} */
4103 
4104 /* {{{ proto int Phar::delMetadata()
4105  * Deletes the global metadata of the phar
4106  */
PHP_METHOD(Phar,delMetadata)4107 PHP_METHOD(Phar, delMetadata)
4108 {
4109 	char *error;
4110 
4111 	PHAR_ARCHIVE_OBJECT();
4112 
4113 	if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
4114 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
4115 		return;
4116 	}
4117 
4118 	if (Z_TYPE(phar_obj->archive->metadata) != IS_UNDEF) {
4119 		zval_ptr_dtor(&phar_obj->archive->metadata);
4120 		ZVAL_UNDEF(&phar_obj->archive->metadata);
4121 		phar_obj->archive->is_modified = 1;
4122 		phar_flush(phar_obj->archive, 0, 0, 0, &error);
4123 
4124 		if (error) {
4125 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
4126 			efree(error);
4127 			RETURN_FALSE;
4128 		} else {
4129 			RETURN_TRUE;
4130 		}
4131 
4132 	} else {
4133 		RETURN_TRUE;
4134 	}
4135 }
4136 /* }}} */
4137 
phar_extract_file(zend_bool overwrite,phar_entry_info * entry,char * dest,size_t dest_len,char ** error)4138 static int phar_extract_file(zend_bool overwrite, phar_entry_info *entry, char *dest, size_t dest_len, char **error) /* {{{ */
4139 {
4140 	php_stream_statbuf ssb;
4141 	size_t len;
4142 	php_stream *fp;
4143 	char *fullpath;
4144 	const char *slash;
4145 	mode_t mode;
4146 	cwd_state new_state;
4147 	char *filename;
4148 	size_t filename_len;
4149 
4150 	if (entry->is_mounted) {
4151 		/* silently ignore mounted entries */
4152 		return SUCCESS;
4153 	}
4154 
4155 	if (entry->filename_len >= sizeof(".phar")-1 && !memcmp(entry->filename, ".phar", sizeof(".phar")-1)) {
4156 		return SUCCESS;
4157 	}
4158 	/* strip .. from path and restrict it to be under dest directory */
4159 	new_state.cwd = (char*)emalloc(2);
4160 	new_state.cwd[0] = DEFAULT_SLASH;
4161 	new_state.cwd[1] = '\0';
4162 	new_state.cwd_length = 1;
4163 	if (virtual_file_ex(&new_state, entry->filename, NULL, CWD_EXPAND) != 0 ||
4164 			new_state.cwd_length <= 1) {
4165 		if (EINVAL == errno && entry->filename_len > 50) {
4166 			char *tmp = estrndup(entry->filename, 50);
4167 			spprintf(error, 4096, "Cannot extract \"%s...\" to \"%s...\", extracted filename is too long for filesystem", tmp, dest);
4168 			efree(tmp);
4169 		} else {
4170 			spprintf(error, 4096, "Cannot extract \"%s\", internal error", entry->filename);
4171 		}
4172 		efree(new_state.cwd);
4173 		return FAILURE;
4174 	}
4175 	filename = new_state.cwd + 1;
4176 	filename_len = new_state.cwd_length - 1;
4177 #ifdef PHP_WIN32
4178 	/* unixify the path back, otherwise non zip formats might be broken */
4179 	{
4180 		size_t cnt = 0;
4181 
4182 		do {
4183 			if ('\\' == filename[cnt]) {
4184 				filename[cnt] = '/';
4185 			}
4186 		} while (cnt++ < filename_len);
4187 	}
4188 #endif
4189 
4190 	len = spprintf(&fullpath, 0, "%s/%s", dest, filename);
4191 
4192 	if (len >= MAXPATHLEN) {
4193 		char *tmp;
4194 		/* truncate for error message */
4195 		fullpath[50] = '\0';
4196 		if (entry->filename_len > 50) {
4197 			tmp = estrndup(entry->filename, 50);
4198 			spprintf(error, 4096, "Cannot extract \"%s...\" to \"%s...\", extracted filename is too long for filesystem", tmp, fullpath);
4199 			efree(tmp);
4200 		} else {
4201 			spprintf(error, 4096, "Cannot extract \"%s\" to \"%s...\", extracted filename is too long for filesystem", entry->filename, fullpath);
4202 		}
4203 		efree(fullpath);
4204 		efree(new_state.cwd);
4205 		return FAILURE;
4206 	}
4207 
4208 	if (!len) {
4209 		spprintf(error, 4096, "Cannot extract \"%s\", internal error", entry->filename);
4210 		efree(fullpath);
4211 		efree(new_state.cwd);
4212 		return FAILURE;
4213 	}
4214 
4215 	if (php_check_open_basedir(fullpath)) {
4216 		spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", openbasedir/safe mode restrictions in effect", entry->filename, fullpath);
4217 		efree(fullpath);
4218 		efree(new_state.cwd);
4219 		return FAILURE;
4220 	}
4221 
4222 	/* let see if the path already exists */
4223 	if (!overwrite && SUCCESS == php_stream_stat_path(fullpath, &ssb)) {
4224 		spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", path already exists", entry->filename, fullpath);
4225 		efree(fullpath);
4226 		efree(new_state.cwd);
4227 		return FAILURE;
4228 	}
4229 
4230 	/* perform dirname */
4231 	slash = zend_memrchr(filename, '/', filename_len);
4232 
4233 	if (slash) {
4234 		fullpath[dest_len + (slash - filename) + 1] = '\0';
4235 	} else {
4236 		fullpath[dest_len] = '\0';
4237 	}
4238 
4239 	if (FAILURE == php_stream_stat_path(fullpath, &ssb)) {
4240 		if (entry->is_dir) {
4241 			if (!php_stream_mkdir(fullpath, entry->flags & PHAR_ENT_PERM_MASK,  PHP_STREAM_MKDIR_RECURSIVE, NULL)) {
4242 				spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath);
4243 				efree(fullpath);
4244 				efree(new_state.cwd);
4245 				return FAILURE;
4246 			}
4247 		} else {
4248 			if (!php_stream_mkdir(fullpath, 0777,  PHP_STREAM_MKDIR_RECURSIVE, NULL)) {
4249 				spprintf(error, 4096, "Cannot extract \"%s\", could not create directory \"%s\"", entry->filename, fullpath);
4250 				efree(fullpath);
4251 				efree(new_state.cwd);
4252 				return FAILURE;
4253 			}
4254 		}
4255 	}
4256 
4257 	if (slash) {
4258 		fullpath[dest_len + (slash - filename) + 1] = '/';
4259 	} else {
4260 		fullpath[dest_len] = '/';
4261 	}
4262 
4263 	filename = NULL;
4264 	efree(new_state.cwd);
4265 	/* it is a standalone directory, job done */
4266 	if (entry->is_dir) {
4267 		efree(fullpath);
4268 		return SUCCESS;
4269 	}
4270 
4271 	fp = php_stream_open_wrapper(fullpath, "w+b", REPORT_ERRORS, NULL);
4272 
4273 	if (!fp) {
4274 		spprintf(error, 4096, "Cannot extract \"%s\", could not open for writing \"%s\"", entry->filename, fullpath);
4275 		efree(fullpath);
4276 		return FAILURE;
4277 	}
4278 
4279 	if ((phar_get_fp_type(entry) == PHAR_FP && (entry->flags & PHAR_ENT_COMPRESSION_MASK)) || !phar_get_efp(entry, 0)) {
4280 		if (FAILURE == phar_open_entry_fp(entry, error, 1)) {
4281 			if (error) {
4282 				spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer: %s", entry->filename, fullpath, *error);
4283 			} else {
4284 				spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to open internal file pointer", entry->filename, fullpath);
4285 			}
4286 			efree(fullpath);
4287 			php_stream_close(fp);
4288 			return FAILURE;
4289 		}
4290 	}
4291 
4292 	if (FAILURE == phar_seek_efp(entry, 0, SEEK_SET, 0, 0)) {
4293 		spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", unable to seek internal file pointer", entry->filename, fullpath);
4294 		efree(fullpath);
4295 		php_stream_close(fp);
4296 		return FAILURE;
4297 	}
4298 
4299 	if (SUCCESS != php_stream_copy_to_stream_ex(phar_get_efp(entry, 0), fp, entry->uncompressed_filesize, NULL)) {
4300 		spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", copying contents failed", entry->filename, fullpath);
4301 		efree(fullpath);
4302 		php_stream_close(fp);
4303 		return FAILURE;
4304 	}
4305 
4306 	php_stream_close(fp);
4307 	mode = (mode_t) entry->flags & PHAR_ENT_PERM_MASK;
4308 
4309 	if (FAILURE == VCWD_CHMOD(fullpath, mode)) {
4310 		spprintf(error, 4096, "Cannot extract \"%s\" to \"%s\", setting file permissions failed", entry->filename, fullpath);
4311 		efree(fullpath);
4312 		return FAILURE;
4313 	}
4314 
4315 	efree(fullpath);
4316 	return SUCCESS;
4317 }
4318 /* }}} */
4319 
extract_helper(phar_archive_data * archive,zend_string * search,char * pathto,size_t pathto_len,zend_bool overwrite,char ** error)4320 static int extract_helper(phar_archive_data *archive, zend_string *search, char *pathto, size_t pathto_len, zend_bool overwrite, char **error) { /* {{{ */
4321 	int extracted = 0;
4322 	phar_entry_info *entry;
4323 
4324 	if (!search) {
4325 		/* nothing to match -- extract all files */
4326 		ZEND_HASH_FOREACH_PTR(&archive->manifest, entry) {
4327 			if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, error)) return -1;
4328 			extracted++;
4329 		} ZEND_HASH_FOREACH_END();
4330 	} else if ('/' == ZSTR_VAL(search)[ZSTR_LEN(search) - 1]) {
4331 		/* ends in "/" -- extract all entries having that prefix */
4332 		ZEND_HASH_FOREACH_PTR(&archive->manifest, entry) {
4333 			if (0 != strncmp(ZSTR_VAL(search), entry->filename, ZSTR_LEN(search))) continue;
4334 			if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, error)) return -1;
4335 			extracted++;
4336 		} ZEND_HASH_FOREACH_END();
4337 	} else {
4338 		/* otherwise, looking for an exact match */
4339 		entry = zend_hash_find_ptr(&archive->manifest, search);
4340 		if (NULL == entry) return 0;
4341 		if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, error)) return -1;
4342 		return 1;
4343 	}
4344 
4345 	return extracted;
4346 }
4347 /* }}} */
4348 
4349 /* {{{ proto bool Phar::extractTo(string pathto[[, mixed files], bool overwrite])
4350  * Extract one or more file from a phar archive, optionally overwriting existing files
4351  */
PHP_METHOD(Phar,extractTo)4352 PHP_METHOD(Phar, extractTo)
4353 {
4354 	php_stream *fp;
4355 	php_stream_statbuf ssb;
4356 	char *pathto;
4357 	zend_string *filename;
4358 	size_t pathto_len;
4359 	int ret;
4360 	zval *zval_file;
4361 	zval *zval_files = NULL;
4362 	zend_bool overwrite = 0;
4363 	char *error = NULL;
4364 
4365 	PHAR_ARCHIVE_OBJECT();
4366 
4367 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|z!b", &pathto, &pathto_len, &zval_files, &overwrite) == FAILURE) {
4368 		return;
4369 	}
4370 
4371 	fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, NULL);
4372 
4373 	if (!fp) {
4374 		zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
4375 			"Invalid argument, %s cannot be found", phar_obj->archive->fname);
4376 		return;
4377 	}
4378 
4379 	php_stream_close(fp);
4380 
4381 	if (pathto_len < 1) {
4382 		zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
4383 			"Invalid argument, extraction path must be non-zero length");
4384 		return;
4385 	}
4386 
4387 	if (pathto_len >= MAXPATHLEN) {
4388 		char *tmp = estrndup(pathto, 50);
4389 		/* truncate for error message */
4390 		zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Cannot extract to \"%s...\", destination directory is too long for filesystem", tmp);
4391 		efree(tmp);
4392 		return;
4393 	}
4394 
4395 	if (php_stream_stat_path(pathto, &ssb) < 0) {
4396 		ret = php_stream_mkdir(pathto, 0777,  PHP_STREAM_MKDIR_RECURSIVE, NULL);
4397 		if (!ret) {
4398 			zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4399 				"Unable to create path \"%s\" for extraction", pathto);
4400 			return;
4401 		}
4402 	} else if (!(ssb.sb.st_mode & S_IFDIR)) {
4403 		zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4404 			"Unable to use path \"%s\" for extraction, it is a file, must be a directory", pathto);
4405 		return;
4406 	}
4407 
4408 	if (zval_files) {
4409 		switch (Z_TYPE_P(zval_files)) {
4410 			case IS_NULL:
4411 				filename = NULL;
4412 				break;
4413 			case IS_STRING:
4414 				filename = Z_STR_P(zval_files);
4415 				break;
4416 			case IS_ARRAY:
4417 				if (zend_hash_num_elements(Z_ARRVAL_P(zval_files)) == 0) {
4418 					RETURN_FALSE;
4419 				}
4420 
4421 				ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(zval_files), zval_file) {
4422 					ZVAL_DEREF(zval_file);
4423 					if (IS_STRING != Z_TYPE_P(zval_file)) {
4424 						zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
4425 							"Invalid argument, array of filenames to extract contains non-string value");
4426 						return;
4427 					}
4428 					switch (extract_helper(phar_obj->archive, Z_STR_P(zval_file), pathto, pathto_len, overwrite, &error)) {
4429 						case -1:
4430 							zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s",
4431 								phar_obj->archive->fname, error);
4432 							efree(error);
4433 							return;
4434 						case 0:
4435 							zend_throw_exception_ex(phar_ce_PharException, 0,
4436 								"Phar Error: attempted to extract non-existent file or directory \"%s\" from phar \"%s\"",
4437 								ZSTR_VAL(Z_STR_P(zval_file)), phar_obj->archive->fname);
4438 							return;
4439 					}
4440 				} ZEND_HASH_FOREACH_END();
4441 				RETURN_TRUE;
4442 			default:
4443 				zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
4444 					"Invalid argument, expected a filename (string) or array of filenames");
4445 				return;
4446 		}
4447 	} else {
4448 		filename = NULL;
4449 	}
4450 
4451 	ret = extract_helper(phar_obj->archive, filename, pathto, pathto_len, overwrite, &error);
4452 	if (-1 == ret) {
4453 		zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s",
4454 			phar_obj->archive->fname, error);
4455 		efree(error);
4456 	} else if (0 == ret && NULL != filename) {
4457 		zend_throw_exception_ex(phar_ce_PharException, 0,
4458 			"Phar Error: attempted to extract non-existent file or directory \"%s\" from phar \"%s\"",
4459 			ZSTR_VAL(filename), phar_obj->archive->fname);
4460 	} else {
4461 		RETURN_TRUE;
4462 	}
4463 }
4464 /* }}} */
4465 
4466 
4467 /* {{{ proto PharFileInfo::__construct(string entry)
4468  * Construct a Phar entry object
4469  */
PHP_METHOD(PharFileInfo,__construct)4470 PHP_METHOD(PharFileInfo, __construct)
4471 {
4472 	char *fname, *arch, *entry, *error;
4473 	size_t fname_len;
4474 	size_t arch_len, entry_len;
4475 	phar_entry_object *entry_obj;
4476 	phar_entry_info *entry_info;
4477 	phar_archive_data *phar_data;
4478 	zval *zobj = ZEND_THIS, arg1;
4479 
4480 	if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
4481 		return;
4482 	}
4483 
4484 	entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset);
4485 
4486 	if (entry_obj->entry) {
4487 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice");
4488 		return;
4489 	}
4490 
4491 	if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) {
4492 		zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4493 			"'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname);
4494 		return;
4495 	}
4496 
4497 	if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) {
4498 		efree(arch);
4499 		efree(entry);
4500 		if (error) {
4501 			zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4502 				"Cannot open phar file '%s': %s", fname, error);
4503 			efree(error);
4504 		} else {
4505 			zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4506 				"Cannot open phar file '%s'", fname);
4507 		}
4508 		return;
4509 	}
4510 
4511 	if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) {
4512 		zend_throw_exception_ex(spl_ce_RuntimeException, 0,
4513 			"Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : "");
4514 		efree(arch);
4515 		efree(entry);
4516 		return;
4517 	}
4518 
4519 	efree(arch);
4520 	efree(entry);
4521 
4522 	entry_obj->entry = entry_info;
4523 
4524 	ZVAL_STRINGL(&arg1, fname, fname_len);
4525 
4526 	zend_call_method_with_1_params(zobj, Z_OBJCE_P(zobj),
4527 		&spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1);
4528 
4529 	zval_ptr_dtor(&arg1);
4530 }
4531 /* }}} */
4532 
4533 #define PHAR_ENTRY_OBJECT() \
4534 	zval *zobj = ZEND_THIS; \
4535 	phar_entry_object *entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); \
4536 	if (!entry_obj->entry) { \
4537 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4538 			"Cannot call method on an uninitialized PharFileInfo object"); \
4539 		return; \
4540 	}
4541 
4542 /* {{{ proto PharFileInfo::__destruct()
4543  * clean up directory-based entry objects
4544  */
PHP_METHOD(PharFileInfo,__destruct)4545 PHP_METHOD(PharFileInfo, __destruct)
4546 {
4547 	zval *zobj = ZEND_THIS;
4548 	phar_entry_object *entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset);
4549 
4550 	if (entry_obj->entry && entry_obj->entry->is_temp_dir) {
4551 		if (entry_obj->entry->filename) {
4552 			efree(entry_obj->entry->filename);
4553 			entry_obj->entry->filename = NULL;
4554 		}
4555 
4556 		efree(entry_obj->entry);
4557 		entry_obj->entry = NULL;
4558 	}
4559 }
4560 /* }}} */
4561 
4562 /* {{{ proto int PharFileInfo::getCompressedSize()
4563  * Returns the compressed size
4564  */
PHP_METHOD(PharFileInfo,getCompressedSize)4565 PHP_METHOD(PharFileInfo, getCompressedSize)
4566 {
4567 	PHAR_ENTRY_OBJECT();
4568 
4569 	if (zend_parse_parameters_none() == FAILURE) {
4570 		return;
4571 	}
4572 
4573 	RETURN_LONG(entry_obj->entry->compressed_filesize);
4574 }
4575 /* }}} */
4576 
4577 /* {{{ proto bool PharFileInfo::isCompressed([int compression_type])
4578  * Returns whether the entry is compressed, and whether it is compressed with Phar::GZ or Phar::BZ2 if specified
4579  */
PHP_METHOD(PharFileInfo,isCompressed)4580 PHP_METHOD(PharFileInfo, isCompressed)
4581 {
4582 	/* a number that is not Phar::GZ or Phar::BZ2 */
4583 	zend_long method = 9021976;
4584 	PHAR_ENTRY_OBJECT();
4585 
4586 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &method) == FAILURE) {
4587 		return;
4588 	}
4589 
4590 	switch (method) {
4591 		case 9021976:
4592 			RETURN_BOOL(entry_obj->entry->flags & PHAR_ENT_COMPRESSION_MASK);
4593 		case PHAR_ENT_COMPRESSED_GZ:
4594 			RETURN_BOOL(entry_obj->entry->flags & PHAR_ENT_COMPRESSED_GZ);
4595 		case PHAR_ENT_COMPRESSED_BZ2:
4596 			RETURN_BOOL(entry_obj->entry->flags & PHAR_ENT_COMPRESSED_BZ2);
4597 		default:
4598 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4599 				"Unknown compression type specified"); \
4600 	}
4601 }
4602 /* }}} */
4603 
4604 /* {{{ proto int PharFileInfo::getCRC32()
4605  * Returns CRC32 code or throws an exception if not CRC checked
4606  */
PHP_METHOD(PharFileInfo,getCRC32)4607 PHP_METHOD(PharFileInfo, getCRC32)
4608 {
4609 	PHAR_ENTRY_OBJECT();
4610 
4611 	if (zend_parse_parameters_none() == FAILURE) {
4612 		return;
4613 	}
4614 
4615 	if (entry_obj->entry->is_dir) {
4616 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4617 			"Phar entry is a directory, does not have a CRC"); \
4618 		return;
4619 	}
4620 
4621 	if (entry_obj->entry->is_crc_checked) {
4622 		RETURN_LONG(entry_obj->entry->crc32);
4623 	} else {
4624 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4625 			"Phar entry was not CRC checked"); \
4626 	}
4627 }
4628 /* }}} */
4629 
4630 /* {{{ proto int PharFileInfo::isCRCChecked()
4631  * Returns whether file entry is CRC checked
4632  */
PHP_METHOD(PharFileInfo,isCRCChecked)4633 PHP_METHOD(PharFileInfo, isCRCChecked)
4634 {
4635 	PHAR_ENTRY_OBJECT();
4636 
4637 	if (zend_parse_parameters_none() == FAILURE) {
4638 		return;
4639 	}
4640 
4641 	RETURN_BOOL(entry_obj->entry->is_crc_checked);
4642 }
4643 /* }}} */
4644 
4645 /* {{{ proto int PharFileInfo::getPharFlags()
4646  * Returns the Phar file entry flags
4647  */
PHP_METHOD(PharFileInfo,getPharFlags)4648 PHP_METHOD(PharFileInfo, getPharFlags)
4649 {
4650 	PHAR_ENTRY_OBJECT();
4651 
4652 	if (zend_parse_parameters_none() == FAILURE) {
4653 		return;
4654 	}
4655 
4656 	RETURN_LONG(entry_obj->entry->flags & ~(PHAR_ENT_PERM_MASK|PHAR_ENT_COMPRESSION_MASK));
4657 }
4658 /* }}} */
4659 
4660 /* {{{ proto int PharFileInfo::chmod()
4661  * set the file permissions for the Phar.  This only allows setting execution bit, read/write
4662  */
PHP_METHOD(PharFileInfo,chmod)4663 PHP_METHOD(PharFileInfo, chmod)
4664 {
4665 	char *error;
4666 	zend_long perms;
4667 	PHAR_ENTRY_OBJECT();
4668 
4669 	if (entry_obj->entry->is_temp_dir) {
4670 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4671 			"Phar entry \"%s\" is a temporary directory (not an actual entry in the archive), cannot chmod", entry_obj->entry->filename); \
4672 		return;
4673 	}
4674 
4675 	if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) {
4676 		zend_throw_exception_ex(phar_ce_PharException, 0, "Cannot modify permissions for file \"%s\" in phar \"%s\", write operations are prohibited", entry_obj->entry->filename, entry_obj->entry->phar->fname);
4677 		return;
4678 	}
4679 
4680 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &perms) == FAILURE) {
4681 		return;
4682 	}
4683 
4684 	if (entry_obj->entry->is_persistent) {
4685 		phar_archive_data *phar = entry_obj->entry->phar;
4686 
4687 		if (FAILURE == phar_copy_on_write(&phar)) {
4688 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
4689 			return;
4690 		}
4691 		/* re-populate after copy-on-write */
4692 		entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len);
4693 	}
4694 	/* clear permissions */
4695 	entry_obj->entry->flags &= ~PHAR_ENT_PERM_MASK;
4696 	perms &= 0777;
4697 	entry_obj->entry->flags |= perms;
4698 	entry_obj->entry->old_flags = entry_obj->entry->flags;
4699 	entry_obj->entry->phar->is_modified = 1;
4700 	entry_obj->entry->is_modified = 1;
4701 
4702 	/* hackish cache in php_stat needs to be cleared */
4703 	/* if this code fails to work, check main/streams/streams.c, _php_stream_stat_path */
4704 	if (BG(CurrentLStatFile)) {
4705 		efree(BG(CurrentLStatFile));
4706 	}
4707 
4708 	if (BG(CurrentStatFile)) {
4709 		efree(BG(CurrentStatFile));
4710 	}
4711 
4712 	BG(CurrentLStatFile) = NULL;
4713 	BG(CurrentStatFile) = NULL;
4714 	phar_flush(entry_obj->entry->phar, 0, 0, 0, &error);
4715 
4716 	if (error) {
4717 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
4718 		efree(error);
4719 	}
4720 }
4721 /* }}} */
4722 
4723 /* {{{ proto int PharFileInfo::hasMetaData()
4724  * Returns the metadata of the entry
4725  */
PHP_METHOD(PharFileInfo,hasMetadata)4726 PHP_METHOD(PharFileInfo, hasMetadata)
4727 {
4728 	PHAR_ENTRY_OBJECT();
4729 
4730 	if (zend_parse_parameters_none() == FAILURE) {
4731 		return;
4732 	}
4733 
4734 	RETURN_BOOL(Z_TYPE(entry_obj->entry->metadata) != IS_UNDEF);
4735 }
4736 /* }}} */
4737 
4738 /* {{{ proto int PharFileInfo::getMetaData()
4739  * Returns the metadata of the entry
4740  */
PHP_METHOD(PharFileInfo,getMetadata)4741 PHP_METHOD(PharFileInfo, getMetadata)
4742 {
4743 	PHAR_ENTRY_OBJECT();
4744 
4745 	if (zend_parse_parameters_none() == FAILURE) {
4746 		return;
4747 	}
4748 
4749 	if (Z_TYPE(entry_obj->entry->metadata) != IS_UNDEF) {
4750 		if (entry_obj->entry->is_persistent) {
4751 			char *buf = estrndup((char *) Z_PTR(entry_obj->entry->metadata), entry_obj->entry->metadata_len);
4752 			/* assume success, we would have failed before */
4753 			phar_parse_metadata(&buf, return_value, entry_obj->entry->metadata_len);
4754 			efree(buf);
4755 		} else {
4756 			ZVAL_COPY(return_value, &entry_obj->entry->metadata);
4757 		}
4758 	}
4759 }
4760 /* }}} */
4761 
4762 /* {{{ proto int PharFileInfo::setMetaData(mixed $metadata)
4763  * Sets the metadata of the entry
4764  */
PHP_METHOD(PharFileInfo,setMetadata)4765 PHP_METHOD(PharFileInfo, setMetadata)
4766 {
4767 	char *error;
4768 	zval *metadata;
4769 
4770 	PHAR_ENTRY_OBJECT();
4771 
4772 	if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) {
4773 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
4774 		return;
4775 	}
4776 
4777 	if (entry_obj->entry->is_temp_dir) {
4778 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4779 			"Phar entry is a temporary directory (not an actual entry in the archive), cannot set metadata"); \
4780 		return;
4781 	}
4782 
4783 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &metadata) == FAILURE) {
4784 		return;
4785 	}
4786 
4787 	if (entry_obj->entry->is_persistent) {
4788 		phar_archive_data *phar = entry_obj->entry->phar;
4789 
4790 		if (FAILURE == phar_copy_on_write(&phar)) {
4791 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
4792 			return;
4793 		}
4794 		/* re-populate after copy-on-write */
4795 		entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len);
4796 	}
4797 	if (Z_TYPE(entry_obj->entry->metadata) != IS_UNDEF) {
4798 		zval_ptr_dtor(&entry_obj->entry->metadata);
4799 		ZVAL_UNDEF(&entry_obj->entry->metadata);
4800 	}
4801 
4802 	ZVAL_COPY(&entry_obj->entry->metadata, metadata);
4803 
4804 	entry_obj->entry->is_modified = 1;
4805 	entry_obj->entry->phar->is_modified = 1;
4806 	phar_flush(entry_obj->entry->phar, 0, 0, 0, &error);
4807 
4808 	if (error) {
4809 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
4810 		efree(error);
4811 	}
4812 }
4813 /* }}} */
4814 
4815 /* {{{ proto bool PharFileInfo::delMetaData()
4816  * Deletes the metadata of the entry
4817  */
PHP_METHOD(PharFileInfo,delMetadata)4818 PHP_METHOD(PharFileInfo, delMetadata)
4819 {
4820 	char *error;
4821 
4822 	PHAR_ENTRY_OBJECT();
4823 
4824 	if (zend_parse_parameters_none() == FAILURE) {
4825 		return;
4826 	}
4827 
4828 	if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) {
4829 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
4830 		return;
4831 	}
4832 
4833 	if (entry_obj->entry->is_temp_dir) {
4834 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4835 			"Phar entry is a temporary directory (not an actual entry in the archive), cannot delete metadata"); \
4836 		return;
4837 	}
4838 
4839 	if (Z_TYPE(entry_obj->entry->metadata) != IS_UNDEF) {
4840 		if (entry_obj->entry->is_persistent) {
4841 			phar_archive_data *phar = entry_obj->entry->phar;
4842 
4843 			if (FAILURE == phar_copy_on_write(&phar)) {
4844 				zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
4845 				return;
4846 			}
4847 			/* re-populate after copy-on-write */
4848 			entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len);
4849 		}
4850 		zval_ptr_dtor(&entry_obj->entry->metadata);
4851 		ZVAL_UNDEF(&entry_obj->entry->metadata);
4852 		entry_obj->entry->is_modified = 1;
4853 		entry_obj->entry->phar->is_modified = 1;
4854 
4855 		phar_flush(entry_obj->entry->phar, 0, 0, 0, &error);
4856 
4857 		if (error) {
4858 			zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
4859 			efree(error);
4860 			RETURN_FALSE;
4861 		} else {
4862 			RETURN_TRUE;
4863 		}
4864 
4865 	} else {
4866 		RETURN_TRUE;
4867 	}
4868 }
4869 /* }}} */
4870 
4871 /* {{{ proto string PharFileInfo::getContent()
4872  * return the complete file contents of the entry (like file_get_contents)
4873  */
PHP_METHOD(PharFileInfo,getContent)4874 PHP_METHOD(PharFileInfo, getContent)
4875 {
4876 	char *error;
4877 	php_stream *fp;
4878 	phar_entry_info *link;
4879 	zend_string *str;
4880 
4881 	PHAR_ENTRY_OBJECT();
4882 
4883 	if (zend_parse_parameters_none() == FAILURE) {
4884 		return;
4885 	}
4886 
4887 	if (entry_obj->entry->is_dir) {
4888 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4889 			"Phar error: Cannot retrieve contents, \"%s\" in phar \"%s\" is a directory", entry_obj->entry->filename, entry_obj->entry->phar->fname);
4890 		return;
4891 	}
4892 
4893 	link = phar_get_link_source(entry_obj->entry);
4894 
4895 	if (!link) {
4896 		link = entry_obj->entry;
4897 	}
4898 
4899 	if (SUCCESS != phar_open_entry_fp(link, &error, 0)) {
4900 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4901 			"Phar error: Cannot retrieve contents, \"%s\" in phar \"%s\": %s", entry_obj->entry->filename, entry_obj->entry->phar->fname, error);
4902 		efree(error);
4903 		return;
4904 	}
4905 
4906 	if (!(fp = phar_get_efp(link, 0))) {
4907 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4908 			"Phar error: Cannot retrieve contents of \"%s\" in phar \"%s\"", entry_obj->entry->filename, entry_obj->entry->phar->fname);
4909 		return;
4910 	}
4911 
4912 	phar_seek_efp(link, 0, SEEK_SET, 0, 0);
4913 	str = php_stream_copy_to_mem(fp, link->uncompressed_filesize, 0);
4914 	if (str) {
4915 		RETURN_STR(str);
4916 	} else {
4917 		RETURN_EMPTY_STRING();
4918 	}
4919 }
4920 /* }}} */
4921 
4922 /* {{{ proto int PharFileInfo::compress(int compression_type)
4923  * Instructs the Phar class to compress the current file using zlib or bzip2 compression
4924  */
PHP_METHOD(PharFileInfo,compress)4925 PHP_METHOD(PharFileInfo, compress)
4926 {
4927 	zend_long method;
4928 	char *error;
4929 	PHAR_ENTRY_OBJECT();
4930 
4931 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &method) == FAILURE) {
4932 		return;
4933 	}
4934 
4935 	if (entry_obj->entry->is_tar) {
4936 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4937 			"Cannot compress with Gzip compression, not possible with tar-based phar archives");
4938 		return;
4939 	}
4940 
4941 	if (entry_obj->entry->is_dir) {
4942 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
4943 			"Phar entry is a directory, cannot set compression"); \
4944 		return;
4945 	}
4946 
4947 	if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) {
4948 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4949 			"Phar is readonly, cannot change compression");
4950 		return;
4951 	}
4952 
4953 	if (entry_obj->entry->is_deleted) {
4954 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4955 			"Cannot compress deleted file");
4956 		return;
4957 	}
4958 
4959 	if (entry_obj->entry->is_persistent) {
4960 		phar_archive_data *phar = entry_obj->entry->phar;
4961 
4962 		if (FAILURE == phar_copy_on_write(&phar)) {
4963 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
4964 			return;
4965 		}
4966 		/* re-populate after copy-on-write */
4967 		entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len);
4968 	}
4969 	switch (method) {
4970 		case PHAR_ENT_COMPRESSED_GZ:
4971 			if (entry_obj->entry->flags & PHAR_ENT_COMPRESSED_GZ) {
4972 				RETURN_TRUE;
4973 			}
4974 
4975 			if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSED_BZ2) != 0) {
4976 				if (!PHAR_G(has_bz2)) {
4977 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4978 						"Cannot compress with gzip compression, file is already compressed with bzip2 compression and bz2 extension is not enabled, cannot decompress");
4979 					return;
4980 				}
4981 
4982 				/* decompress this file indirectly */
4983 				if (SUCCESS != phar_open_entry_fp(entry_obj->entry, &error, 1)) {
4984 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4985 						"Phar error: Cannot decompress bzip2-compressed file \"%s\" in phar \"%s\" in order to compress with gzip: %s", entry_obj->entry->filename, entry_obj->entry->phar->fname, error);
4986 					efree(error);
4987 					return;
4988 				}
4989 			}
4990 
4991 			if (!PHAR_G(has_zlib)) {
4992 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
4993 					"Cannot compress with gzip compression, zlib extension is not enabled");
4994 				return;
4995 			}
4996 
4997 			entry_obj->entry->old_flags = entry_obj->entry->flags;
4998 			entry_obj->entry->flags &= ~PHAR_ENT_COMPRESSION_MASK;
4999 			entry_obj->entry->flags |= PHAR_ENT_COMPRESSED_GZ;
5000 			break;
5001 		case PHAR_ENT_COMPRESSED_BZ2:
5002 			if (entry_obj->entry->flags & PHAR_ENT_COMPRESSED_BZ2) {
5003 				RETURN_TRUE;
5004 			}
5005 
5006 			if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSED_GZ) != 0) {
5007 				if (!PHAR_G(has_zlib)) {
5008 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5009 						"Cannot compress with bzip2 compression, file is already compressed with gzip compression and zlib extension is not enabled, cannot decompress");
5010 					return;
5011 				}
5012 
5013 				/* decompress this file indirectly */
5014 				if (SUCCESS != phar_open_entry_fp(entry_obj->entry, &error, 1)) {
5015 					zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5016 						"Phar error: Cannot decompress gzip-compressed file \"%s\" in phar \"%s\" in order to compress with bzip2: %s", entry_obj->entry->filename, entry_obj->entry->phar->fname, error);
5017 					efree(error);
5018 					return;
5019 				}
5020 			}
5021 
5022 			if (!PHAR_G(has_bz2)) {
5023 				zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5024 					"Cannot compress with bzip2 compression, bz2 extension is not enabled");
5025 				return;
5026 			}
5027 			entry_obj->entry->old_flags = entry_obj->entry->flags;
5028 			entry_obj->entry->flags &= ~PHAR_ENT_COMPRESSION_MASK;
5029 			entry_obj->entry->flags |= PHAR_ENT_COMPRESSED_BZ2;
5030 			break;
5031 		default:
5032 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
5033 				"Unknown compression type specified"); \
5034 	}
5035 
5036 	entry_obj->entry->phar->is_modified = 1;
5037 	entry_obj->entry->is_modified = 1;
5038 	phar_flush(entry_obj->entry->phar, 0, 0, 0, &error);
5039 
5040 	if (error) {
5041 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
5042 		efree(error);
5043 	}
5044 
5045 	RETURN_TRUE;
5046 }
5047 /* }}} */
5048 
5049 /* {{{ proto int PharFileInfo::decompress()
5050  * Instructs the Phar class to decompress the current file
5051  */
PHP_METHOD(PharFileInfo,decompress)5052 PHP_METHOD(PharFileInfo, decompress)
5053 {
5054 	char *error;
5055 	char *compression_type;
5056 	PHAR_ENTRY_OBJECT();
5057 
5058 	if (zend_parse_parameters_none() == FAILURE) {
5059 		return;
5060 	}
5061 
5062 	if (entry_obj->entry->is_dir) {
5063 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \
5064 			"Phar entry is a directory, cannot set compression"); \
5065 		return;
5066 	}
5067 
5068 	if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSION_MASK) == 0) {
5069 		RETURN_TRUE;
5070 	}
5071 
5072 	if (PHAR_G(readonly) && !entry_obj->entry->phar->is_data) {
5073 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5074 			"Phar is readonly, cannot decompress");
5075 		return;
5076 	}
5077 
5078 	if (entry_obj->entry->is_deleted) {
5079 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5080 			"Cannot compress deleted file");
5081 		return;
5082 	}
5083 
5084 	if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSED_GZ) != 0 && !PHAR_G(has_zlib)) {
5085 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5086 			"Cannot decompress Gzip-compressed file, zlib extension is not enabled");
5087 		return;
5088 	}
5089 
5090 	if ((entry_obj->entry->flags & PHAR_ENT_COMPRESSED_BZ2) != 0 && !PHAR_G(has_bz2)) {
5091 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5092 			"Cannot decompress Bzip2-compressed file, bz2 extension is not enabled");
5093 		return;
5094 	}
5095 
5096 	if (entry_obj->entry->is_persistent) {
5097 		phar_archive_data *phar = entry_obj->entry->phar;
5098 
5099 		if (FAILURE == phar_copy_on_write(&phar)) {
5100 			zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar->fname);
5101 			return;
5102 		}
5103 		/* re-populate after copy-on-write */
5104 		entry_obj->entry = zend_hash_str_find_ptr(&phar->manifest, entry_obj->entry->filename, entry_obj->entry->filename_len);
5105 	}
5106 	switch (entry_obj->entry->flags & PHAR_ENT_COMPRESSION_MASK) {
5107 		case PHAR_ENT_COMPRESSED_GZ:
5108 			compression_type = "gzip";
5109 			break;
5110 		case PHAR_ENT_COMPRESSED_BZ2:
5111 			compression_type = "bz2";
5112 			break;
5113 		default:
5114 			zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5115 				"Cannot decompress file compressed with unknown compression type");
5116 			return;
5117 	}
5118 	/* decompress this file indirectly */
5119 	if (SUCCESS != phar_open_entry_fp(entry_obj->entry, &error, 1)) {
5120 		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0,
5121 			"Phar error: Cannot decompress %s-compressed file \"%s\" in phar \"%s\": %s", compression_type, entry_obj->entry->filename, entry_obj->entry->phar->fname, error);
5122 		efree(error);
5123 		return;
5124 	}
5125 
5126 	entry_obj->entry->old_flags = entry_obj->entry->flags;
5127 	entry_obj->entry->flags &= ~PHAR_ENT_COMPRESSION_MASK;
5128 	entry_obj->entry->phar->is_modified = 1;
5129 	entry_obj->entry->is_modified = 1;
5130 	phar_flush(entry_obj->entry->phar, 0, 0, 0, &error);
5131 
5132 	if (error) {
5133 		zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
5134 		efree(error);
5135 	}
5136 	RETURN_TRUE;
5137 }
5138 /* }}} */
5139 
5140 /* {{{ phar methods */
5141 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar___construct, 0, 0, 1)
5142 	ZEND_ARG_INFO(0, filename)
5143 	ZEND_ARG_INFO(0, flags)
5144 	ZEND_ARG_INFO(0, alias)
5145 ZEND_END_ARG_INFO()
5146 
5147 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_createDS, 0, 0, 0)
5148 	ZEND_ARG_INFO(0, index)
5149 	ZEND_ARG_INFO(0, webindex)
5150 ZEND_END_ARG_INFO()
5151 
5152 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_cancompress, 0, 0, 0)
5153 	ZEND_ARG_INFO(0, method)
5154 ZEND_END_ARG_INFO()
5155 
5156 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_isvalidpharfilename, 0, 0, 1)
5157 	ZEND_ARG_INFO(0, filename)
5158 	ZEND_ARG_INFO(0, executable)
5159 ZEND_END_ARG_INFO()
5160 
5161 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_loadPhar, 0, 0, 1)
5162 	ZEND_ARG_INFO(0, filename)
5163 	ZEND_ARG_INFO(0, alias)
5164 ZEND_END_ARG_INFO()
5165 
5166 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_mapPhar, 0, 0, 0)
5167 	ZEND_ARG_INFO(0, alias)
5168 	ZEND_ARG_INFO(0, offset)
5169 ZEND_END_ARG_INFO()
5170 
5171 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_mount, 0, 0, 2)
5172 	ZEND_ARG_INFO(0, inphar)
5173 	ZEND_ARG_INFO(0, externalfile)
5174 ZEND_END_ARG_INFO()
5175 
5176 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_mungServer, 0, 0, 1)
5177 	ZEND_ARG_INFO(0, munglist)
5178 ZEND_END_ARG_INFO()
5179 
5180 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_webPhar, 0, 0, 0)
5181 	ZEND_ARG_INFO(0, alias)
5182 	ZEND_ARG_INFO(0, index)
5183 	ZEND_ARG_INFO(0, f404)
5184 	ZEND_ARG_INFO(0, mimetypes)
5185 	ZEND_ARG_INFO(0, rewrites)
5186 ZEND_END_ARG_INFO()
5187 
5188 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_running, 0, 0, 0)
5189 	ZEND_ARG_INFO(0, retphar)
5190 ZEND_END_ARG_INFO()
5191 
5192 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_ua, 0, 0, 1)
5193 	ZEND_ARG_INFO(0, archive)
5194 ZEND_END_ARG_INFO()
5195 
5196 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_build, 0, 0, 1)
5197 	ZEND_ARG_INFO(0, iterator)
5198 	ZEND_ARG_INFO(0, base_directory)
5199 ZEND_END_ARG_INFO()
5200 
5201 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_conv, 0, 0, 0)
5202 	ZEND_ARG_INFO(0, format)
5203 	ZEND_ARG_INFO(0, compression_type)
5204 	ZEND_ARG_INFO(0, file_ext)
5205 ZEND_END_ARG_INFO()
5206 
5207 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_comps, 0, 0, 1)
5208 	ZEND_ARG_INFO(0, compression_type)
5209 	ZEND_ARG_INFO(0, file_ext)
5210 ZEND_END_ARG_INFO()
5211 
5212 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_decomp, 0, 0, 0)
5213 	ZEND_ARG_INFO(0, file_ext)
5214 ZEND_END_ARG_INFO()
5215 
5216 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_comp, 0, 0, 1)
5217 	ZEND_ARG_INFO(0, compression_type)
5218 ZEND_END_ARG_INFO()
5219 
5220 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_compo, 0, 0, 0)
5221 	ZEND_ARG_INFO(0, compression_type)
5222 ZEND_END_ARG_INFO()
5223 
5224 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_copy, 0, 0, 2)
5225 	ZEND_ARG_INFO(0, newfile)
5226 	ZEND_ARG_INFO(0, oldfile)
5227 ZEND_END_ARG_INFO()
5228 
5229 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_delete, 0, 0, 1)
5230 	ZEND_ARG_INFO(0, entry)
5231 ZEND_END_ARG_INFO()
5232 
5233 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_fromdir, 0, 0, 1)
5234 	ZEND_ARG_INFO(0, base_dir)
5235 	ZEND_ARG_INFO(0, regex)
5236 ZEND_END_ARG_INFO()
5237 
5238 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_offsetExists, 0, 0, 1)
5239 	ZEND_ARG_INFO(0, entry)
5240 ZEND_END_ARG_INFO()
5241 
5242 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_offsetSet, 0, 0, 2)
5243 	ZEND_ARG_INFO(0, entry)
5244 	ZEND_ARG_INFO(0, value)
5245 ZEND_END_ARG_INFO()
5246 
5247 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setAlias, 0, 0, 1)
5248 	ZEND_ARG_INFO(0, alias)
5249 ZEND_END_ARG_INFO()
5250 
5251 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setMetadata, 0, 0, 1)
5252 	ZEND_ARG_INFO(0, metadata)
5253 ZEND_END_ARG_INFO()
5254 
5255 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setSigAlgo, 0, 0, 1)
5256 	ZEND_ARG_INFO(0, algorithm)
5257 	ZEND_ARG_INFO(0, privatekey)
5258 ZEND_END_ARG_INFO()
5259 
5260 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_setStub, 0, 0, 1)
5261 	ZEND_ARG_INFO(0, newstub)
5262 	ZEND_ARG_INFO(0, maxlen)
5263 ZEND_END_ARG_INFO()
5264 
5265 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_emptydir, 0, 0, 0)
5266 	ZEND_ARG_INFO(0, dirname)
5267 ZEND_END_ARG_INFO()
5268 
5269 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_extract, 0, 0, 1)
5270 	ZEND_ARG_INFO(0, pathto)
5271 	ZEND_ARG_INFO(0, files)
5272 	ZEND_ARG_INFO(0, overwrite)
5273 ZEND_END_ARG_INFO()
5274 
5275 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_addfile, 0, 0, 1)
5276 	ZEND_ARG_INFO(0, filename)
5277 	ZEND_ARG_INFO(0, localname)
5278 ZEND_END_ARG_INFO()
5279 
5280 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_fromstring, 0, 0, 1)
5281 	ZEND_ARG_INFO(0, localname)
5282 	ZEND_ARG_INFO(0, contents)
5283 ZEND_END_ARG_INFO()
5284 
5285 ZEND_BEGIN_ARG_INFO_EX(arginfo_phar_isff, 0, 0, 1)
5286 	ZEND_ARG_INFO(0, fileformat)
5287 ZEND_END_ARG_INFO()
5288 
5289 ZEND_BEGIN_ARG_INFO(arginfo_phar__void, 0)
5290 ZEND_END_ARG_INFO()
5291 
5292 
5293 static const zend_function_entry php_archive_methods[] = {
5294 	PHP_ME(Phar, __construct,           arginfo_phar___construct,  ZEND_ACC_PUBLIC)
5295 	PHP_ME(Phar, __destruct,            arginfo_phar__void,        ZEND_ACC_PUBLIC)
5296 	PHP_ME(Phar, addEmptyDir,           arginfo_phar_emptydir,     ZEND_ACC_PUBLIC)
5297 	PHP_ME(Phar, addFile,               arginfo_phar_addfile,      ZEND_ACC_PUBLIC)
5298 	PHP_ME(Phar, addFromString,         arginfo_phar_fromstring,   ZEND_ACC_PUBLIC)
5299 	PHP_ME(Phar, buildFromDirectory,    arginfo_phar_fromdir,      ZEND_ACC_PUBLIC)
5300 	PHP_ME(Phar, buildFromIterator,     arginfo_phar_build,        ZEND_ACC_PUBLIC)
5301 	PHP_ME(Phar, compressFiles,         arginfo_phar_comp,         ZEND_ACC_PUBLIC)
5302 	PHP_ME(Phar, decompressFiles,       arginfo_phar__void,        ZEND_ACC_PUBLIC)
5303 	PHP_ME(Phar, compress,              arginfo_phar_comps,        ZEND_ACC_PUBLIC)
5304 	PHP_ME(Phar, decompress,            arginfo_phar_decomp,       ZEND_ACC_PUBLIC)
5305 	PHP_ME(Phar, convertToExecutable,   arginfo_phar_conv,         ZEND_ACC_PUBLIC)
5306 	PHP_ME(Phar, convertToData,         arginfo_phar_conv,         ZEND_ACC_PUBLIC)
5307 	PHP_ME(Phar, copy,                  arginfo_phar_copy,         ZEND_ACC_PUBLIC)
5308 	PHP_ME(Phar, count,                 arginfo_phar__void,        ZEND_ACC_PUBLIC)
5309 	PHP_ME(Phar, delete,                arginfo_phar_delete,       ZEND_ACC_PUBLIC)
5310 	PHP_ME(Phar, delMetadata,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5311 	PHP_ME(Phar, extractTo,             arginfo_phar_extract,      ZEND_ACC_PUBLIC)
5312 	PHP_ME(Phar, getAlias,              arginfo_phar__void,        ZEND_ACC_PUBLIC)
5313 	PHP_ME(Phar, getPath,               arginfo_phar__void,        ZEND_ACC_PUBLIC)
5314 	PHP_ME(Phar, getMetadata,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5315 	PHP_ME(Phar, getModified,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5316 	PHP_ME(Phar, getSignature,          arginfo_phar__void,        ZEND_ACC_PUBLIC)
5317 	PHP_ME(Phar, getStub,               arginfo_phar__void,        ZEND_ACC_PUBLIC)
5318 	PHP_ME(Phar, getVersion,            arginfo_phar__void,        ZEND_ACC_PUBLIC)
5319 	PHP_ME(Phar, hasMetadata,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5320 	PHP_ME(Phar, isBuffering,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5321 	PHP_ME(Phar, isCompressed,          arginfo_phar__void,        ZEND_ACC_PUBLIC)
5322 	PHP_ME(Phar, isFileFormat,          arginfo_phar_isff,         ZEND_ACC_PUBLIC)
5323 	PHP_ME(Phar, isWritable,            arginfo_phar__void,        ZEND_ACC_PUBLIC)
5324 	PHP_ME(Phar, offsetExists,          arginfo_phar_offsetExists, ZEND_ACC_PUBLIC)
5325 	PHP_ME(Phar, offsetGet,             arginfo_phar_offsetExists, ZEND_ACC_PUBLIC)
5326 	PHP_ME(Phar, offsetSet,             arginfo_phar_offsetSet,    ZEND_ACC_PUBLIC)
5327 	PHP_ME(Phar, offsetUnset,           arginfo_phar_offsetExists, ZEND_ACC_PUBLIC)
5328 	PHP_ME(Phar, setAlias,              arginfo_phar_setAlias,     ZEND_ACC_PUBLIC)
5329 	PHP_ME(Phar, setDefaultStub,        arginfo_phar_createDS,     ZEND_ACC_PUBLIC)
5330 	PHP_ME(Phar, setMetadata,           arginfo_phar_setMetadata,  ZEND_ACC_PUBLIC)
5331 	PHP_ME(Phar, setSignatureAlgorithm, arginfo_phar_setSigAlgo,   ZEND_ACC_PUBLIC)
5332 	PHP_ME(Phar, setStub,               arginfo_phar_setStub,      ZEND_ACC_PUBLIC)
5333 	PHP_ME(Phar, startBuffering,        arginfo_phar__void,        ZEND_ACC_PUBLIC)
5334 	PHP_ME(Phar, stopBuffering,         arginfo_phar__void,        ZEND_ACC_PUBLIC)
5335 	/* static member functions */
5336 	PHP_ME(Phar, apiVersion,            arginfo_phar__void,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5337 	PHP_ME(Phar, canCompress,           arginfo_phar_cancompress,  ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5338 	PHP_ME(Phar, canWrite,              arginfo_phar__void,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5339 	PHP_ME(Phar, createDefaultStub,     arginfo_phar_createDS,     ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5340 	PHP_ME(Phar, getSupportedCompression,arginfo_phar__void,       ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5341 	PHP_ME(Phar, getSupportedSignatures,arginfo_phar__void,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5342 	PHP_ME(Phar, interceptFileFuncs,    arginfo_phar__void,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5343 	PHP_ME(Phar, isValidPharFilename,   arginfo_phar_isvalidpharfilename, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5344 	PHP_ME(Phar, loadPhar,              arginfo_phar_loadPhar,     ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5345 	PHP_ME(Phar, mapPhar,               arginfo_phar_mapPhar,      ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5346 	PHP_ME(Phar, running,               arginfo_phar_running,      ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5347 	PHP_ME(Phar, mount,                 arginfo_phar_mount,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5348 	PHP_ME(Phar, mungServer,            arginfo_phar_mungServer,   ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5349 	PHP_ME(Phar, unlinkArchive,         arginfo_phar_ua,           ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5350 	PHP_ME(Phar, webPhar,               arginfo_phar_webPhar,      ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5351 	PHP_FE_END
5352 };
5353 
5354 
5355 ZEND_BEGIN_ARG_INFO_EX(arginfo_data___construct, 0, 0, 1)
5356     ZEND_ARG_INFO(0, filename)
5357     ZEND_ARG_INFO(0, flags)
5358     ZEND_ARG_INFO(0, alias)
5359     ZEND_ARG_INFO(0, fileformat)
5360 ZEND_END_ARG_INFO()
5361 
5362 static const zend_function_entry php_data_methods[] = {
5363     PHP_ME(Phar, __construct,           arginfo_data___construct,  ZEND_ACC_PUBLIC)
5364     PHP_ME(Phar, __destruct,            arginfo_phar__void,        ZEND_ACC_PUBLIC)
5365     PHP_ME(Phar, addEmptyDir,           arginfo_phar_emptydir,     ZEND_ACC_PUBLIC)
5366     PHP_ME(Phar, addFile,               arginfo_phar_addfile,      ZEND_ACC_PUBLIC)
5367     PHP_ME(Phar, addFromString,         arginfo_phar_fromstring,   ZEND_ACC_PUBLIC)
5368     PHP_ME(Phar, buildFromDirectory,    arginfo_phar_fromdir,      ZEND_ACC_PUBLIC)
5369     PHP_ME(Phar, buildFromIterator,     arginfo_phar_build,        ZEND_ACC_PUBLIC)
5370     PHP_ME(Phar, compressFiles,         arginfo_phar_comp,         ZEND_ACC_PUBLIC)
5371     PHP_ME(Phar, decompressFiles,       arginfo_phar__void,        ZEND_ACC_PUBLIC)
5372     PHP_ME(Phar, compress,              arginfo_phar_comps,        ZEND_ACC_PUBLIC)
5373     PHP_ME(Phar, decompress,            arginfo_phar_decomp,       ZEND_ACC_PUBLIC)
5374     PHP_ME(Phar, convertToExecutable,   arginfo_phar_conv,         ZEND_ACC_PUBLIC)
5375     PHP_ME(Phar, convertToData,         arginfo_phar_conv,         ZEND_ACC_PUBLIC)
5376     PHP_ME(Phar, copy,                  arginfo_phar_copy,         ZEND_ACC_PUBLIC)
5377     PHP_ME(Phar, count,                 arginfo_phar__void,        ZEND_ACC_PUBLIC)
5378     PHP_ME(Phar, delete,                arginfo_phar_delete,       ZEND_ACC_PUBLIC)
5379     PHP_ME(Phar, delMetadata,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5380     PHP_ME(Phar, extractTo,             arginfo_phar_extract,      ZEND_ACC_PUBLIC)
5381     PHP_ME(Phar, getAlias,              arginfo_phar__void,        ZEND_ACC_PUBLIC)
5382     PHP_ME(Phar, getPath,               arginfo_phar__void,        ZEND_ACC_PUBLIC)
5383     PHP_ME(Phar, getMetadata,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5384     PHP_ME(Phar, getModified,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5385     PHP_ME(Phar, getSignature,          arginfo_phar__void,        ZEND_ACC_PUBLIC)
5386     PHP_ME(Phar, getStub,               arginfo_phar__void,        ZEND_ACC_PUBLIC)
5387     PHP_ME(Phar, getVersion,            arginfo_phar__void,        ZEND_ACC_PUBLIC)
5388     PHP_ME(Phar, hasMetadata,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5389     PHP_ME(Phar, isBuffering,           arginfo_phar__void,        ZEND_ACC_PUBLIC)
5390     PHP_ME(Phar, isCompressed,          arginfo_phar__void,        ZEND_ACC_PUBLIC)
5391     PHP_ME(Phar, isFileFormat,          arginfo_phar_isff,         ZEND_ACC_PUBLIC)
5392     PHP_ME(Phar, isWritable,            arginfo_phar__void,        ZEND_ACC_PUBLIC)
5393     PHP_ME(Phar, offsetExists,          arginfo_phar_offsetExists, ZEND_ACC_PUBLIC)
5394     PHP_ME(Phar, offsetGet,             arginfo_phar_offsetExists, ZEND_ACC_PUBLIC)
5395     PHP_ME(Phar, offsetSet,             arginfo_phar_offsetSet,    ZEND_ACC_PUBLIC)
5396     PHP_ME(Phar, offsetUnset,           arginfo_phar_offsetExists, ZEND_ACC_PUBLIC)
5397     PHP_ME(Phar, setAlias,              arginfo_phar_setAlias,     ZEND_ACC_PUBLIC)
5398     PHP_ME(Phar, setDefaultStub,        arginfo_phar_createDS,     ZEND_ACC_PUBLIC)
5399     PHP_ME(Phar, setMetadata,           arginfo_phar_setMetadata,  ZEND_ACC_PUBLIC)
5400     PHP_ME(Phar, setSignatureAlgorithm, arginfo_phar_setSigAlgo,   ZEND_ACC_PUBLIC)
5401     PHP_ME(Phar, setStub,               arginfo_phar_setStub,      ZEND_ACC_PUBLIC)
5402     PHP_ME(Phar, startBuffering,        arginfo_phar__void,        ZEND_ACC_PUBLIC)
5403     PHP_ME(Phar, stopBuffering,         arginfo_phar__void,        ZEND_ACC_PUBLIC)
5404     /* static member functions */
5405     PHP_ME(Phar, apiVersion,            arginfo_phar__void,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5406     PHP_ME(Phar, canCompress,           arginfo_phar_cancompress,  ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5407     PHP_ME(Phar, canWrite,              arginfo_phar__void,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5408     PHP_ME(Phar, createDefaultStub,     arginfo_phar_createDS,     ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5409     PHP_ME(Phar, getSupportedCompression,arginfo_phar__void,       ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5410     PHP_ME(Phar, getSupportedSignatures,arginfo_phar__void,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5411     PHP_ME(Phar, interceptFileFuncs,    arginfo_phar__void,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5412     PHP_ME(Phar, isValidPharFilename,   arginfo_phar_isvalidpharfilename, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5413     PHP_ME(Phar, loadPhar,              arginfo_phar_loadPhar,     ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5414     PHP_ME(Phar, mapPhar,               arginfo_phar_mapPhar,      ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5415     PHP_ME(Phar, running,               arginfo_phar_running,      ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5416     PHP_ME(Phar, mount,                 arginfo_phar_mount,        ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5417     PHP_ME(Phar, mungServer,            arginfo_phar_mungServer,   ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5418     PHP_ME(Phar, unlinkArchive,         arginfo_phar_ua,           ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5419     PHP_ME(Phar, webPhar,               arginfo_phar_webPhar,      ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
5420     PHP_FE_END
5421 };
5422 
5423 ZEND_BEGIN_ARG_INFO_EX(arginfo_entry___construct, 0, 0, 1)
5424 	ZEND_ARG_INFO(0, filename)
5425 ZEND_END_ARG_INFO()
5426 
5427 ZEND_BEGIN_ARG_INFO_EX(arginfo_entry_chmod, 0, 0, 1)
5428 	ZEND_ARG_INFO(0, perms)
5429 ZEND_END_ARG_INFO()
5430 
5431 static const zend_function_entry php_entry_methods[] = {
5432 	PHP_ME(PharFileInfo, __construct,        arginfo_entry___construct,  ZEND_ACC_PUBLIC)
5433 	PHP_ME(PharFileInfo, __destruct,         arginfo_phar__void,         ZEND_ACC_PUBLIC)
5434 	PHP_ME(PharFileInfo, chmod,              arginfo_entry_chmod,        ZEND_ACC_PUBLIC)
5435 	PHP_ME(PharFileInfo, compress,           arginfo_phar_comp,          ZEND_ACC_PUBLIC)
5436 	PHP_ME(PharFileInfo, decompress,         arginfo_phar__void,         ZEND_ACC_PUBLIC)
5437 	PHP_ME(PharFileInfo, delMetadata,        arginfo_phar__void,         ZEND_ACC_PUBLIC)
5438 	PHP_ME(PharFileInfo, getCompressedSize,  arginfo_phar__void,         ZEND_ACC_PUBLIC)
5439 	PHP_ME(PharFileInfo, getCRC32,           arginfo_phar__void,         ZEND_ACC_PUBLIC)
5440 	PHP_ME(PharFileInfo, getContent,         arginfo_phar__void,         ZEND_ACC_PUBLIC)
5441 	PHP_ME(PharFileInfo, getMetadata,        arginfo_phar__void,         ZEND_ACC_PUBLIC)
5442 	PHP_ME(PharFileInfo, getPharFlags,       arginfo_phar__void,         ZEND_ACC_PUBLIC)
5443 	PHP_ME(PharFileInfo, hasMetadata,        arginfo_phar__void,         ZEND_ACC_PUBLIC)
5444 	PHP_ME(PharFileInfo, isCompressed,       arginfo_phar_compo,         ZEND_ACC_PUBLIC)
5445 	PHP_ME(PharFileInfo, isCRCChecked,       arginfo_phar__void,         ZEND_ACC_PUBLIC)
5446 	PHP_ME(PharFileInfo, setMetadata,        arginfo_phar_setMetadata,   ZEND_ACC_PUBLIC)
5447 	PHP_FE_END
5448 };
5449 
5450 static const zend_function_entry phar_exception_methods[] = {
5451 	PHP_FE_END
5452 };
5453 /* }}} */
5454 
5455 #define REGISTER_PHAR_CLASS_CONST_LONG(class_name, const_name, value) \
5456 	zend_declare_class_constant_long(class_name, const_name, sizeof(const_name)-1, (zend_long)value);
5457 
phar_object_init(void)5458 void phar_object_init(void) /* {{{ */
5459 {
5460 	zend_class_entry ce;
5461 
5462 	INIT_CLASS_ENTRY(ce, "PharException", phar_exception_methods);
5463 	phar_ce_PharException = zend_register_internal_class_ex(&ce, zend_ce_exception);
5464 
5465 	INIT_CLASS_ENTRY(ce, "Phar", php_archive_methods);
5466 	phar_ce_archive = zend_register_internal_class_ex(&ce, spl_ce_RecursiveDirectoryIterator);
5467 
5468 	zend_class_implements(phar_ce_archive, 2, zend_ce_countable, zend_ce_arrayaccess);
5469 
5470 	INIT_CLASS_ENTRY(ce, "PharData", php_data_methods);
5471 	phar_ce_data = zend_register_internal_class_ex(&ce, spl_ce_RecursiveDirectoryIterator);
5472 
5473 	zend_class_implements(phar_ce_data, 2, zend_ce_countable, zend_ce_arrayaccess);
5474 
5475 	INIT_CLASS_ENTRY(ce, "PharFileInfo", php_entry_methods);
5476 	phar_ce_entry = zend_register_internal_class_ex(&ce, spl_ce_SplFileInfo);
5477 
5478 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "BZ2", PHAR_ENT_COMPRESSED_BZ2)
5479 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "GZ", PHAR_ENT_COMPRESSED_GZ)
5480 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "NONE", PHAR_ENT_COMPRESSED_NONE)
5481 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHAR", PHAR_FORMAT_PHAR)
5482 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "TAR", PHAR_FORMAT_TAR)
5483 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "ZIP", PHAR_FORMAT_ZIP)
5484 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "COMPRESSED", PHAR_ENT_COMPRESSION_MASK)
5485 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHP", PHAR_MIME_PHP)
5486 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "PHPS", PHAR_MIME_PHPS)
5487 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "MD5", PHAR_SIG_MD5)
5488 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "OPENSSL", PHAR_SIG_OPENSSL)
5489 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA1", PHAR_SIG_SHA1)
5490 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA256", PHAR_SIG_SHA256)
5491 	REGISTER_PHAR_CLASS_CONST_LONG(phar_ce_archive, "SHA512", PHAR_SIG_SHA512)
5492 }
5493 /* }}} */
5494