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