xref: /PHP-8.1/ext/phar/stream.c (revision 01b3fc03)
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 = zend_string_init("phar", 4, 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 				phar_entry_info *entry;
258 
259 				entry = (phar_entry_info *) ecalloc(1, sizeof(phar_entry_info));
260 				entry->is_temp_dir = 1;
261 				entry->filename = estrndup("", 0);
262 				entry->filename_len = 0;
263 				entry->phar = phar;
264 				entry->offset = entry->offset_abs = 0;
265 				entry->compressed_filesize = entry->uncompressed_filesize = phar->halt_offset;
266 				entry->is_crc_checked = 1;
267 
268 				idata = (phar_entry_data *) ecalloc(1, sizeof(phar_entry_data));
269 				idata->fp = phar_get_pharfp(phar);
270 				idata->phar = phar;
271 				idata->internal_file = entry;
272 				if (!phar->is_persistent) {
273 					++(entry->phar->refcount);
274 				}
275 				++(entry->fp_refcount);
276 				php_url_free(resource);
277 				if (opened_path) {
278 					*opened_path = strpprintf(MAXPATHLEN, "%s", phar->fname);
279 				}
280 				efree(internal_file);
281 				goto phar_stub;
282 			}
283 		}
284 		/* read-only access is allowed to magic files in .phar directory */
285 		if ((FAILURE == phar_get_entry_data(&idata, ZSTR_VAL(resource->host), host_len, internal_file, strlen(internal_file), "r", 0, &error, 0)) || !idata) {
286 idata_error:
287 			if (error) {
288 				php_stream_wrapper_log_error(wrapper, options, "%s", error);
289 				efree(error);
290 			} else {
291 				php_stream_wrapper_log_error(wrapper, options, "phar error: \"%s\" is not a file in phar \"%s\"", internal_file, ZSTR_VAL(resource->host));
292 			}
293 			efree(internal_file);
294 			php_url_free(resource);
295 			return NULL;
296 		}
297 	}
298 	php_url_free(resource);
299 #ifdef MBO_0
300 		fprintf(stderr, "Pharname:   %s\n", idata->phar->filename);
301 		fprintf(stderr, "Filename:   %s\n", internal_file);
302 		fprintf(stderr, "Entry:      %s\n", idata->internal_file->filename);
303 		fprintf(stderr, "Size:       %u\n", idata->internal_file->uncompressed_filesize);
304 		fprintf(stderr, "Compressed: %u\n", idata->internal_file->flags);
305 		fprintf(stderr, "Offset:     %u\n", idata->internal_file->offset_within_phar);
306 		fprintf(stderr, "Cached:     %s\n", idata->internal_file->filedata ? "yes" : "no");
307 #endif
308 
309 	/* check length, crc32 */
310 	if (!idata->internal_file->is_crc_checked && phar_postprocess_file(idata, idata->internal_file->crc32, &error, 2) != SUCCESS) {
311 		php_stream_wrapper_log_error(wrapper, options, "%s", error);
312 		efree(error);
313 		phar_entry_delref(idata);
314 		efree(internal_file);
315 		return NULL;
316 	}
317 
318 	if (!PHAR_G(cwd_init) && (options & STREAM_OPEN_FOR_INCLUDE)) {
319 		char *entry = idata->internal_file->filename, *cwd;
320 
321 		PHAR_G(cwd_init) = 1;
322 		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)) {
323 			/* we're executing the stub, which doesn't count as a file */
324 			PHAR_G(cwd_init) = 0;
325 		} else if ((cwd = strrchr(entry, '/'))) {
326 			PHAR_G(cwd_len) = cwd - entry;
327 			PHAR_G(cwd) = estrndup(entry, PHAR_G(cwd_len));
328 		} else {
329 			/* root directory */
330 			PHAR_G(cwd_len) = 0;
331 			PHAR_G(cwd) = NULL;
332 		}
333 	}
334 	if (opened_path) {
335 		*opened_path = strpprintf(MAXPATHLEN, "phar://%s/%s", idata->phar->fname, idata->internal_file->filename);
336 	}
337 	efree(internal_file);
338 phar_stub:
339 	fpf = php_stream_alloc(&phar_ops, idata, NULL, mode);
340 	return fpf;
341 }
342 /* }}} */
343 
344 /**
345  * Used for fclose($fp) where $fp is a phar archive
346  */
phar_stream_close(php_stream * stream,int close_handle)347 static int phar_stream_close(php_stream *stream, int close_handle) /* {{{ */
348 {
349 	/* for some reasons phar needs to be flushed even if there is no write going on */
350 	phar_stream_flush(stream);
351 
352 	phar_entry_delref((phar_entry_data *)stream->abstract);
353 
354 	return 0;
355 }
356 /* }}} */
357 
358 /**
359  * used for fread($fp) and company on a fopen()ed phar file handle
360  */
phar_stream_read(php_stream * stream,char * buf,size_t count)361 static ssize_t phar_stream_read(php_stream *stream, char *buf, size_t count) /* {{{ */
362 {
363 	phar_entry_data *data = (phar_entry_data *)stream->abstract;
364 	size_t got;
365 	phar_entry_info *entry;
366 
367 	if (data->internal_file->link) {
368 		entry = phar_get_link_source(data->internal_file);
369 	} else {
370 		entry = data->internal_file;
371 	}
372 
373 	if (entry->is_deleted) {
374 		stream->eof = 1;
375 		return -1;
376 	}
377 
378 	/* use our proxy position */
379 	php_stream_seek(data->fp, data->position + data->zero, SEEK_SET);
380 
381 	got = php_stream_read(data->fp, buf, MIN(count, (size_t)(entry->uncompressed_filesize - data->position)));
382 	data->position = php_stream_tell(data->fp) - data->zero;
383 	stream->eof = (data->position == (zend_off_t) entry->uncompressed_filesize);
384 
385 	return got;
386 }
387 /* }}} */
388 
389 /**
390  * Used for fseek($fp) on a phar file handle
391  */
phar_stream_seek(php_stream * stream,zend_off_t offset,int whence,zend_off_t * newoffset)392 static int phar_stream_seek(php_stream *stream, zend_off_t offset, int whence, zend_off_t *newoffset) /* {{{ */
393 {
394 	phar_entry_data *data = (phar_entry_data *)stream->abstract;
395 	phar_entry_info *entry;
396 	int res;
397 	zend_off_t temp;
398 
399 	if (data->internal_file->link) {
400 		entry = phar_get_link_source(data->internal_file);
401 	} else {
402 		entry = data->internal_file;
403 	}
404 
405 	switch (whence) {
406 		case SEEK_END :
407 			temp = data->zero + entry->uncompressed_filesize + offset;
408 			break;
409 		case SEEK_CUR :
410 			temp = data->zero + data->position + offset;
411 			break;
412 		case SEEK_SET :
413 			temp = data->zero + offset;
414 			break;
415 		default:
416 			temp = 0;
417 	}
418 	if (temp > data->zero + (zend_off_t) entry->uncompressed_filesize) {
419 		*newoffset = -1;
420 		return -1;
421 	}
422 	if (temp < data->zero) {
423 		*newoffset = -1;
424 		return -1;
425 	}
426 	res = php_stream_seek(data->fp, temp, SEEK_SET);
427 	*newoffset = php_stream_tell(data->fp) - data->zero;
428 	data->position = *newoffset;
429 	return res;
430 }
431 /* }}} */
432 
433 /**
434  * Used for writing to a phar file
435  */
phar_stream_write(php_stream * stream,const char * buf,size_t count)436 static ssize_t phar_stream_write(php_stream *stream, const char *buf, size_t count) /* {{{ */
437 {
438 	phar_entry_data *data = (phar_entry_data *) stream->abstract;
439 
440 	php_stream_seek(data->fp, data->position, SEEK_SET);
441 	if (count != php_stream_write(data->fp, buf, count)) {
442 		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);
443 		return -1;
444 	}
445 	data->position = php_stream_tell(data->fp);
446 	if (data->position > (zend_off_t)data->internal_file->uncompressed_filesize) {
447 		data->internal_file->uncompressed_filesize = data->position;
448 	}
449 	data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize;
450 	data->internal_file->old_flags = data->internal_file->flags;
451 	data->internal_file->is_modified = 1;
452 	return count;
453 }
454 /* }}} */
455 
456 /**
457  * Used to save work done on a writeable phar
458  */
phar_stream_flush(php_stream * stream)459 static int phar_stream_flush(php_stream *stream) /* {{{ */
460 {
461 	char *error;
462 	int ret;
463 	phar_entry_data *data = (phar_entry_data *) stream->abstract;
464 
465 	if (data->internal_file->is_modified) {
466 		data->internal_file->timestamp = time(0);
467 		ret = phar_flush(data->phar, 0, 0, 0, &error);
468 		if (error) {
469 			php_stream_wrapper_log_error(stream->wrapper, REPORT_ERRORS, "%s", error);
470 			efree(error);
471 		}
472 		return ret;
473 	} else {
474 		return EOF;
475 	}
476 }
477 /* }}} */
478 
479  /* {{{ phar_dostat */
480 /**
481  * stat an opened phar file handle stream, used by phar_stat()
482  */
phar_dostat(phar_archive_data * phar,phar_entry_info * data,php_stream_statbuf * ssb,bool is_temp_dir)483 void phar_dostat(phar_archive_data *phar, phar_entry_info *data, php_stream_statbuf *ssb, bool is_temp_dir)
484 {
485 	memset(ssb, 0, sizeof(php_stream_statbuf));
486 
487 	if (!is_temp_dir && !data->is_dir) {
488 		ssb->sb.st_size = data->uncompressed_filesize;
489 		ssb->sb.st_mode = data->flags & PHAR_ENT_PERM_MASK;
490 		ssb->sb.st_mode |= S_IFREG; /* regular file */
491 		/* timestamp is just the timestamp when this was added to the phar */
492 		ssb->sb.st_mtime = data->timestamp;
493 		ssb->sb.st_atime = data->timestamp;
494 		ssb->sb.st_ctime = data->timestamp;
495 	} else if (!is_temp_dir && data->is_dir) {
496 		ssb->sb.st_size = 0;
497 		ssb->sb.st_mode = data->flags & PHAR_ENT_PERM_MASK;
498 		ssb->sb.st_mode |= S_IFDIR; /* regular directory */
499 		/* timestamp is just the timestamp when this was added to the phar */
500 		ssb->sb.st_mtime = data->timestamp;
501 		ssb->sb.st_atime = data->timestamp;
502 		ssb->sb.st_ctime = data->timestamp;
503 	} else {
504 		ssb->sb.st_size = 0;
505 		ssb->sb.st_mode = 0777;
506 		ssb->sb.st_mode |= S_IFDIR; /* regular directory */
507 		ssb->sb.st_mtime = phar->max_timestamp;
508 		ssb->sb.st_atime = phar->max_timestamp;
509 		ssb->sb.st_ctime = phar->max_timestamp;
510 	}
511 	if (!phar->is_writeable) {
512 		ssb->sb.st_mode = (ssb->sb.st_mode & 0555) | (ssb->sb.st_mode & ~0777);
513 	}
514 
515 	ssb->sb.st_nlink = 1;
516 	ssb->sb.st_rdev = -1;
517 	/* this is only for APC, so use /dev/null device - no chance of conflict there! */
518 	ssb->sb.st_dev = 0xc;
519 	/* generate unique inode number for alias/filename, so no phars will conflict */
520 	if (!is_temp_dir) {
521 		ssb->sb.st_ino = data->inode;
522 	}
523 #ifndef PHP_WIN32
524 	ssb->sb.st_blksize = -1;
525 	ssb->sb.st_blocks = -1;
526 #endif
527 }
528 /* }}}*/
529 
530 /**
531  * Stat an opened phar file handle
532  */
phar_stream_stat(php_stream * stream,php_stream_statbuf * ssb)533 static int phar_stream_stat(php_stream *stream, php_stream_statbuf *ssb) /* {{{ */
534 {
535 	phar_entry_data *data = (phar_entry_data *)stream->abstract;
536 
537 	/* If ssb is NULL then someone is misbehaving */
538 	if (!ssb) {
539 		return -1;
540 	}
541 
542 	phar_dostat(data->phar, data->internal_file, ssb, 0);
543 	return 0;
544 }
545 /* }}} */
546 
547 /**
548  * Stream wrapper stat implementation of stat()
549  */
phar_wrapper_stat(php_stream_wrapper * wrapper,const char * url,int flags,php_stream_statbuf * ssb,php_stream_context * context)550 static int phar_wrapper_stat(php_stream_wrapper *wrapper, const char *url, int flags,
551 				  php_stream_statbuf *ssb, php_stream_context *context) /* {{{ */
552 {
553 	php_url *resource = NULL;
554 	char *internal_file, *error;
555 	phar_archive_data *phar;
556 	phar_entry_info *entry;
557 	uint32_t host_len;
558 	size_t internal_file_len;
559 
560 	if ((resource = phar_parse_url(wrapper, url, "r", flags|PHP_STREAM_URL_STAT_QUIET)) == NULL) {
561 		return FAILURE;
562 	}
563 
564 	/* we must have at the very least phar://alias.phar/internalfile.php */
565 	if (!resource->scheme || !resource->host || !resource->path) {
566 		php_url_free(resource);
567 		return FAILURE;
568 	}
569 
570 	if (!zend_string_equals_literal_ci(resource->scheme, "phar")) {
571 		php_url_free(resource);
572 		return FAILURE;
573 	}
574 
575 	host_len = ZSTR_LEN(resource->host);
576 	phar_request_initialize();
577 
578 	internal_file = ZSTR_VAL(resource->path) + 1; /* strip leading "/" */
579 	/* find the phar in our trusty global hash indexed by alias (host of phar://blah.phar/file.whatever) */
580 	if (FAILURE == phar_get_archive(&phar, ZSTR_VAL(resource->host), host_len, NULL, 0, &error)) {
581 		php_url_free(resource);
582 		if (error) {
583 			efree(error);
584 		}
585 		return FAILURE;
586 	}
587 	if (error) {
588 		efree(error);
589 	}
590 	if (*internal_file == '\0') {
591 		/* root directory requested */
592 		phar_dostat(phar, NULL, ssb, 1);
593 		php_url_free(resource);
594 		return SUCCESS;
595 	}
596 	if (!HT_IS_INITIALIZED(&phar->manifest)) {
597 		php_url_free(resource);
598 		return FAILURE;
599 	}
600 	internal_file_len = strlen(internal_file);
601 	/* search through the manifest of files, and if we have an exact match, it's a file */
602 	if (NULL != (entry = zend_hash_str_find_ptr(&phar->manifest, internal_file, internal_file_len))) {
603 		phar_dostat(phar, entry, ssb, 0);
604 		php_url_free(resource);
605 		return SUCCESS;
606 	}
607 	if (zend_hash_str_exists(&(phar->virtual_dirs), internal_file, internal_file_len)) {
608 		phar_dostat(phar, NULL, ssb, 1);
609 		php_url_free(resource);
610 		return SUCCESS;
611 	}
612 	/* check for mounted directories */
613 	if (HT_IS_INITIALIZED(&phar->mounted_dirs) && zend_hash_num_elements(&phar->mounted_dirs)) {
614 		zend_string *str_key;
615 
616 		ZEND_HASH_FOREACH_STR_KEY(&phar->mounted_dirs, str_key) {
617 			if (ZSTR_LEN(str_key) >= internal_file_len || strncmp(ZSTR_VAL(str_key), internal_file, ZSTR_LEN(str_key))) {
618 				continue;
619 			} else {
620 				char *test;
621 				size_t test_len;
622 				php_stream_statbuf ssbi;
623 
624 				if (NULL == (entry = zend_hash_find_ptr(&phar->manifest, str_key))) {
625 					goto free_resource;
626 				}
627 				if (!entry->tmp || !entry->is_mounted) {
628 					goto free_resource;
629 				}
630 				test_len = spprintf(&test, MAXPATHLEN, "%s%s", entry->tmp, internal_file + ZSTR_LEN(str_key));
631 				if (SUCCESS != php_stream_stat_path(test, &ssbi)) {
632 					efree(test);
633 					continue;
634 				}
635 				/* mount the file/directory just in time */
636 				if (SUCCESS != phar_mount_entry(phar, test, test_len, internal_file, internal_file_len)) {
637 					efree(test);
638 					goto free_resource;
639 				}
640 				efree(test);
641 				if (NULL == (entry = zend_hash_str_find_ptr(&phar->manifest, internal_file, internal_file_len))) {
642 					goto free_resource;
643 				}
644 				phar_dostat(phar, entry, ssb, 0);
645 				php_url_free(resource);
646 				return SUCCESS;
647 			}
648 		} ZEND_HASH_FOREACH_END();
649 	}
650 free_resource:
651 	php_url_free(resource);
652 	return FAILURE;
653 }
654 /* }}} */
655 
656 /**
657  * Unlink a file within a phar archive
658  */
phar_wrapper_unlink(php_stream_wrapper * wrapper,const char * url,int options,php_stream_context * context)659 static int phar_wrapper_unlink(php_stream_wrapper *wrapper, const char *url, int options, php_stream_context *context) /* {{{ */
660 {
661 	php_url *resource;
662 	char *internal_file, *error;
663 	int internal_file_len;
664 	phar_entry_data *idata;
665 	phar_archive_data *pphar;
666 	uint32_t host_len;
667 
668 	if ((resource = phar_parse_url(wrapper, url, "rb", options)) == NULL) {
669 		php_stream_wrapper_log_error(wrapper, options, "phar error: unlink failed");
670 		return 0;
671 	}
672 
673 	/* we must have at the very least phar://alias.phar/internalfile.php */
674 	if (!resource->scheme || !resource->host || !resource->path) {
675 		php_url_free(resource);
676 		php_stream_wrapper_log_error(wrapper, options, "phar error: invalid url \"%s\"", url);
677 		return 0;
678 	}
679 
680 	if (!zend_string_equals_literal_ci(resource->scheme, "phar")) {
681 		php_url_free(resource);
682 		php_stream_wrapper_log_error(wrapper, options, "phar error: not a phar stream url \"%s\"", url);
683 		return 0;
684 	}
685 
686 	host_len = ZSTR_LEN(resource->host);
687 	phar_request_initialize();
688 
689 	pphar = zend_hash_find_ptr(&(PHAR_G(phar_fname_map)), resource->host);
690 	if (PHAR_G(readonly) && (!pphar || !pphar->is_data)) {
691 		php_url_free(resource);
692 		php_stream_wrapper_log_error(wrapper, options, "phar error: write operations disabled by the php.ini setting phar.readonly");
693 		return 0;
694 	}
695 
696 	/* need to copy to strip leading "/", will get touched again */
697 	internal_file = estrndup(ZSTR_VAL(resource->path) + 1, ZSTR_LEN(resource->path) - 1);
698 	internal_file_len = ZSTR_LEN(resource->path) - 1;
699 	if (FAILURE == phar_get_entry_data(&idata, ZSTR_VAL(resource->host), host_len, internal_file, internal_file_len, "r", 0, &error, 1)) {
700 		/* constraints of fp refcount were not met */
701 		if (error) {
702 			php_stream_wrapper_log_error(wrapper, options, "unlink of \"%s\" failed: %s", url, error);
703 			efree(error);
704 		} else {
705 			php_stream_wrapper_log_error(wrapper, options, "unlink of \"%s\" failed, file does not exist", url);
706 		}
707 		efree(internal_file);
708 		php_url_free(resource);
709 		return 0;
710 	}
711 	if (error) {
712 		efree(error);
713 	}
714 	if (idata->internal_file->fp_refcount > 1) {
715 		/* more than just our fp resource is open for this file */
716 		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));
717 		efree(internal_file);
718 		php_url_free(resource);
719 		phar_entry_delref(idata);
720 		return 0;
721 	}
722 	php_url_free(resource);
723 	efree(internal_file);
724 	phar_entry_remove(idata, &error);
725 	if (error) {
726 		php_stream_wrapper_log_error(wrapper, options, "%s", error);
727 		efree(error);
728 	}
729 	return 1;
730 }
731 /* }}} */
732 
phar_wrapper_rename(php_stream_wrapper * wrapper,const char * url_from,const char * url_to,int options,php_stream_context * context)733 static int phar_wrapper_rename(php_stream_wrapper *wrapper, const char *url_from, const char *url_to, int options, php_stream_context *context) /* {{{ */
734 {
735 	php_url *resource_from, *resource_to;
736 	char *error;
737 	phar_archive_data *phar, *pfrom, *pto;
738 	phar_entry_info *entry;
739 	uint32_t host_len;
740 	int is_dir = 0;
741 	int is_modified = 0;
742 
743 	error = NULL;
744 
745 	if ((resource_from = phar_parse_url(wrapper, url_from, "wb", options|PHP_STREAM_URL_STAT_QUIET)) == NULL) {
746 		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);
747 		return 0;
748 	}
749 	if (SUCCESS != phar_get_archive(&pfrom, ZSTR_VAL(resource_from->host), ZSTR_LEN(resource_from->host), NULL, 0, &error)) {
750 		pfrom = NULL;
751 		if (error) {
752 			efree(error);
753 		}
754 	}
755 	if (PHAR_G(readonly) && (!pfrom || !pfrom->is_data)) {
756 		php_url_free(resource_from);
757 		php_error_docref(NULL, E_WARNING, "phar error: Write operations disabled by the php.ini setting phar.readonly");
758 		return 0;
759 	}
760 
761 	if ((resource_to = phar_parse_url(wrapper, url_to, "wb", options|PHP_STREAM_URL_STAT_QUIET)) == NULL) {
762 		php_url_free(resource_from);
763 		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);
764 		return 0;
765 	}
766 	if (SUCCESS != phar_get_archive(&pto, ZSTR_VAL(resource_to->host), ZSTR_LEN(resource_to->host), NULL, 0, &error)) {
767 		if (error) {
768 			efree(error);
769 		}
770 		pto = NULL;
771 	}
772 	if (PHAR_G(readonly) && (!pto || !pto->is_data)) {
773 		php_url_free(resource_from);
774 		php_error_docref(NULL, E_WARNING, "phar error: Write operations disabled by the php.ini setting phar.readonly");
775 		return 0;
776 	}
777 
778 	if (!zend_string_equals(resource_from->host, resource_to->host)) {
779 		php_url_free(resource_from);
780 		php_url_free(resource_to);
781 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\", not within the same phar archive", url_from, url_to);
782 		return 0;
783 	}
784 
785 	/* we must have at the very least phar://alias.phar/internalfile.php */
786 	if (!resource_from->scheme || !resource_from->host || !resource_from->path) {
787 		php_url_free(resource_from);
788 		php_url_free(resource_to);
789 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": invalid url \"%s\"", url_from, url_to, url_from);
790 		return 0;
791 	}
792 
793 	if (!resource_to->scheme || !resource_to->host || !resource_to->path) {
794 		php_url_free(resource_from);
795 		php_url_free(resource_to);
796 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": invalid url \"%s\"", url_from, url_to, url_to);
797 		return 0;
798 	}
799 
800 	if (!zend_string_equals_literal_ci(resource_from->scheme, "phar")) {
801 		php_url_free(resource_from);
802 		php_url_free(resource_to);
803 		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);
804 		return 0;
805 	}
806 
807 	if (!zend_string_equals_literal_ci(resource_to->scheme, "phar")) {
808 		php_url_free(resource_from);
809 		php_url_free(resource_to);
810 		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);
811 		return 0;
812 	}
813 
814 	host_len = ZSTR_LEN(resource_from->host);
815 
816 	if (SUCCESS != phar_get_archive(&phar, ZSTR_VAL(resource_from->host), host_len, NULL, 0, &error)) {
817 		php_url_free(resource_from);
818 		php_url_free(resource_to);
819 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": %s", url_from, url_to, error);
820 		efree(error);
821 		return 0;
822 	}
823 
824 	if (phar->is_persistent && FAILURE == phar_copy_on_write(&phar)) {
825 		php_url_free(resource_from);
826 		php_url_free(resource_to);
827 		php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": could not make cached phar writeable", url_from, url_to);
828 		return 0;
829 	}
830 
831 	if (NULL != (entry = zend_hash_str_find_ptr(&(phar->manifest), ZSTR_VAL(resource_from->path)+1, ZSTR_LEN(resource_from->path)-1))) {
832 		phar_entry_info new, *source;
833 
834 		/* perform rename magic */
835 		if (entry->is_deleted) {
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\" from extracted phar archive, source has been deleted", url_from, url_to);
839 			return 0;
840 		}
841 		/* transfer all data over to the new entry */
842 		memcpy((void *) &new, (void *) entry, sizeof(phar_entry_info));
843 		/* mark the old one for deletion */
844 		entry->is_deleted = 1;
845 		entry->fp = NULL;
846 		ZVAL_UNDEF(&entry->metadata_tracker.val);
847 		entry->link = entry->tmp = NULL;
848 		source = entry;
849 
850 		/* add to the manifest, and then store the pointer to the new guy in entry */
851 		entry = zend_hash_str_add_mem(&(phar->manifest), ZSTR_VAL(resource_to->path)+1, ZSTR_LEN(resource_to->path)-1, (void **)&new, sizeof(phar_entry_info));
852 
853 		entry->filename = estrndup(ZSTR_VAL(resource_to->path)+1, ZSTR_LEN(resource_to->path)-1);
854 		if (FAILURE == phar_copy_entry_fp(source, entry, &error)) {
855 			php_url_free(resource_from);
856 			php_url_free(resource_to);
857 			php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": %s", url_from, url_to, error);
858 			efree(error);
859 			zend_hash_str_del(&(phar->manifest), entry->filename, strlen(entry->filename));
860 			return 0;
861 		}
862 		is_modified = 1;
863 		entry->is_modified = 1;
864 		entry->filename_len = strlen(entry->filename);
865 		is_dir = entry->is_dir;
866 	} else {
867 		is_dir = zend_hash_str_exists(&(phar->virtual_dirs), ZSTR_VAL(resource_from->path)+1, ZSTR_LEN(resource_from->path)-1);
868 		if (!is_dir) {
869 			/* file does not exist */
870 			php_url_free(resource_from);
871 			php_url_free(resource_to);
872 			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);
873 			return 0;
874 
875 		}
876 	}
877 
878 	/* Rename directory. Update all nested paths */
879 	if (is_dir) {
880 		Bucket *b;
881 		zend_string *str_key;
882 		zend_string *new_str_key;
883 		uint32_t from_len = ZSTR_LEN(resource_from->path) - 1;
884 		uint32_t to_len = ZSTR_LEN(resource_to->path) - 1;
885 
886 		ZEND_HASH_FOREACH_BUCKET(&phar->manifest, b) {
887 			str_key = b->key;
888 			entry = Z_PTR(b->val);
889 			if (!entry->is_deleted &&
890 				ZSTR_LEN(str_key) > from_len &&
891 				memcmp(ZSTR_VAL(str_key), ZSTR_VAL(resource_from->path)+1, from_len) == 0 &&
892 				IS_SLASH(ZSTR_VAL(str_key)[from_len])) {
893 
894 				new_str_key = zend_string_alloc(ZSTR_LEN(str_key) + to_len - from_len, 0);
895 				memcpy(ZSTR_VAL(new_str_key), ZSTR_VAL(resource_to->path) + 1, to_len);
896 				memcpy(ZSTR_VAL(new_str_key) + to_len, ZSTR_VAL(str_key) + from_len, ZSTR_LEN(str_key) - from_len);
897 				ZSTR_VAL(new_str_key)[ZSTR_LEN(new_str_key)] = 0;
898 
899 				is_modified = 1;
900 				entry->is_modified = 1;
901 				efree(entry->filename);
902 				// TODO: avoid reallocation (make entry->filename zend_string*)
903 				entry->filename = estrndup(ZSTR_VAL(new_str_key), ZSTR_LEN(new_str_key));
904 				entry->filename_len = ZSTR_LEN(new_str_key);
905 
906 				zend_string_release_ex(str_key, 0);
907 				b->h = zend_string_hash_val(new_str_key);
908 				b->key = new_str_key;
909 			}
910 		} ZEND_HASH_FOREACH_END();
911 		zend_hash_rehash(&phar->manifest);
912 
913 		ZEND_HASH_FOREACH_BUCKET(&phar->virtual_dirs, b) {
914 			str_key = b->key;
915 			if (ZSTR_LEN(str_key) >= from_len &&
916 				memcmp(ZSTR_VAL(str_key), ZSTR_VAL(resource_from->path)+1, from_len) == 0 &&
917 				(ZSTR_LEN(str_key) == from_len || IS_SLASH(ZSTR_VAL(str_key)[from_len]))) {
918 
919 				new_str_key = zend_string_alloc(ZSTR_LEN(str_key) + to_len - from_len, 0);
920 				memcpy(ZSTR_VAL(new_str_key), ZSTR_VAL(resource_to->path) + 1, to_len);
921 				memcpy(ZSTR_VAL(new_str_key) + to_len, ZSTR_VAL(str_key) + from_len, ZSTR_LEN(str_key) - from_len);
922 				ZSTR_VAL(new_str_key)[ZSTR_LEN(new_str_key)] = 0;
923 
924 				zend_string_release_ex(str_key, 0);
925 				b->h = zend_string_hash_val(new_str_key);
926 				b->key = new_str_key;
927 			}
928 		} ZEND_HASH_FOREACH_END();
929 		zend_hash_rehash(&phar->virtual_dirs);
930 
931 		ZEND_HASH_FOREACH_BUCKET(&phar->mounted_dirs, b) {
932 			str_key = b->key;
933 			if (ZSTR_LEN(str_key) >= from_len &&
934 				memcmp(ZSTR_VAL(str_key), ZSTR_VAL(resource_from->path)+1, from_len) == 0 &&
935 				(ZSTR_LEN(str_key) == from_len || IS_SLASH(ZSTR_VAL(str_key)[from_len]))) {
936 
937 				new_str_key = zend_string_alloc(ZSTR_LEN(str_key) + to_len - from_len, 0);
938 				memcpy(ZSTR_VAL(new_str_key), ZSTR_VAL(resource_to->path) + 1, to_len);
939 				memcpy(ZSTR_VAL(new_str_key) + to_len, ZSTR_VAL(str_key) + from_len, ZSTR_LEN(str_key) - from_len);
940 				ZSTR_VAL(new_str_key)[ZSTR_LEN(new_str_key)] = 0;
941 
942 				zend_string_release_ex(str_key, 0);
943 				b->h = zend_string_hash_val(new_str_key);
944 				b->key = new_str_key;
945 			}
946 		} ZEND_HASH_FOREACH_END();
947 		zend_hash_rehash(&phar->mounted_dirs);
948 	}
949 
950 	if (is_modified) {
951 		phar_flush(phar, 0, 0, 0, &error);
952 		if (error) {
953 			php_url_free(resource_from);
954 			php_url_free(resource_to);
955 			php_error_docref(NULL, E_WARNING, "phar error: cannot rename \"%s\" to \"%s\": %s", url_from, url_to, error);
956 			efree(error);
957 			return 0;
958 		}
959 	}
960 
961 	php_url_free(resource_from);
962 	php_url_free(resource_to);
963 
964 	return 1;
965 }
966 /* }}} */
967