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