xref: /php-src/ext/phar/stream.c (revision ed8ed714)
1 /*
2   +----------------------------------------------------------------------+
3   | phar:// stream wrapper support                                       |
4   +----------------------------------------------------------------------+
5   | Copyright (c) The PHP Group                                          |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | https://www.php.net/license/3_01.txt                                 |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Gregory Beaver <cellog@php.net>                             |
16   |          Marcus Boerger <helly@php.net>                              |
17   +----------------------------------------------------------------------+
18 */
19 
20 #define PHAR_STREAM 1
21 #include "phar_internal.h"
22 #include "stream.h"
23 #include "dirstream.h"
24 
25 const php_stream_ops phar_ops = {
26 	phar_stream_write, /* write */
27 	phar_stream_read,  /* read */
28 	phar_stream_close, /* close */
29 	phar_stream_flush, /* flush */
30 	"phar stream",
31 	phar_stream_seek,  /* seek */
32 	NULL,              /* cast */
33 	phar_stream_stat,  /* stat */
34 	NULL, /* set option */
35 };
36 
37 const php_stream_wrapper_ops phar_stream_wops = {
38 	phar_wrapper_open_url,
39 	NULL,                  /* phar_wrapper_close */
40 	NULL,                  /* phar_wrapper_stat, */
41 	phar_wrapper_stat,     /* stat_url */
42 	phar_wrapper_open_dir, /* opendir */
43 	"phar",
44 	phar_wrapper_unlink,   /* unlink */
45 	phar_wrapper_rename,   /* rename */
46 	phar_wrapper_mkdir,    /* create directory */
47 	phar_wrapper_rmdir,    /* remove directory */
48 	NULL
49 };
50 
51 const php_stream_wrapper php_stream_phar_wrapper = {
52 	&phar_stream_wops,
53 	NULL,
54 	0 /* is_url */
55 };
56 
57 /**
58  * Open a phar file for streams API
59  */
phar_parse_url(php_stream_wrapper * wrapper,const char * filename,const char * mode,int options)60 php_url* phar_parse_url(php_stream_wrapper *wrapper, const char *filename, const char *mode, int options) /* {{{ */
61 {
62 	php_url *resource;
63 	char *arch = NULL, *entry = NULL, *error;
64 	size_t arch_len, entry_len;
65 
66 	if (strlen(filename) < 7 || strncasecmp(filename, "phar://", 7)) {
67 		return NULL;
68 	}
69 	if (mode[0] == 'a') {
70 		if (!(options & PHP_STREAM_URL_STAT_QUIET)) {
71 			php_stream_wrapper_log_error(wrapper, options, "phar error: open mode append not supported");
72 		}
73 		return NULL;
74 	}
75 	if (phar_split_fname(filename, strlen(filename), &arch, &arch_len, &entry, &entry_len, 2, (mode[0] == 'w' ? 2 : 0)) == FAILURE) {
76 		if (!(options & PHP_STREAM_URL_STAT_QUIET)) {
77 			if (arch && !entry) {
78 				php_stream_wrapper_log_error(wrapper, options, "phar error: no directory in \"%s\", must have at least phar://%s/ for root directory (always use full path to a new phar)", filename, arch);
79 				arch = NULL;
80 			} else {
81 				php_stream_wrapper_log_error(wrapper, options, "phar error: invalid url or non-existent phar \"%s\"", filename);
82 			}
83 		}
84 		return NULL;
85 	}
86 	resource = ecalloc(1, sizeof(php_url));
87 	resource->scheme = ZSTR_INIT_LITERAL("phar", 0);
88 	resource->host = zend_string_init(arch, arch_len, 0);
89 	efree(arch);
90 	resource->path = zend_string_init(entry, entry_len, 0);
91 	efree(entry);
92 
93 #ifdef MBO_0
94 		if (resource) {
95 			fprintf(stderr, "Alias:     %s\n", alias);
96 			fprintf(stderr, "Scheme:    %s\n", ZSTR_VAL(resource->scheme));
97 /*			fprintf(stderr, "User:      %s\n", resource->user);*/
98 /*			fprintf(stderr, "Pass:      %s\n", resource->pass ? "***" : NULL);*/
99 			fprintf(stderr, "Host:      %s\n", ZSTR_VAL(resource->host));
100 /*			fprintf(stderr, "Port:      %d\n", resource->port);*/
101 			fprintf(stderr, "Path:      %s\n", ZSTR_VAL(resource->path));
102 /*			fprintf(stderr, "Query:     %s\n", resource->query);*/
103 /*			fprintf(stderr, "Fragment:  %s\n", resource->fragment);*/
104 		}
105 #endif
106 	if (mode[0] == 'w' || (mode[0] == 'r' && mode[1] == '+')) {
107 		phar_archive_data *pphar = NULL, *phar;
108 
109 		if (PHAR_G(request_init) && HT_IS_INITIALIZED(&PHAR_G(phar_fname_map)) && NULL == (pphar = zend_hash_find_ptr(&(PHAR_G(phar_fname_map)), resource->host))) {
110 			pphar = NULL;
111 		}
112 		if (PHAR_G(readonly) && (!pphar || !pphar->is_data)) {
113 			if (!(options & PHP_STREAM_URL_STAT_QUIET)) {
114 				php_stream_wrapper_log_error(wrapper, options, "phar error: write operations disabled by the php.ini setting phar.readonly");
115 			}
116 			php_url_free(resource);
117 			return NULL;
118 		}
119 		if (phar_open_or_create_filename(ZSTR_VAL(resource->host), ZSTR_LEN(resource->host), NULL, 0, 0, options, &phar, &error) == FAILURE)
120 		{
121 			if (error) {
122 				if (!(options & PHP_STREAM_URL_STAT_QUIET)) {
123 					php_stream_wrapper_log_error(wrapper, options, "%s", error);
124 				}
125 				efree(error);
126 			}
127 			php_url_free(resource);
128 			return NULL;
129 		}
130 		if (phar->is_persistent && FAILURE == phar_copy_on_write(&phar)) {
131 			if (error) {
132 				spprintf(&error, 0, "Cannot open cached phar '%s' as writeable, copy on write failed", ZSTR_VAL(resource->host));
133 				if (!(options & PHP_STREAM_URL_STAT_QUIET)) {
134 					php_stream_wrapper_log_error(wrapper, options, "%s", error);
135 				}
136 				efree(error);
137 			}
138 			php_url_free(resource);
139 			return NULL;
140 		}
141 	} else {
142 		if (phar_open_from_filename(ZSTR_VAL(resource->host), ZSTR_LEN(resource->host), NULL, 0, options, NULL, &error) == FAILURE)
143 		{
144 			if (error) {
145 				if (!(options & PHP_STREAM_URL_STAT_QUIET)) {
146 					php_stream_wrapper_log_error(wrapper, options, "%s", error);
147 				}
148 				efree(error);
149 			}
150 			php_url_free(resource);
151 			return NULL;
152 		}
153 	}
154 	return resource;
155 }
156 /* }}} */
157 
158 /**
159  * used for fopen('phar://...') and company
160  */
phar_wrapper_open_url(php_stream_wrapper * wrapper,const char * path,const char * mode,int options,zend_string ** opened_path,php_stream_context * context STREAMS_DC)161 static php_stream * phar_wrapper_open_url(php_stream_wrapper *wrapper, const char *path, const char *mode, int options, zend_string **opened_path, php_stream_context *context STREAMS_DC) /* {{{ */
162 {
163 	phar_archive_data *phar;
164 	phar_entry_data *idata;
165 	char *internal_file;
166 	char *error;
167 	HashTable *pharcontext;
168 	php_url *resource = NULL;
169 	php_stream *fpf;
170 	zval *pzoption, *metadata;
171 	uint32_t host_len;
172 
173 	if ((resource = phar_parse_url(wrapper, path, mode, options)) == NULL) {
174 		return NULL;
175 	}
176 
177 	/* we must have at the very least phar://alias.phar/internalfile.php */
178 	if (!resource->scheme || !resource->host || !resource->path) {
179 		php_url_free(resource);
180 		php_stream_wrapper_log_error(wrapper, options, "phar error: invalid url \"%s\"", path);
181 		return NULL;
182 	}
183 
184 	if (!zend_string_equals_literal_ci(resource->scheme, "phar")) {
185 		php_url_free(resource);
186 		php_stream_wrapper_log_error(wrapper, options, "phar error: not a phar stream url \"%s\"", path);
187 		return NULL;
188 	}
189 
190 	host_len = ZSTR_LEN(resource->host);
191 	phar_request_initialize();
192 
193 	/* strip leading "/" */
194 	internal_file = estrndup(ZSTR_VAL(resource->path) + 1, ZSTR_LEN(resource->path) - 1);
195 	if (mode[0] == 'w' || (mode[0] == 'r' && mode[1] == '+')) {
196 		if (NULL == (idata = phar_get_or_create_entry_data(ZSTR_VAL(resource->host), host_len, internal_file, strlen(internal_file), mode, 0, &error, 1))) {
197 			if (error) {
198 				php_stream_wrapper_log_error(wrapper, options, "%s", error);
199 				efree(error);
200 			} else {
201 				php_stream_wrapper_log_error(wrapper, options, "phar error: file \"%s\" could not be created in phar \"%s\"", internal_file, ZSTR_VAL(resource->host));
202 			}
203 			efree(internal_file);
204 			php_url_free(resource);
205 			return NULL;
206 		}
207 		if (error) {
208 			efree(error);
209 		}
210 		fpf = php_stream_alloc(&phar_ops, idata, NULL, mode);
211 		php_url_free(resource);
212 		efree(internal_file);
213 
214 		if (context && Z_TYPE(context->options) != IS_UNDEF && (pzoption = zend_hash_str_find(HASH_OF(&context->options), "phar", sizeof("phar")-1)) != NULL) {
215 			pharcontext = HASH_OF(pzoption);
216 			if (idata->internal_file->uncompressed_filesize == 0
217 				&& idata->internal_file->compressed_filesize == 0
218 				&& (pzoption = zend_hash_str_find(pharcontext, "compress", sizeof("compress")-1)) != NULL
219 				&& Z_TYPE_P(pzoption) == IS_LONG
220 				&& (Z_LVAL_P(pzoption) & ~PHAR_ENT_COMPRESSION_MASK) == 0
221 			) {
222 				idata->internal_file->flags &= ~PHAR_ENT_COMPRESSION_MASK;
223 				idata->internal_file->flags |= Z_LVAL_P(pzoption);
224 			}
225 			if ((pzoption = zend_hash_str_find(pharcontext, "metadata", sizeof("metadata")-1)) != NULL) {
226 				phar_metadata_tracker_free(&idata->internal_file->metadata_tracker, idata->internal_file->is_persistent);
227 
228 				metadata = pzoption;
229 				ZVAL_COPY_DEREF(&idata->internal_file->metadata_tracker.val, metadata);
230 				idata->phar->is_modified = 1;
231 			}
232 		}
233 		if (opened_path) {
234 			*opened_path = strpprintf(MAXPATHLEN, "phar://%s/%s", idata->phar->fname, idata->internal_file->filename);
235 		}
236 		return fpf;
237 	} else {
238 		if (!*internal_file && (options & STREAM_OPEN_FOR_INCLUDE)) {
239 			/* retrieve the stub */
240 			if (FAILURE == phar_get_archive(&phar, ZSTR_VAL(resource->host), host_len, NULL, 0, NULL)) {
241 				php_stream_wrapper_log_error(wrapper, options, "file %s is not a valid phar archive", ZSTR_VAL(resource->host));
242 				efree(internal_file);
243 				php_url_free(resource);
244 				return NULL;
245 			}
246 			if (phar->is_tar || phar->is_zip) {
247 				if ((FAILURE == phar_get_entry_data(&idata, ZSTR_VAL(resource->host), host_len, ".phar/stub.php", sizeof(".phar/stub.php")-1, "r", 0, &error, 0)) || !idata) {
248 					goto idata_error;
249 				}
250 				efree(internal_file);
251 				if (opened_path) {
252 					*opened_path = strpprintf(MAXPATHLEN, "%s", phar->fname);
253 				}
254 				php_url_free(resource);
255 				goto phar_stub;
256 			} else {
257 				php_stream *stream = phar_get_pharfp(phar);
258 				if (stream == NULL) {
259 					if (UNEXPECTED(FAILURE == phar_open_archive_fp(phar))) {
260 						php_stream_wrapper_log_error(wrapper, options, "phar error: could not reopen phar \"%s\"", ZSTR_VAL(resource->host));
261 						efree(internal_file);
262 						php_url_free(resource);
263 						return NULL;
264 					}
265 					stream = phar_get_pharfp(phar);
266 				}
267 
268 				phar_entry_info *entry;
269 
270 				entry = (phar_entry_info *) ecalloc(1, sizeof(phar_entry_info));
271 				entry->is_temp_dir = 1;
272 				entry->filename = estrndup("", 0);
273 				entry->filename_len = 0;
274 				entry->phar = phar;
275 				entry->offset = entry->offset_abs = 0;
276 				entry->compressed_filesize = entry->uncompressed_filesize = phar->halt_offset;
277 				entry->is_crc_checked = 1;
278 
279 				idata = (phar_entry_data *) ecalloc(1, sizeof(phar_entry_data));
280 				idata->fp = stream;
281 				idata->phar = phar;
282 				idata->internal_file = entry;
283 				if (!phar->is_persistent) {
284 					++(entry->phar->refcount);
285 				}
286 				++(entry->fp_refcount);
287 				php_url_free(resource);
288 				if (opened_path) {
289 					*opened_path = strpprintf(MAXPATHLEN, "%s", phar->fname);
290 				}
291 				efree(internal_file);
292 				goto phar_stub;
293 			}
294 		}
295 		/* read-only access is allowed to magic files in .phar directory */
296 		if ((FAILURE == phar_get_entry_data(&idata, ZSTR_VAL(resource->host), host_len, internal_file, strlen(internal_file), "r", 0, &error, 0)) || !idata) {
297 idata_error:
298 			if (error) {
299 				php_stream_wrapper_log_error(wrapper, options, "%s", error);
300 				efree(error);
301 			} else {
302 				php_stream_wrapper_log_error(wrapper, options, "phar error: \"%s\" is not a file in phar \"%s\"", internal_file, ZSTR_VAL(resource->host));
303 			}
304 			efree(internal_file);
305 			php_url_free(resource);
306 			return NULL;
307 		}
308 	}
309 	php_url_free(resource);
310 #ifdef MBO_0
311 		fprintf(stderr, "Pharname:   %s\n", idata->phar->filename);
312 		fprintf(stderr, "Filename:   %s\n", internal_file);
313 		fprintf(stderr, "Entry:      %s\n", idata->internal_file->filename);
314 		fprintf(stderr, "Size:       %u\n", idata->internal_file->uncompressed_filesize);
315 		fprintf(stderr, "Compressed: %u\n", idata->internal_file->flags);
316 		fprintf(stderr, "Offset:     %u\n", idata->internal_file->offset_within_phar);
317 		fprintf(stderr, "Cached:     %s\n", idata->internal_file->filedata ? "yes" : "no");
318 #endif
319 
320 	/* check length, crc32 */
321 	if (!idata->internal_file->is_crc_checked && phar_postprocess_file(idata, idata->internal_file->crc32, &error, 2) != SUCCESS) {
322 		php_stream_wrapper_log_error(wrapper, options, "%s", error);
323 		efree(error);
324 		phar_entry_delref(idata);
325 		efree(internal_file);
326 		return NULL;
327 	}
328 
329 	if (!PHAR_G(cwd_init) && (options & STREAM_OPEN_FOR_INCLUDE)) {
330 		char *entry = idata->internal_file->filename, *cwd;
331 
332 		PHAR_G(cwd_init) = 1;
333 		if ((idata->phar->is_tar || idata->phar->is_zip) && idata->internal_file->filename_len == sizeof(".phar/stub.php")-1 && !strncmp(idata->internal_file->filename, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
334 			/* we're executing the stub, which doesn't count as a file */
335 			PHAR_G(cwd_init) = 0;
336 		} else if ((cwd = strrchr(entry, '/'))) {
337 			PHAR_G(cwd_len) = cwd - entry;
338 			PHAR_G(cwd) = estrndup(entry, PHAR_G(cwd_len));
339 		} else {
340 			/* root directory */
341 			PHAR_G(cwd_len) = 0;
342 			PHAR_G(cwd) = NULL;
343 		}
344 	}
345 	if (opened_path) {
346 		*opened_path = strpprintf(MAXPATHLEN, "phar://%s/%s", idata->phar->fname, idata->internal_file->filename);
347 	}
348 	efree(internal_file);
349 phar_stub:
350 	fpf = php_stream_alloc(&phar_ops, idata, NULL, mode);
351 	return fpf;
352 }
353 /* }}} */
354 
355 /**
356  * Used for fclose($fp) where $fp is a phar archive
357  */
phar_stream_close(php_stream * stream,int close_handle)358 static int phar_stream_close(php_stream *stream, int close_handle) /* {{{ */
359 {
360 	/* for some reasons phar needs to be flushed even if there is no write going on */
361 	phar_stream_flush(stream);
362 
363 	phar_entry_delref((phar_entry_data *)stream->abstract);
364 
365 	return 0;
366 }
367 /* }}} */
368 
369 /**
370  * used for fread($fp) and company on a fopen()ed phar file handle
371  */
phar_stream_read(php_stream * stream,char * buf,size_t count)372 static ssize_t phar_stream_read(php_stream *stream, char *buf, size_t count) /* {{{ */
373 {
374 	phar_entry_data *data = (phar_entry_data *)stream->abstract;
375 	size_t got;
376 	phar_entry_info *entry;
377 
378 	if (data->internal_file->link) {
379 		entry = phar_get_link_source(data->internal_file);
380 	} else {
381 		entry = data->internal_file;
382 	}
383 
384 	if (entry->is_deleted) {
385 		stream->eof = 1;
386 		return -1;
387 	}
388 
389 	/* use our proxy position */
390 	php_stream_seek(data->fp, data->position + data->zero, SEEK_SET);
391 
392 	got = php_stream_read(data->fp, buf, MIN(count, (size_t)(entry->uncompressed_filesize - data->position)));
393 	data->position = php_stream_tell(data->fp) - data->zero;
394 	stream->eof = (data->position == (zend_off_t) entry->uncompressed_filesize);
395 
396 	return got;
397 }
398 /* }}} */
399 
400 /**
401  * Used for fseek($fp) on a phar file handle
402  */
phar_stream_seek(php_stream * stream,zend_off_t offset,int whence,zend_off_t * newoffset)403 static int phar_stream_seek(php_stream *stream, zend_off_t offset, int whence, zend_off_t *newoffset) /* {{{ */
404 {
405 	phar_entry_data *data = (phar_entry_data *)stream->abstract;
406 	phar_entry_info *entry;
407 	int res;
408 	zend_off_t temp;
409 
410 	if (data->internal_file->link) {
411 		entry = phar_get_link_source(data->internal_file);
412 	} else {
413 		entry = data->internal_file;
414 	}
415 
416 	switch (whence) {
417 		case SEEK_END :
418 			temp = data->zero + entry->uncompressed_filesize + offset;
419 			break;
420 		case SEEK_CUR :
421 			temp = data->zero + data->position + offset;
422 			break;
423 		case SEEK_SET :
424 			temp = data->zero + offset;
425 			break;
426 		default:
427 			temp = 0;
428 	}
429 	if (temp > data->zero + (zend_off_t) entry->uncompressed_filesize) {
430 		*newoffset = -1;
431 		return -1;
432 	}
433 	if (temp < data->zero) {
434 		*newoffset = -1;
435 		return -1;
436 	}
437 	res = php_stream_seek(data->fp, temp, SEEK_SET);
438 	*newoffset = php_stream_tell(data->fp) - data->zero;
439 	data->position = *newoffset;
440 	return res;
441 }
442 /* }}} */
443 
444 /**
445  * Used for writing to a phar file
446  */
phar_stream_write(php_stream * stream,const char * buf,size_t count)447 static ssize_t phar_stream_write(php_stream *stream, const char *buf, size_t count) /* {{{ */
448 {
449 	phar_entry_data *data = (phar_entry_data *) stream->abstract;
450 
451 	php_stream_seek(data->fp, data->position, SEEK_SET);
452 	if (count != php_stream_write(data->fp, buf, count)) {
453 		php_stream_wrapper_log_error(stream->wrapper, stream->flags, "phar error: Could not write %d characters to \"%s\" in phar \"%s\"", (int) count, data->internal_file->filename, data->phar->fname);
454 		return -1;
455 	}
456 	data->position = php_stream_tell(data->fp);
457 	if (data->position > (zend_off_t)data->internal_file->uncompressed_filesize) {
458 		data->internal_file->uncompressed_filesize = data->position;
459 	}
460 	data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize;
461 	data->internal_file->old_flags = data->internal_file->flags;
462 	data->internal_file->is_modified = 1;
463 	return count;
464 }
465 /* }}} */
466 
467 /**
468  * Used to save work done on a writeable phar
469  */
phar_stream_flush(php_stream * stream)470 static int phar_stream_flush(php_stream *stream) /* {{{ */
471 {
472 	char *error;
473 	int ret;
474 	phar_entry_data *data = (phar_entry_data *) stream->abstract;
475 
476 	if (data->internal_file->is_modified) {
477 		data->internal_file->timestamp = time(0);
478 		ret = phar_flush(data->phar, 0, 0, 0, &error);
479 		if (error) {
480 			php_stream_wrapper_log_error(stream->wrapper, REPORT_ERRORS, "%s", error);
481 			efree(error);
482 		}
483 		return ret;
484 	} else {
485 		return EOF;
486 	}
487 }
488 /* }}} */
489 
490  /* {{{ phar_dostat */
491 /**
492  * stat an opened phar file handle stream, used by phar_stat()
493  */
phar_dostat(phar_archive_data * phar,phar_entry_info * data,php_stream_statbuf * ssb,bool is_temp_dir)494 void phar_dostat(phar_archive_data *phar, phar_entry_info *data, php_stream_statbuf *ssb, bool is_temp_dir)
495 {
496 	memset(ssb, 0, sizeof(php_stream_statbuf));
497 
498 	if (!is_temp_dir && !data->is_dir) {
499 		ssb->sb.st_size = data->uncompressed_filesize;
500 		ssb->sb.st_mode = data->flags & PHAR_ENT_PERM_MASK;
501 		ssb->sb.st_mode |= S_IFREG; /* regular file */
502 		/* timestamp is just the timestamp when this was added to the phar */
503 		ssb->sb.st_mtime = data->timestamp;
504 		ssb->sb.st_atime = data->timestamp;
505 		ssb->sb.st_ctime = data->timestamp;
506 	} else if (!is_temp_dir && data->is_dir) {
507 		ssb->sb.st_size = 0;
508 		ssb->sb.st_mode = data->flags & PHAR_ENT_PERM_MASK;
509 		ssb->sb.st_mode |= S_IFDIR; /* regular directory */
510 		/* timestamp is just the timestamp when this was added to the phar */
511 		ssb->sb.st_mtime = data->timestamp;
512 		ssb->sb.st_atime = data->timestamp;
513 		ssb->sb.st_ctime = data->timestamp;
514 	} else {
515 		ssb->sb.st_size = 0;
516 		ssb->sb.st_mode = 0777;
517 		ssb->sb.st_mode |= S_IFDIR; /* regular directory */
518 		ssb->sb.st_mtime = phar->max_timestamp;
519 		ssb->sb.st_atime = phar->max_timestamp;
520 		ssb->sb.st_ctime = phar->max_timestamp;
521 	}
522 	if (!phar->is_writeable) {
523 		ssb->sb.st_mode = (ssb->sb.st_mode & 0555) | (ssb->sb.st_mode & ~0777);
524 	}
525 
526 	ssb->sb.st_nlink = 1;
527 	ssb->sb.st_rdev = -1;
528 	/* this is only for APC, so use /dev/null device - no chance of conflict there! */
529 	ssb->sb.st_dev = 0xc;
530 	/* generate unique inode number for alias/filename, so no phars will conflict */
531 	if (!is_temp_dir) {
532 		ssb->sb.st_ino = data->inode;
533 	}
534 #ifndef PHP_WIN32
535 	ssb->sb.st_blksize = -1;
536 	ssb->sb.st_blocks = -1;
537 #endif
538 }
539 /* }}}*/
540 
541 /**
542  * Stat an opened phar file handle
543  */
phar_stream_stat(php_stream * stream,php_stream_statbuf * ssb)544 static int phar_stream_stat(php_stream *stream, php_stream_statbuf *ssb) /* {{{ */
545 {
546 	phar_entry_data *data = (phar_entry_data *)stream->abstract;
547 
548 	/* If ssb is NULL then someone is misbehaving */
549 	if (!ssb) {
550 		return -1;
551 	}
552 
553 	phar_dostat(data->phar, data->internal_file, ssb, 0);
554 	return 0;
555 }
556 /* }}} */
557 
558 /**
559  * Stream wrapper stat implementation of stat()
560  */
phar_wrapper_stat(php_stream_wrapper * wrapper,const char * url,int flags,php_stream_statbuf * ssb,php_stream_context * context)561 static int phar_wrapper_stat(php_stream_wrapper *wrapper, const char *url, int flags,
562 				  php_stream_statbuf *ssb, php_stream_context *context) /* {{{ */
563 {
564 	php_url *resource = NULL;
565 	char *internal_file, *error;
566 	phar_archive_data *phar;
567 	phar_entry_info *entry;
568 	uint32_t host_len;
569 	size_t internal_file_len;
570 
571 	if ((resource = phar_parse_url(wrapper, url, "r", flags|PHP_STREAM_URL_STAT_QUIET)) == NULL) {
572 		return FAILURE;
573 	}
574 
575 	/* we must have at the very least phar://alias.phar/internalfile.php */
576 	if (!resource->scheme || !resource->host || !resource->path) {
577 		php_url_free(resource);
578 		return FAILURE;
579 	}
580 
581 	if (!zend_string_equals_literal_ci(resource->scheme, "phar")) {
582 		php_url_free(resource);
583 		return FAILURE;
584 	}
585 
586 	host_len = ZSTR_LEN(resource->host);
587 	phar_request_initialize();
588 
589 	internal_file = ZSTR_VAL(resource->path) + 1; /* strip leading "/" */
590 	/* find the phar in our trusty global hash indexed by alias (host of phar://blah.phar/file.whatever) */
591 	if (FAILURE == phar_get_archive(&phar, ZSTR_VAL(resource->host), host_len, NULL, 0, &error)) {
592 		php_url_free(resource);
593 		if (error) {
594 			efree(error);
595 		}
596 		return FAILURE;
597 	}
598 	if (error) {
599 		efree(error);
600 	}
601 	if (*internal_file == '\0') {
602 		/* root directory requested */
603 		phar_dostat(phar, NULL, ssb, 1);
604 		php_url_free(resource);
605 		return SUCCESS;
606 	}
607 	if (!HT_IS_INITIALIZED(&phar->manifest)) {
608 		php_url_free(resource);
609 		return FAILURE;
610 	}
611 	internal_file_len = strlen(internal_file);
612 	/* search through the manifest of files, and if we have an exact match, it's a file */
613 	if (NULL != (entry = zend_hash_str_find_ptr(&phar->manifest, internal_file, internal_file_len))) {
614 		phar_dostat(phar, entry, ssb, 0);
615 		php_url_free(resource);
616 		return SUCCESS;
617 	}
618 	if (zend_hash_str_exists(&(phar->virtual_dirs), internal_file, internal_file_len)) {
619 		phar_dostat(phar, NULL, ssb, 1);
620 		php_url_free(resource);
621 		return SUCCESS;
622 	}
623 	/* check for mounted directories */
624 	if (HT_IS_INITIALIZED(&phar->mounted_dirs) && zend_hash_num_elements(&phar->mounted_dirs)) {
625 		zend_string *str_key;
626 
627 		ZEND_HASH_MAP_FOREACH_STR_KEY(&phar->mounted_dirs, str_key) {
628 			if (ZSTR_LEN(str_key) >= internal_file_len || strncmp(ZSTR_VAL(str_key), internal_file, ZSTR_LEN(str_key))) {
629 				continue;
630 			} else {
631 				char *test;
632 				size_t test_len;
633 				php_stream_statbuf ssbi;
634 
635 				if (NULL == (entry = zend_hash_find_ptr(&phar->manifest, str_key))) {
636 					goto free_resource;
637 				}
638 				if (!entry->tmp || !entry->is_mounted) {
639 					goto free_resource;
640 				}
641 				test_len = spprintf(&test, MAXPATHLEN, "%s%s", entry->tmp, internal_file + ZSTR_LEN(str_key));
642 				if (SUCCESS != php_stream_stat_path(test, &ssbi)) {
643 					efree(test);
644 					continue;
645 				}
646 				/* mount the file/directory just in time */
647 				if (SUCCESS != phar_mount_entry(phar, test, test_len, internal_file, internal_file_len)) {
648 					efree(test);
649 					goto free_resource;
650 				}
651 				efree(test);
652 				if (NULL == (entry = zend_hash_str_find_ptr(&phar->manifest, internal_file, internal_file_len))) {
653 					goto free_resource;
654 				}
655 				phar_dostat(phar, entry, ssb, 0);
656 				php_url_free(resource);
657 				return SUCCESS;
658 			}
659 		} ZEND_HASH_FOREACH_END();
660 	}
661 free_resource:
662 	php_url_free(resource);
663 	return FAILURE;
664 }
665 /* }}} */
666 
667 /**
668  * Unlink a file within a phar archive
669  */
phar_wrapper_unlink(php_stream_wrapper * wrapper,const char * url,int options,php_stream_context * context)670 static int phar_wrapper_unlink(php_stream_wrapper *wrapper, const char *url, int options, php_stream_context *context) /* {{{ */
671 {
672 	php_url *resource;
673 	char *internal_file, *error;
674 	int internal_file_len;
675 	phar_entry_data *idata;
676 	phar_archive_data *pphar;
677 	uint32_t host_len;
678 
679 	if ((resource = phar_parse_url(wrapper, url, "rb", options)) == NULL) {
680 		php_stream_wrapper_log_error(wrapper, options, "phar error: unlink failed");
681 		return 0;
682 	}
683 
684 	/* we must have at the very least phar://alias.phar/internalfile.php */
685 	if (!resource->scheme || !resource->host || !resource->path) {
686 		php_url_free(resource);
687 		php_stream_wrapper_log_error(wrapper, options, "phar error: invalid url \"%s\"", url);
688 		return 0;
689 	}
690 
691 	if (!zend_string_equals_literal_ci(resource->scheme, "phar")) {
692 		php_url_free(resource);
693 		php_stream_wrapper_log_error(wrapper, options, "phar error: not a phar stream url \"%s\"", url);
694 		return 0;
695 	}
696 
697 	host_len = ZSTR_LEN(resource->host);
698 	phar_request_initialize();
699 
700 	pphar = zend_hash_find_ptr(&(PHAR_G(phar_fname_map)), resource->host);
701 	if (PHAR_G(readonly) && (!pphar || !pphar->is_data)) {
702 		php_url_free(resource);
703 		php_stream_wrapper_log_error(wrapper, options, "phar error: write operations disabled by the php.ini setting phar.readonly");
704 		return 0;
705 	}
706 
707 	/* need to copy to strip leading "/", will get touched again */
708 	internal_file = estrndup(ZSTR_VAL(resource->path) + 1, ZSTR_LEN(resource->path) - 1);
709 	internal_file_len = ZSTR_LEN(resource->path) - 1;
710 	if (FAILURE == phar_get_entry_data(&idata, ZSTR_VAL(resource->host), host_len, internal_file, internal_file_len, "r", 0, &error, 1)) {
711 		/* constraints of fp refcount were not met */
712 		if (error) {
713 			php_stream_wrapper_log_error(wrapper, options, "unlink of \"%s\" failed: %s", url, error);
714 			efree(error);
715 		} else {
716 			php_stream_wrapper_log_error(wrapper, options, "unlink of \"%s\" failed, file does not exist", url);
717 		}
718 		efree(internal_file);
719 		php_url_free(resource);
720 		return 0;
721 	}
722 	if (error) {
723 		efree(error);
724 	}
725 	if (idata->internal_file->fp_refcount > 1) {
726 		/* more than just our fp resource is open for this file */
727 		php_stream_wrapper_log_error(wrapper, options, "phar error: \"%s\" in phar \"%s\", has open file pointers, cannot unlink", internal_file, ZSTR_VAL(resource->host));
728 		efree(internal_file);
729 		php_url_free(resource);
730 		phar_entry_delref(idata);
731 		return 0;
732 	}
733 	php_url_free(resource);
734 	efree(internal_file);
735 	phar_entry_remove(idata, &error);
736 	if (error) {
737 		php_stream_wrapper_log_error(wrapper, options, "%s", error);
738 		efree(error);
739 	}
740 	return 1;
741 }
742 /* }}} */
743 
phar_wrapper_rename(php_stream_wrapper * wrapper,const char * url_from,const char * url_to,int options,php_stream_context * context)744 static int phar_wrapper_rename(php_stream_wrapper *wrapper, const char *url_from, const char *url_to, int options, php_stream_context *context) /* {{{ */
745 {
746 	php_url *resource_from, *resource_to;
747 	char *error;
748 	phar_archive_data *phar, *pfrom, *pto;
749 	phar_entry_info *entry;
750 	uint32_t host_len;
751 	int is_dir = 0;
752 	int is_modified = 0;
753 
754 	error = NULL;
755 
756 	if ((resource_from = phar_parse_url(wrapper, url_from, "wb", options|PHP_STREAM_URL_STAT_QUIET)) == NULL) {
757 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": invalid or non-writable url \"%s\"", url_from, url_to, url_from);
758 		return 0;
759 	}
760 	if (SUCCESS != phar_get_archive(&pfrom, ZSTR_VAL(resource_from->host), ZSTR_LEN(resource_from->host), NULL, 0, &error)) {
761 		pfrom = NULL;
762 		if (error) {
763 			efree(error);
764 		}
765 	}
766 	if (PHAR_G(readonly) && (!pfrom || !pfrom->is_data)) {
767 		php_url_free(resource_from);
768 		php_error_docref(NULL, E_WARNING, "phar error: Write operations disabled by the php.ini setting phar.readonly");
769 		return 0;
770 	}
771 
772 	if ((resource_to = phar_parse_url(wrapper, url_to, "wb", options|PHP_STREAM_URL_STAT_QUIET)) == NULL) {
773 		php_url_free(resource_from);
774 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": invalid or non-writable url \"%s\"", url_from, url_to, url_to);
775 		return 0;
776 	}
777 	if (SUCCESS != phar_get_archive(&pto, ZSTR_VAL(resource_to->host), ZSTR_LEN(resource_to->host), NULL, 0, &error)) {
778 		if (error) {
779 			efree(error);
780 		}
781 		pto = NULL;
782 	}
783 	if (PHAR_G(readonly) && (!pto || !pto->is_data)) {
784 		php_url_free(resource_from);
785 		php_error_docref(NULL, E_WARNING, "phar error: Write operations disabled by the php.ini setting phar.readonly");
786 		return 0;
787 	}
788 
789 	if (!zend_string_equals(resource_from->host, resource_to->host)) {
790 		php_url_free(resource_from);
791 		php_url_free(resource_to);
792 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\", not within the same phar archive", url_from, url_to);
793 		return 0;
794 	}
795 
796 	/* we must have at the very least phar://alias.phar/internalfile.php */
797 	if (!resource_from->scheme || !resource_from->host || !resource_from->path) {
798 		php_url_free(resource_from);
799 		php_url_free(resource_to);
800 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": invalid url \"%s\"", url_from, url_to, url_from);
801 		return 0;
802 	}
803 
804 	if (!resource_to->scheme || !resource_to->host || !resource_to->path) {
805 		php_url_free(resource_from);
806 		php_url_free(resource_to);
807 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": invalid url \"%s\"", url_from, url_to, url_to);
808 		return 0;
809 	}
810 
811 	if (!zend_string_equals_literal_ci(resource_from->scheme, "phar")) {
812 		php_url_free(resource_from);
813 		php_url_free(resource_to);
814 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": not a phar stream url \"%s\"", url_from, url_to, url_from);
815 		return 0;
816 	}
817 
818 	if (!zend_string_equals_literal_ci(resource_to->scheme, "phar")) {
819 		php_url_free(resource_from);
820 		php_url_free(resource_to);
821 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": not a phar stream url \"%s\"", url_from, url_to, url_to);
822 		return 0;
823 	}
824 
825 	host_len = ZSTR_LEN(resource_from->host);
826 
827 	if (SUCCESS != phar_get_archive(&phar, ZSTR_VAL(resource_from->host), host_len, NULL, 0, &error)) {
828 		php_url_free(resource_from);
829 		php_url_free(resource_to);
830 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": %s", url_from, url_to, error);
831 		efree(error);
832 		return 0;
833 	}
834 
835 	if (phar->is_persistent && FAILURE == phar_copy_on_write(&phar)) {
836 		php_url_free(resource_from);
837 		php_url_free(resource_to);
838 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": could not make cached phar writeable", url_from, url_to);
839 		return 0;
840 	}
841 
842 	if (NULL != (entry = zend_hash_str_find_ptr(&(phar->manifest), ZSTR_VAL(resource_from->path)+1, ZSTR_LEN(resource_from->path)-1))) {
843 		phar_entry_info new, *source;
844 
845 		/* perform rename magic */
846 		if (entry->is_deleted) {
847 			php_url_free(resource_from);
848 			php_url_free(resource_to);
849 			php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\" from extracted phar archive, source has been deleted", url_from, url_to);
850 			return 0;
851 		}
852 		/* transfer all data over to the new entry */
853 		memcpy((void *) &new, (void *) entry, sizeof(phar_entry_info));
854 		/* mark the old one for deletion */
855 		entry->is_deleted = 1;
856 		entry->fp = NULL;
857 		ZVAL_UNDEF(&entry->metadata_tracker.val);
858 		entry->link = entry->tmp = NULL;
859 		source = entry;
860 
861 		/* add to the manifest, and then store the pointer to the new guy in entry
862 		 * if it already exists, we overwrite the destination like what copy('phar://...', 'phar://...') does. */
863 		entry = zend_hash_str_update_mem(&(phar->manifest), ZSTR_VAL(resource_to->path)+1, ZSTR_LEN(resource_to->path)-1, (void **)&new, sizeof(phar_entry_info));
864 
865 		entry->filename = estrndup(ZSTR_VAL(resource_to->path)+1, ZSTR_LEN(resource_to->path)-1);
866 		if (FAILURE == phar_copy_entry_fp(source, entry, &error)) {
867 			php_url_free(resource_from);
868 			php_url_free(resource_to);
869 			php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": %s", url_from, url_to, error);
870 			efree(error);
871 			zend_hash_str_del(&(phar->manifest), entry->filename, strlen(entry->filename));
872 			return 0;
873 		}
874 		is_modified = 1;
875 		entry->is_modified = 1;
876 		entry->filename_len = strlen(entry->filename);
877 		is_dir = entry->is_dir;
878 	} else {
879 		is_dir = zend_hash_str_exists(&(phar->virtual_dirs), ZSTR_VAL(resource_from->path)+1, ZSTR_LEN(resource_from->path)-1);
880 		if (!is_dir) {
881 			/* file does not exist */
882 			php_url_free(resource_from);
883 			php_url_free(resource_to);
884 			php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\" from extracted phar archive, source does not exist", url_from, url_to);
885 			return 0;
886 
887 		}
888 	}
889 
890 	/* Rename directory. Update all nested paths */
891 	if (is_dir) {
892 		Bucket *b;
893 		zend_string *str_key;
894 		zend_string *new_str_key;
895 		uint32_t from_len = ZSTR_LEN(resource_from->path) - 1;
896 		uint32_t to_len = ZSTR_LEN(resource_to->path) - 1;
897 
898 		ZEND_HASH_MAP_FOREACH_BUCKET(&phar->manifest, b) {
899 			str_key = b->key;
900 			entry = Z_PTR(b->val);
901 			if (!entry->is_deleted &&
902 				ZSTR_LEN(str_key) > from_len &&
903 				memcmp(ZSTR_VAL(str_key), ZSTR_VAL(resource_from->path)+1, from_len) == 0 &&
904 				IS_SLASH(ZSTR_VAL(str_key)[from_len])) {
905 
906 				new_str_key = zend_string_alloc(ZSTR_LEN(str_key) + to_len - from_len, 0);
907 				memcpy(ZSTR_VAL(new_str_key), ZSTR_VAL(resource_to->path) + 1, to_len);
908 				memcpy(ZSTR_VAL(new_str_key) + to_len, ZSTR_VAL(str_key) + from_len, ZSTR_LEN(str_key) - from_len);
909 				ZSTR_VAL(new_str_key)[ZSTR_LEN(new_str_key)] = 0;
910 
911 				is_modified = 1;
912 				entry->is_modified = 1;
913 				efree(entry->filename);
914 				// TODO: avoid reallocation (make entry->filename zend_string*)
915 				entry->filename = estrndup(ZSTR_VAL(new_str_key), ZSTR_LEN(new_str_key));
916 				entry->filename_len = ZSTR_LEN(new_str_key);
917 
918 				zend_string_release_ex(str_key, 0);
919 				b->h = zend_string_hash_val(new_str_key);
920 				b->key = new_str_key;
921 			}
922 		} ZEND_HASH_FOREACH_END();
923 		zend_hash_rehash(&phar->manifest);
924 
925 		ZEND_HASH_MAP_FOREACH_BUCKET(&phar->virtual_dirs, b) {
926 			str_key = b->key;
927 			if (zend_string_starts_with_cstr(str_key, ZSTR_VAL(resource_from->path)+1, from_len) &&
928 				(ZSTR_LEN(str_key) == from_len || IS_SLASH(ZSTR_VAL(str_key)[from_len]))) {
929 
930 				new_str_key = zend_string_alloc(ZSTR_LEN(str_key) + to_len - from_len, 0);
931 				memcpy(ZSTR_VAL(new_str_key), ZSTR_VAL(resource_to->path) + 1, to_len);
932 				memcpy(ZSTR_VAL(new_str_key) + to_len, ZSTR_VAL(str_key) + from_len, ZSTR_LEN(str_key) - from_len);
933 				ZSTR_VAL(new_str_key)[ZSTR_LEN(new_str_key)] = 0;
934 
935 				zend_string_release_ex(str_key, 0);
936 				b->h = zend_string_hash_val(new_str_key);
937 				b->key = new_str_key;
938 			}
939 		} ZEND_HASH_FOREACH_END();
940 		zend_hash_rehash(&phar->virtual_dirs);
941 
942 		ZEND_HASH_MAP_FOREACH_BUCKET(&phar->mounted_dirs, b) {
943 			str_key = b->key;
944 			if (zend_string_starts_with_cstr(str_key, ZSTR_VAL(resource_from->path)+1, from_len) &&
945 				(ZSTR_LEN(str_key) == from_len || IS_SLASH(ZSTR_VAL(str_key)[from_len]))) {
946 
947 				new_str_key = zend_string_alloc(ZSTR_LEN(str_key) + to_len - from_len, 0);
948 				memcpy(ZSTR_VAL(new_str_key), ZSTR_VAL(resource_to->path) + 1, to_len);
949 				memcpy(ZSTR_VAL(new_str_key) + to_len, ZSTR_VAL(str_key) + from_len, ZSTR_LEN(str_key) - from_len);
950 				ZSTR_VAL(new_str_key)[ZSTR_LEN(new_str_key)] = 0;
951 
952 				zend_string_release_ex(str_key, 0);
953 				b->h = zend_string_hash_val(new_str_key);
954 				b->key = new_str_key;
955 			}
956 		} ZEND_HASH_FOREACH_END();
957 		zend_hash_rehash(&phar->mounted_dirs);
958 	}
959 
960 	if (is_modified) {
961 		phar_flush(phar, 0, 0, 0, &error);
962 		if (error) {
963 			php_url_free(resource_from);
964 			php_url_free(resource_to);
965 			php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": %s", url_from, url_to, error);
966 			efree(error);
967 			return 0;
968 		}
969 	}
970 
971 	php_url_free(resource_from);
972 	php_url_free(resource_to);
973 
974 	return 1;
975 }
976 /* }}} */
977