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