xref: /PHP-8.0/main/streams/streams.c (revision d0b3096f)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | http://www.php.net/license/3_01.txt                                  |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Authors: Wez Furlong <wez@thebrainroom.com>                          |
14    | Borrowed code from:                                                  |
15    |          Rasmus Lerdorf <rasmus@lerdorf.on.ca>                       |
16    |          Jim Winstead <jimw@php.net>                                 |
17    +----------------------------------------------------------------------+
18  */
19 
20 #define _GNU_SOURCE
21 #include "php.h"
22 #include "php_globals.h"
23 #include "php_memory_streams.h"
24 #include "php_network.h"
25 #include "php_open_temporary_file.h"
26 #include "ext/standard/file.h"
27 #include "ext/standard/basic_functions.h" /* for BG(CurrentStatFile) */
28 #include "ext/standard/php_string.h" /* for php_memnstr, used by php_stream_get_record() */
29 #include <stddef.h>
30 #include <fcntl.h>
31 #include "php_streams_int.h"
32 
33 /* {{{ resource and registration code */
34 /* Global wrapper hash, copied to FG(stream_wrappers) on registration of volatile wrapper */
35 static HashTable url_stream_wrappers_hash;
36 static int le_stream = FAILURE; /* true global */
37 static int le_pstream = FAILURE; /* true global */
38 static int le_stream_filter = FAILURE; /* true global */
39 
php_file_le_stream(void)40 PHPAPI int php_file_le_stream(void)
41 {
42 	return le_stream;
43 }
44 
php_file_le_pstream(void)45 PHPAPI int php_file_le_pstream(void)
46 {
47 	return le_pstream;
48 }
49 
php_file_le_stream_filter(void)50 PHPAPI int php_file_le_stream_filter(void)
51 {
52 	return le_stream_filter;
53 }
54 
_php_stream_get_url_stream_wrappers_hash(void)55 PHPAPI HashTable *_php_stream_get_url_stream_wrappers_hash(void)
56 {
57 	return (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash);
58 }
59 
php_stream_get_url_stream_wrappers_hash_global(void)60 PHPAPI HashTable *php_stream_get_url_stream_wrappers_hash_global(void)
61 {
62 	return &url_stream_wrappers_hash;
63 }
64 
forget_persistent_resource_id_numbers(zval * el)65 static int forget_persistent_resource_id_numbers(zval *el)
66 {
67 	php_stream *stream;
68 	zend_resource *rsrc = Z_RES_P(el);
69 
70 	if (rsrc->type != le_pstream) {
71 		return 0;
72 	}
73 
74 	stream = (php_stream*)rsrc->ptr;
75 
76 #if STREAM_DEBUG
77 fprintf(stderr, "forget_persistent: %s:%p\n", stream->ops->label, stream);
78 #endif
79 
80 	stream->res = NULL;
81 
82 	if (stream->ctx) {
83 		zend_list_delete(stream->ctx);
84 		stream->ctx = NULL;
85 	}
86 
87 	return 0;
88 }
89 
PHP_RSHUTDOWN_FUNCTION(streams)90 PHP_RSHUTDOWN_FUNCTION(streams)
91 {
92 	zval *el;
93 
94 	ZEND_HASH_FOREACH_VAL(&EG(persistent_list), el) {
95 		forget_persistent_resource_id_numbers(el);
96 	} ZEND_HASH_FOREACH_END();
97 	return SUCCESS;
98 }
99 
php_stream_encloses(php_stream * enclosing,php_stream * enclosed)100 PHPAPI php_stream *php_stream_encloses(php_stream *enclosing, php_stream *enclosed)
101 {
102 	php_stream *orig = enclosed->enclosing_stream;
103 
104 	php_stream_auto_cleanup(enclosed);
105 	enclosed->enclosing_stream = enclosing;
106 	return orig;
107 }
108 
php_stream_from_persistent_id(const char * persistent_id,php_stream ** stream)109 PHPAPI int php_stream_from_persistent_id(const char *persistent_id, php_stream **stream)
110 {
111 	zend_resource *le;
112 
113 	if ((le = zend_hash_str_find_ptr(&EG(persistent_list), persistent_id, strlen(persistent_id))) != NULL) {
114 		if (le->type == le_pstream) {
115 			if (stream) {
116 				zend_resource *regentry = NULL;
117 
118 				/* see if this persistent resource already has been loaded to the
119 				 * regular list; allowing the same resource in several entries in the
120 				 * regular list causes trouble (see bug #54623) */
121 				*stream = (php_stream*)le->ptr;
122 				ZEND_HASH_FOREACH_PTR(&EG(regular_list), regentry) {
123 					if (regentry->ptr == le->ptr) {
124 						GC_ADDREF(regentry);
125 						(*stream)->res = regentry;
126 						return PHP_STREAM_PERSISTENT_SUCCESS;
127 					}
128 				} ZEND_HASH_FOREACH_END();
129 				GC_ADDREF(le);
130 				(*stream)->res = zend_register_resource(*stream, le_pstream);
131 			}
132 			return PHP_STREAM_PERSISTENT_SUCCESS;
133 		}
134 		return PHP_STREAM_PERSISTENT_FAILURE;
135 	}
136 	return PHP_STREAM_PERSISTENT_NOT_EXIST;
137 }
138 
139 /* }}} */
140 
php_get_wrapper_errors_list(php_stream_wrapper * wrapper)141 static zend_llist *php_get_wrapper_errors_list(php_stream_wrapper *wrapper)
142 {
143     if (!FG(wrapper_errors)) {
144         return NULL;
145     } else {
146         return (zend_llist*) zend_hash_str_find_ptr(FG(wrapper_errors), (const char*)&wrapper, sizeof(wrapper));
147     }
148 }
149 
150 /* {{{ wrapper error reporting */
php_stream_display_wrapper_errors(php_stream_wrapper * wrapper,const char * path,const char * caption)151 void php_stream_display_wrapper_errors(php_stream_wrapper *wrapper, const char *path, const char *caption)
152 {
153 	char *tmp;
154 	char *msg;
155 	int free_msg = 0;
156 
157 	if (EG(exception)) {
158 		/* Don't emit additional warnings if an exception has already been thrown. */
159 		return;
160 	}
161 
162 	tmp = estrdup(path);
163 	if (wrapper) {
164 		zend_llist *err_list = php_get_wrapper_errors_list(wrapper);
165 		if (err_list) {
166 			size_t l = 0;
167 			int brlen;
168 			int i;
169 			int count = (int)zend_llist_count(err_list);
170 			const char *br;
171 			const char **err_buf_p;
172 			zend_llist_position pos;
173 
174 			if (PG(html_errors)) {
175 				brlen = 7;
176 				br = "<br />\n";
177 			} else {
178 				brlen = 1;
179 				br = "\n";
180 			}
181 
182 			for (err_buf_p = zend_llist_get_first_ex(err_list, &pos), i = 0;
183 					err_buf_p;
184 					err_buf_p = zend_llist_get_next_ex(err_list, &pos), i++) {
185 				l += strlen(*err_buf_p);
186 				if (i < count - 1) {
187 					l += brlen;
188 				}
189 			}
190 			msg = emalloc(l + 1);
191 			msg[0] = '\0';
192 			for (err_buf_p = zend_llist_get_first_ex(err_list, &pos), i = 0;
193 					err_buf_p;
194 					err_buf_p = zend_llist_get_next_ex(err_list, &pos), i++) {
195 				strcat(msg, *err_buf_p);
196 				if (i < count - 1) {
197 					strcat(msg, br);
198 				}
199 			}
200 
201 			free_msg = 1;
202 		} else {
203 			if (wrapper == &php_plain_files_wrapper) {
204 				msg = strerror(errno); /* TODO: not ts on linux */
205 			} else {
206 				msg = "operation failed";
207 			}
208 		}
209 	} else {
210 		msg = "no suitable wrapper could be found";
211 	}
212 
213 	php_strip_url_passwd(tmp);
214 	php_error_docref1(NULL, tmp, E_WARNING, "%s: %s", caption, msg);
215 	efree(tmp);
216 	if (free_msg) {
217 		efree(msg);
218 	}
219 }
220 
php_stream_tidy_wrapper_error_log(php_stream_wrapper * wrapper)221 void php_stream_tidy_wrapper_error_log(php_stream_wrapper *wrapper)
222 {
223 	if (wrapper && FG(wrapper_errors)) {
224 		zend_hash_str_del(FG(wrapper_errors), (const char*)&wrapper, sizeof(wrapper));
225 	}
226 }
227 
wrapper_error_dtor(void * error)228 static void wrapper_error_dtor(void *error)
229 {
230 	efree(*(char**)error);
231 }
232 
wrapper_list_dtor(zval * item)233 static void wrapper_list_dtor(zval *item) {
234 	zend_llist *list = (zend_llist*)Z_PTR_P(item);
235 	zend_llist_destroy(list);
236 	efree(list);
237 }
238 
php_stream_wrapper_log_error(const php_stream_wrapper * wrapper,int options,const char * fmt,...)239 PHPAPI void php_stream_wrapper_log_error(const php_stream_wrapper *wrapper, int options, const char *fmt, ...)
240 {
241 	va_list args;
242 	char *buffer = NULL;
243 
244 	va_start(args, fmt);
245 	vspprintf(&buffer, 0, fmt, args);
246 	va_end(args);
247 
248 	if ((options & REPORT_ERRORS) || wrapper == NULL) {
249 		php_error_docref(NULL, E_WARNING, "%s", buffer);
250 		efree(buffer);
251 	} else {
252 		zend_llist *list = NULL;
253 		if (!FG(wrapper_errors)) {
254 			ALLOC_HASHTABLE(FG(wrapper_errors));
255 			zend_hash_init(FG(wrapper_errors), 8, NULL, wrapper_list_dtor, 0);
256 		} else {
257 			list = zend_hash_str_find_ptr(FG(wrapper_errors), (const char*)&wrapper, sizeof(wrapper));
258 		}
259 
260 		if (!list) {
261 			zend_llist new_list;
262 			zend_llist_init(&new_list, sizeof(buffer), wrapper_error_dtor, 0);
263 			list = zend_hash_str_update_mem(FG(wrapper_errors), (const char*)&wrapper,
264 					sizeof(wrapper), &new_list, sizeof(new_list));
265 		}
266 
267 		/* append to linked list */
268 		zend_llist_add_element(list, &buffer);
269 	}
270 }
271 
272 
273 /* }}} */
274 
275 /* allocate a new stream for a particular ops */
_php_stream_alloc(const php_stream_ops * ops,void * abstract,const char * persistent_id,const char * mode STREAMS_DC)276 PHPAPI php_stream *_php_stream_alloc(const php_stream_ops *ops, void *abstract, const char *persistent_id, const char *mode STREAMS_DC) /* {{{ */
277 {
278 	php_stream *ret;
279 
280 	ret = (php_stream*) pemalloc_rel_orig(sizeof(php_stream), persistent_id ? 1 : 0);
281 
282 	memset(ret, 0, sizeof(php_stream));
283 
284 	ret->readfilters.stream = ret;
285 	ret->writefilters.stream = ret;
286 
287 #if STREAM_DEBUG
288 fprintf(stderr, "stream_alloc: %s:%p persistent=%s\n", ops->label, ret, persistent_id);
289 #endif
290 
291 	ret->ops = ops;
292 	ret->abstract = abstract;
293 	ret->is_persistent = persistent_id ? 1 : 0;
294 	ret->chunk_size = FG(def_chunk_size);
295 
296 #if ZEND_DEBUG
297 	ret->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename;
298 	ret->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno;
299 #endif
300 
301 	if (FG(auto_detect_line_endings)) {
302 		ret->flags |= PHP_STREAM_FLAG_DETECT_EOL;
303 	}
304 
305 	if (persistent_id) {
306 		if (NULL == zend_register_persistent_resource(persistent_id, strlen(persistent_id), ret, le_pstream)) {
307 			pefree(ret, 1);
308 			return NULL;
309 		}
310 	}
311 
312 	ret->res = zend_register_resource(ret, persistent_id ? le_pstream : le_stream);
313 	strlcpy(ret->mode, mode, sizeof(ret->mode));
314 
315 	ret->wrapper          = NULL;
316 	ret->wrapperthis      = NULL;
317 	ZVAL_UNDEF(&ret->wrapperdata);
318 	ret->stdiocast        = NULL;
319 	ret->orig_path        = NULL;
320 	ret->ctx              = NULL;
321 	ret->readbuf          = NULL;
322 	ret->enclosing_stream = NULL;
323 
324 	return ret;
325 }
326 /* }}} */
327 
_php_stream_free_enclosed(php_stream * stream_enclosed,int close_options)328 PHPAPI int _php_stream_free_enclosed(php_stream *stream_enclosed, int close_options) /* {{{ */
329 {
330 	return php_stream_free(stream_enclosed,
331 		close_options | PHP_STREAM_FREE_IGNORE_ENCLOSING);
332 }
333 /* }}} */
334 
335 #if STREAM_DEBUG
_php_stream_pretty_free_options(int close_options,char * out)336 static const char *_php_stream_pretty_free_options(int close_options, char *out)
337 {
338 	if (close_options & PHP_STREAM_FREE_CALL_DTOR)
339 		strcat(out, "CALL_DTOR, ");
340 	if (close_options & PHP_STREAM_FREE_RELEASE_STREAM)
341 		strcat(out, "RELEASE_STREAM, ");
342 	if (close_options & PHP_STREAM_FREE_PRESERVE_HANDLE)
343 		strcat(out, "PREVERSE_HANDLE, ");
344 	if (close_options & PHP_STREAM_FREE_RSRC_DTOR)
345 		strcat(out, "RSRC_DTOR, ");
346 	if (close_options & PHP_STREAM_FREE_PERSISTENT)
347 		strcat(out, "PERSISTENT, ");
348 	if (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING)
349 		strcat(out, "IGNORE_ENCLOSING, ");
350 	if (out[0] != '\0')
351 		out[strlen(out) - 2] = '\0';
352 	return out;
353 }
354 #endif
355 
_php_stream_free_persistent(zval * zv,void * pStream)356 static int _php_stream_free_persistent(zval *zv, void *pStream)
357 {
358 	zend_resource *le = Z_RES_P(zv);
359 	return le->ptr == pStream;
360 }
361 
362 
_php_stream_free(php_stream * stream,int close_options)363 PHPAPI int _php_stream_free(php_stream *stream, int close_options) /* {{{ */
364 {
365 	int ret = 1;
366 	int preserve_handle = close_options & PHP_STREAM_FREE_PRESERVE_HANDLE ? 1 : 0;
367 	int release_cast = 1;
368 	php_stream_context *context;
369 
370 	/* During shutdown resources may be released before other resources still holding them.
371 	 * When only resoruces are referenced this is not a problem, because they are refcounted
372 	 * and will only be fully freed once the refcount drops to zero. However, if php_stream*
373 	 * is held directly, we don't have this guarantee. To avoid use-after-free we ignore all
374 	 * stream free operations in shutdown unless they come from the resource list destruction,
375 	 * or by freeing an enclosed stream (in which case resource list destruction will not have
376 	 * freed it). */
377 	if ((EG(flags) & EG_FLAGS_IN_RESOURCE_SHUTDOWN) &&
378 			!(close_options & (PHP_STREAM_FREE_RSRC_DTOR|PHP_STREAM_FREE_IGNORE_ENCLOSING))) {
379 		return 1;
380 	}
381 
382 	context = PHP_STREAM_CONTEXT(stream);
383 
384 	if (stream->flags & PHP_STREAM_FLAG_NO_CLOSE) {
385 		preserve_handle = 1;
386 	}
387 
388 #if STREAM_DEBUG
389 	{
390 		char out[200] = "";
391 		fprintf(stderr, "stream_free: %s:%p[%s] in_free=%d opts=%s\n",
392 			stream->ops->label, stream, stream->orig_path, stream->in_free, _php_stream_pretty_free_options(close_options, out));
393 	}
394 
395 #endif
396 
397 	if (stream->in_free) {
398 		/* hopefully called recursively from the enclosing stream; the pointer was NULLed below */
399 		if ((stream->in_free == 1) && (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) && (stream->enclosing_stream == NULL)) {
400 			close_options |= PHP_STREAM_FREE_RSRC_DTOR; /* restore flag */
401 		} else {
402 			return 1; /* recursion protection */
403 		}
404 	}
405 
406 	stream->in_free++;
407 
408 	/* force correct order on enclosing/enclosed stream destruction (only from resource
409 	 * destructor as in when reverse destroying the resource list) */
410 	if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) &&
411 			!(close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) &&
412 			(close_options & (PHP_STREAM_FREE_CALL_DTOR | PHP_STREAM_FREE_RELEASE_STREAM)) && /* always? */
413 			(stream->enclosing_stream != NULL)) {
414 		php_stream *enclosing_stream = stream->enclosing_stream;
415 		stream->enclosing_stream = NULL;
416 		/* we force PHP_STREAM_CALL_DTOR because that's from where the
417 		 * enclosing stream can free this stream. */
418 		return php_stream_free(enclosing_stream,
419 			(close_options | PHP_STREAM_FREE_CALL_DTOR | PHP_STREAM_FREE_KEEP_RSRC) & ~PHP_STREAM_FREE_RSRC_DTOR);
420 	}
421 
422 	/* if we are releasing the stream only (and preserving the underlying handle),
423 	 * we need to do things a little differently.
424 	 * We are only ever called like this when the stream is cast to a FILE*
425 	 * for include (or other similar) purposes.
426 	 * */
427 	if (preserve_handle) {
428 		if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) {
429 			/* If the stream was fopencookied, we must NOT touch anything
430 			 * here, as the cookied stream relies on it all.
431 			 * Instead, mark the stream as OK to auto-clean */
432 			php_stream_auto_cleanup(stream);
433 			stream->in_free--;
434 			return 0;
435 		}
436 		/* otherwise, make sure that we don't close the FILE* from a cast */
437 		release_cast = 0;
438 	}
439 
440 #if STREAM_DEBUG
441 fprintf(stderr, "stream_free: %s:%p[%s] preserve_handle=%d release_cast=%d remove_rsrc=%d\n",
442 		stream->ops->label, stream, stream->orig_path, preserve_handle, release_cast,
443 		(close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0);
444 #endif
445 
446 	if (stream->flags & PHP_STREAM_FLAG_WAS_WRITTEN || stream->writefilters.head) {
447 		/* make sure everything is saved */
448 		_php_stream_flush(stream, 1);
449 	}
450 
451 	/* If not called from the resource dtor, remove the stream from the resource list. */
452 	if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0 && stream->res) {
453 		/* Close resource, but keep it in resource list */
454 		zend_list_close(stream->res);
455 		if ((close_options & PHP_STREAM_FREE_KEEP_RSRC) == 0) {
456 			/* Completely delete zend_resource, if not referenced */
457 			zend_list_delete(stream->res);
458 			stream->res = NULL;
459 		}
460 	}
461 
462 	if (close_options & PHP_STREAM_FREE_CALL_DTOR) {
463 		if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) {
464 			/* calling fclose on an fopencookied stream will ultimately
465 				call this very same function.  If we were called via fclose,
466 				the cookie_closer unsets the fclose_stdiocast flags, so
467 				we can be sure that we only reach here when PHP code calls
468 				php_stream_free.
469 				Lets let the cookie code clean it all up.
470 			 */
471 			stream->in_free = 0;
472 			return fclose(stream->stdiocast);
473 		}
474 
475 		ret = stream->ops->close(stream, preserve_handle ? 0 : 1);
476 		stream->abstract = NULL;
477 
478 		/* tidy up any FILE* that might have been fdopened */
479 		if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FDOPEN && stream->stdiocast) {
480 			fclose(stream->stdiocast);
481 			stream->stdiocast = NULL;
482 			stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE;
483 		}
484 	}
485 
486 	if (close_options & PHP_STREAM_FREE_RELEASE_STREAM) {
487 		while (stream->readfilters.head) {
488 			if (stream->readfilters.head->res != NULL) {
489 				zend_list_close(stream->readfilters.head->res);
490 			}
491 			php_stream_filter_remove(stream->readfilters.head, 1);
492 		}
493 		while (stream->writefilters.head) {
494 			if (stream->writefilters.head->res != NULL) {
495 				zend_list_close(stream->writefilters.head->res);
496 			}
497 			php_stream_filter_remove(stream->writefilters.head, 1);
498 		}
499 
500 		if (stream->wrapper && stream->wrapper->wops && stream->wrapper->wops->stream_closer) {
501 			stream->wrapper->wops->stream_closer(stream->wrapper, stream);
502 			stream->wrapper = NULL;
503 		}
504 
505 		if (Z_TYPE(stream->wrapperdata) != IS_UNDEF) {
506 			zval_ptr_dtor(&stream->wrapperdata);
507 			ZVAL_UNDEF(&stream->wrapperdata);
508 		}
509 
510 		if (stream->readbuf) {
511 			pefree(stream->readbuf, stream->is_persistent);
512 			stream->readbuf = NULL;
513 		}
514 
515 		if (stream->is_persistent && (close_options & PHP_STREAM_FREE_PERSISTENT)) {
516 			/* we don't work with *stream but need its value for comparison */
517 			zend_hash_apply_with_argument(&EG(persistent_list), _php_stream_free_persistent, stream);
518 		}
519 
520 		if (stream->orig_path) {
521 			pefree(stream->orig_path, stream->is_persistent);
522 			stream->orig_path = NULL;
523 		}
524 
525 		pefree(stream, stream->is_persistent);
526 	}
527 
528 	if (context) {
529 		zend_list_delete(context->res);
530 	}
531 
532 	return ret;
533 }
534 /* }}} */
535 
536 /* {{{ generic stream operations */
537 
_php_stream_fill_read_buffer(php_stream * stream,size_t size)538 PHPAPI int _php_stream_fill_read_buffer(php_stream *stream, size_t size)
539 {
540 	/* allocate/fill the buffer */
541 
542 	if (stream->readfilters.head) {
543 		size_t to_read_now = MIN(size, stream->chunk_size);
544 		char *chunk_buf;
545 		php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL };
546 		php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap;
547 
548 		/* allocate a buffer for reading chunks */
549 		chunk_buf = emalloc(stream->chunk_size);
550 
551 		while (!stream->eof && (stream->writepos - stream->readpos < (zend_off_t)to_read_now)) {
552 			ssize_t justread = 0;
553 			int flags;
554 			php_stream_bucket *bucket;
555 			php_stream_filter_status_t status = PSFS_ERR_FATAL;
556 			php_stream_filter *filter;
557 
558 			/* read a chunk into a bucket */
559 			justread = stream->ops->read(stream, chunk_buf, stream->chunk_size);
560 			if (justread < 0 && stream->writepos == stream->readpos) {
561 				efree(chunk_buf);
562 				return FAILURE;
563 			} else if (justread > 0) {
564 				bucket = php_stream_bucket_new(stream, chunk_buf, justread, 0, 0);
565 
566 				/* after this call, bucket is owned by the brigade */
567 				php_stream_bucket_append(brig_inp, bucket);
568 
569 				flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_NORMAL;
570 			} else {
571 				flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC;
572 			}
573 
574 			/* wind the handle... */
575 			for (filter = stream->readfilters.head; filter; filter = filter->next) {
576 				status = filter->fops->filter(stream, filter, brig_inp, brig_outp, NULL, flags);
577 
578 				if (status != PSFS_PASS_ON) {
579 					break;
580 				}
581 
582 				/* brig_out becomes brig_in.
583 				 * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets
584 				 * to its own brigade */
585 				brig_swap = brig_inp;
586 				brig_inp = brig_outp;
587 				brig_outp = brig_swap;
588 				memset(brig_outp, 0, sizeof(*brig_outp));
589 			}
590 
591 			switch (status) {
592 				case PSFS_PASS_ON:
593 					/* we get here when the last filter in the chain has data to pass on.
594 					 * in this situation, we are passing the brig_in brigade into the
595 					 * stream read buffer */
596 					while (brig_inp->head) {
597 						bucket = brig_inp->head;
598 						/* reduce buffer memory consumption if possible, to avoid a realloc */
599 						if (stream->readbuf && stream->readbuflen - stream->writepos < bucket->buflen) {
600 							if (stream->writepos > stream->readpos) {
601 								memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->writepos - stream->readpos);
602 							}
603 							stream->writepos -= stream->readpos;
604 							stream->readpos = 0;
605 						}
606 						/* grow buffer to hold this bucket */
607 						if (stream->readbuflen - stream->writepos < bucket->buflen) {
608 							stream->readbuflen += bucket->buflen;
609 							stream->readbuf = perealloc(stream->readbuf, stream->readbuflen,
610 									stream->is_persistent);
611 						}
612 						if (bucket->buflen) {
613 							memcpy(stream->readbuf + stream->writepos, bucket->buf, bucket->buflen);
614 						}
615 						stream->writepos += bucket->buflen;
616 
617 						php_stream_bucket_unlink(bucket);
618 						php_stream_bucket_delref(bucket);
619 					}
620 					break;
621 
622 				case PSFS_FEED_ME:
623 					/* when a filter needs feeding, there is no brig_out to deal with.
624 					 * we simply continue the loop; if the caller needs more data,
625 					 * we will read again, otherwise out job is done here */
626 					break;
627 
628 				case PSFS_ERR_FATAL:
629 					/* some fatal error. Theoretically, the stream is borked, so all
630 					 * further reads should fail. */
631 					stream->eof = 1;
632 					efree(chunk_buf);
633 					return FAILURE;
634 			}
635 
636 			if (justread <= 0) {
637 				break;
638 			}
639 		}
640 
641 		efree(chunk_buf);
642 		return SUCCESS;
643 
644 	} else {
645 		/* is there enough data in the buffer ? */
646 		if (stream->writepos - stream->readpos < (zend_off_t)size) {
647 			ssize_t justread = 0;
648 
649 			/* reduce buffer memory consumption if possible, to avoid a realloc */
650 			if (stream->readbuf && stream->readbuflen - stream->writepos < stream->chunk_size) {
651 				if (stream->writepos > stream->readpos) {
652 					memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->writepos - stream->readpos);
653 				}
654 				stream->writepos -= stream->readpos;
655 				stream->readpos = 0;
656 			}
657 
658 			/* grow the buffer if required
659 			 * TODO: this can fail for persistent streams */
660 			if (stream->readbuflen - stream->writepos < stream->chunk_size) {
661 				stream->readbuflen += stream->chunk_size;
662 				stream->readbuf = perealloc(stream->readbuf, stream->readbuflen,
663 						stream->is_persistent);
664 			}
665 
666 			justread = stream->ops->read(stream, (char*)stream->readbuf + stream->writepos,
667 					stream->readbuflen - stream->writepos
668 					);
669 			if (justread < 0) {
670 				return FAILURE;
671 			}
672 			stream->writepos += justread;
673 		}
674 		return SUCCESS;
675 	}
676 }
677 
_php_stream_read(php_stream * stream,char * buf,size_t size)678 PHPAPI ssize_t _php_stream_read(php_stream *stream, char *buf, size_t size)
679 {
680 	ssize_t toread = 0, didread = 0;
681 
682 	while (size > 0) {
683 
684 		/* take from the read buffer first.
685 		 * It is possible that a buffered stream was switched to non-buffered, so we
686 		 * drain the remainder of the buffer before using the "raw" read mode for
687 		 * the excess */
688 		if (stream->writepos > stream->readpos) {
689 
690 			toread = stream->writepos - stream->readpos;
691 			if (toread > size) {
692 				toread = size;
693 			}
694 
695 			memcpy(buf, stream->readbuf + stream->readpos, toread);
696 			stream->readpos += toread;
697 			size -= toread;
698 			buf += toread;
699 			didread += toread;
700 		}
701 
702 		/* ignore eof here; the underlying state might have changed */
703 		if (size == 0) {
704 			break;
705 		}
706 
707 		if (!stream->readfilters.head && ((stream->flags & PHP_STREAM_FLAG_NO_BUFFER) || stream->chunk_size == 1)) {
708 			toread = stream->ops->read(stream, buf, size);
709 			if (toread < 0) {
710 				/* Report an error if the read failed and we did not read any data
711 				 * before that. Otherwise return the data we did read. */
712 				if (didread == 0) {
713 					return toread;
714 				}
715 				break;
716 			}
717 		} else {
718 			if (php_stream_fill_read_buffer(stream, size) != SUCCESS) {
719 				if (didread == 0) {
720 					return -1;
721 				}
722 				break;
723 			}
724 
725 			toread = stream->writepos - stream->readpos;
726 			if ((size_t) toread > size) {
727 				toread = size;
728 			}
729 
730 			if (toread > 0) {
731 				memcpy(buf, stream->readbuf + stream->readpos, toread);
732 				stream->readpos += toread;
733 			}
734 		}
735 		if (toread > 0) {
736 			didread += toread;
737 			buf += toread;
738 			size -= toread;
739 		} else {
740 			/* EOF, or temporary end of data (for non-blocking mode). */
741 			break;
742 		}
743 
744 		/* just break anyway, to avoid greedy read for file://, php://memory, and php://temp */
745 		if ((stream->wrapper != &php_plain_files_wrapper) &&
746 			(stream->ops != &php_stream_memory_ops) &&
747 			(stream->ops != &php_stream_temp_ops)) {
748 			break;
749 		}
750 	}
751 
752 	if (didread > 0) {
753 		stream->position += didread;
754 	}
755 
756 	return didread;
757 }
758 
759 /* Like php_stream_read(), but reading into a zend_string buffer. This has some similarity
760  * to the copy_to_mem() operation, but only performs a single direct read. */
php_stream_read_to_str(php_stream * stream,size_t len)761 PHPAPI zend_string *php_stream_read_to_str(php_stream *stream, size_t len)
762 {
763 	zend_string *str = zend_string_alloc(len, 0);
764 	ssize_t read = php_stream_read(stream, ZSTR_VAL(str), len);
765 	if (read < 0) {
766 		zend_string_efree(str);
767 		return NULL;
768 	}
769 
770 	ZSTR_LEN(str) = read;
771 	ZSTR_VAL(str)[read] = 0;
772 
773 	if ((size_t) read < len / 2) {
774 		return zend_string_truncate(str, read, 0);
775 	}
776 	return str;
777 }
778 
_php_stream_eof(php_stream * stream)779 PHPAPI int _php_stream_eof(php_stream *stream)
780 {
781 	/* if there is data in the buffer, it's not EOF */
782 	if (stream->writepos - stream->readpos > 0) {
783 		return 0;
784 	}
785 
786 	/* use the configured timeout when checking eof */
787 	if (!stream->eof && PHP_STREAM_OPTION_RETURN_ERR ==
788 		   	php_stream_set_option(stream, PHP_STREAM_OPTION_CHECK_LIVENESS,
789 		   	0, NULL)) {
790 		stream->eof = 1;
791 	}
792 
793 	return stream->eof;
794 }
795 
_php_stream_putc(php_stream * stream,int c)796 PHPAPI int _php_stream_putc(php_stream *stream, int c)
797 {
798 	unsigned char buf = c;
799 
800 	if (php_stream_write(stream, (char*)&buf, 1) > 0) {
801 		return 1;
802 	}
803 	return EOF;
804 }
805 
_php_stream_getc(php_stream * stream)806 PHPAPI int _php_stream_getc(php_stream *stream)
807 {
808 	char buf;
809 
810 	if (php_stream_read(stream, &buf, 1) > 0) {
811 		return buf & 0xff;
812 	}
813 	return EOF;
814 }
815 
_php_stream_puts(php_stream * stream,const char * buf)816 PHPAPI int _php_stream_puts(php_stream *stream, const char *buf)
817 {
818 	size_t len;
819 	char newline[2] = "\n"; /* is this OK for Win? */
820 	len = strlen(buf);
821 
822 	if (len > 0 && php_stream_write(stream, buf, len) > 0 && php_stream_write(stream, newline, 1) > 0) {
823 		return 1;
824 	}
825 	return 0;
826 }
827 
_php_stream_stat(php_stream * stream,php_stream_statbuf * ssb)828 PHPAPI int _php_stream_stat(php_stream *stream, php_stream_statbuf *ssb)
829 {
830 	memset(ssb, 0, sizeof(*ssb));
831 
832 	/* if the stream was wrapped, allow the wrapper to stat it */
833 	if (stream->wrapper && stream->wrapper->wops->stream_stat != NULL) {
834 		return stream->wrapper->wops->stream_stat(stream->wrapper, stream, ssb);
835 	}
836 
837 	/* if the stream doesn't directly support stat-ing, return with failure.
838 	 * We could try and emulate this by casting to a FD and fstat-ing it,
839 	 * but since the fd might not represent the actual underlying content
840 	 * this would give bogus results. */
841 	if (stream->ops->stat == NULL) {
842 		return -1;
843 	}
844 
845 	return (stream->ops->stat)(stream, ssb);
846 }
847 
php_stream_locate_eol(php_stream * stream,zend_string * buf)848 PHPAPI const char *php_stream_locate_eol(php_stream *stream, zend_string *buf)
849 {
850 	size_t avail;
851 	const char *cr, *lf, *eol = NULL;
852 	const char *readptr;
853 
854 	if (!buf) {
855 		readptr = (char*)stream->readbuf + stream->readpos;
856 		avail = stream->writepos - stream->readpos;
857 	} else {
858 		readptr = ZSTR_VAL(buf);
859 		avail = ZSTR_LEN(buf);
860 	}
861 
862 	/* Look for EOL */
863 	if (stream->flags & PHP_STREAM_FLAG_DETECT_EOL) {
864 		cr = memchr(readptr, '\r', avail);
865 		lf = memchr(readptr, '\n', avail);
866 
867 		if (cr && lf != cr + 1 && !(lf && lf < cr)) {
868 			/* mac */
869 			stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL;
870 			stream->flags |= PHP_STREAM_FLAG_EOL_MAC;
871 			eol = cr;
872 		} else if ((cr && lf && cr == lf - 1) || (lf)) {
873 			/* dos or unix endings */
874 			stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL;
875 			eol = lf;
876 		}
877 	} else if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) {
878 		eol = memchr(readptr, '\r', avail);
879 	} else {
880 		/* unix (and dos) line endings */
881 		eol = memchr(readptr, '\n', avail);
882 	}
883 
884 	return eol;
885 }
886 
887 /* If buf == NULL, the buffer will be allocated automatically and will be of an
888  * appropriate length to hold the line, regardless of the line length, memory
889  * permitting */
_php_stream_get_line(php_stream * stream,char * buf,size_t maxlen,size_t * returned_len)890 PHPAPI char *_php_stream_get_line(php_stream *stream, char *buf, size_t maxlen,
891 		size_t *returned_len)
892 {
893 	size_t avail = 0;
894 	size_t current_buf_size = 0;
895 	size_t total_copied = 0;
896 	int grow_mode = 0;
897 	char *bufstart = buf;
898 
899 	if (buf == NULL) {
900 		grow_mode = 1;
901 	} else if (maxlen == 0) {
902 		return NULL;
903 	}
904 
905 	/*
906 	 * If the underlying stream operations block when no new data is readable,
907 	 * we need to take extra precautions.
908 	 *
909 	 * If there is buffered data available, we check for a EOL. If it exists,
910 	 * we pass the data immediately back to the caller. This saves a call
911 	 * to the read implementation and will not block where blocking
912 	 * is not necessary at all.
913 	 *
914 	 * If the stream buffer contains more data than the caller requested,
915 	 * we can also avoid that costly step and simply return that data.
916 	 */
917 
918 	for (;;) {
919 		avail = stream->writepos - stream->readpos;
920 
921 		if (avail > 0) {
922 			size_t cpysz = 0;
923 			char *readptr;
924 			const char *eol;
925 			int done = 0;
926 
927 			readptr = (char*)stream->readbuf + stream->readpos;
928 			eol = php_stream_locate_eol(stream, NULL);
929 
930 			if (eol) {
931 				cpysz = eol - readptr + 1;
932 				done = 1;
933 			} else {
934 				cpysz = avail;
935 			}
936 
937 			if (grow_mode) {
938 				/* allow room for a NUL. If this realloc is really a realloc
939 				 * (ie: second time around), we get an extra byte. In most
940 				 * cases, with the default chunk size of 8K, we will only
941 				 * incur that overhead once.  When people have lines longer
942 				 * than 8K, we waste 1 byte per additional 8K or so.
943 				 * That seems acceptable to me, to avoid making this code
944 				 * hard to follow */
945 				bufstart = erealloc(bufstart, current_buf_size + cpysz + 1);
946 				current_buf_size += cpysz + 1;
947 				buf = bufstart + total_copied;
948 			} else {
949 				if (cpysz >= maxlen - 1) {
950 					cpysz = maxlen - 1;
951 					done = 1;
952 				}
953 			}
954 
955 			memcpy(buf, readptr, cpysz);
956 
957 			stream->position += cpysz;
958 			stream->readpos += cpysz;
959 			buf += cpysz;
960 			maxlen -= cpysz;
961 			total_copied += cpysz;
962 
963 			if (done) {
964 				break;
965 			}
966 		} else if (stream->eof) {
967 			break;
968 		} else {
969 			/* XXX: Should be fine to always read chunk_size */
970 			size_t toread;
971 
972 			if (grow_mode) {
973 				toread = stream->chunk_size;
974 			} else {
975 				toread = maxlen - 1;
976 				if (toread > stream->chunk_size) {
977 					toread = stream->chunk_size;
978 				}
979 			}
980 
981 			php_stream_fill_read_buffer(stream, toread);
982 
983 			if (stream->writepos - stream->readpos == 0) {
984 				break;
985 			}
986 		}
987 	}
988 
989 	if (total_copied == 0) {
990 		if (grow_mode) {
991 			assert(bufstart == NULL);
992 		}
993 		return NULL;
994 	}
995 
996 	buf[0] = '\0';
997 	if (returned_len) {
998 		*returned_len = total_copied;
999 	}
1000 
1001 	return bufstart;
1002 }
1003 
1004 #define STREAM_BUFFERED_AMOUNT(stream) \
1005 	((size_t)(((stream)->writepos) - (stream)->readpos))
1006 
_php_stream_search_delim(php_stream * stream,size_t maxlen,size_t skiplen,const char * delim,size_t delim_len)1007 static const char *_php_stream_search_delim(php_stream *stream,
1008 											size_t maxlen,
1009 											size_t skiplen,
1010 											const char *delim, /* non-empty! */
1011 											size_t delim_len)
1012 {
1013 	size_t	seek_len;
1014 
1015 	/* set the maximum number of bytes we're allowed to read from buffer */
1016 	seek_len = MIN(STREAM_BUFFERED_AMOUNT(stream), maxlen);
1017 	if (seek_len <= skiplen) {
1018 		return NULL;
1019 	}
1020 
1021 	if (delim_len == 1) {
1022 		return memchr(&stream->readbuf[stream->readpos + skiplen],
1023 			delim[0], seek_len - skiplen);
1024 	} else {
1025 		return php_memnstr((char*)&stream->readbuf[stream->readpos + skiplen],
1026 				delim, delim_len,
1027 				(char*)&stream->readbuf[stream->readpos + seek_len]);
1028 	}
1029 }
1030 
php_stream_get_record(php_stream * stream,size_t maxlen,const char * delim,size_t delim_len)1031 PHPAPI zend_string *php_stream_get_record(php_stream *stream, size_t maxlen, const char *delim, size_t delim_len)
1032 {
1033 	zend_string	*ret_buf;				/* returned buffer */
1034 	const char *found_delim = NULL;
1035 	size_t	buffered_len,
1036 			tent_ret_len;			/* tentative returned length */
1037 	int	has_delim = delim_len > 0;
1038 
1039 	if (maxlen == 0) {
1040 		return NULL;
1041 	}
1042 
1043 	if (has_delim) {
1044 		found_delim = _php_stream_search_delim(
1045 			stream, maxlen, 0, delim, delim_len);
1046 	}
1047 
1048 	buffered_len = STREAM_BUFFERED_AMOUNT(stream);
1049 	/* try to read up to maxlen length bytes while we don't find the delim */
1050 	while (!found_delim && buffered_len < maxlen) {
1051 		size_t	just_read,
1052 				to_read_now;
1053 
1054 		to_read_now = MIN(maxlen - buffered_len, stream->chunk_size);
1055 
1056 		php_stream_fill_read_buffer(stream, buffered_len + to_read_now);
1057 
1058 		just_read = STREAM_BUFFERED_AMOUNT(stream) - buffered_len;
1059 
1060 		/* Assume the stream is temporarily or permanently out of data */
1061 		if (just_read == 0) {
1062 			break;
1063 		}
1064 
1065 		if (has_delim) {
1066 			/* search for delimiter, but skip buffered_len (the number of bytes
1067 			 * buffered before this loop iteration), as they have already been
1068 			 * searched for the delimiter.
1069 			 * The left part of the delimiter may still remain in the buffer,
1070 			 * so subtract up to <delim_len - 1> from buffered_len, which is
1071 			 * the amount of data we skip on this search  as an optimization
1072 			 */
1073 			found_delim = _php_stream_search_delim(
1074 				stream, maxlen,
1075 				buffered_len >= (delim_len - 1)
1076 						? buffered_len - (delim_len - 1)
1077 						: 0,
1078 				delim, delim_len);
1079 			if (found_delim) {
1080 				break;
1081 			}
1082 		}
1083 		buffered_len += just_read;
1084 	}
1085 
1086 	if (has_delim && found_delim) {
1087 		tent_ret_len = found_delim - (char*)&stream->readbuf[stream->readpos];
1088 	} else if (!has_delim && STREAM_BUFFERED_AMOUNT(stream) >= maxlen) {
1089 		tent_ret_len = maxlen;
1090 	} else {
1091 		/* return with error if the delimiter string (if any) was not found, we
1092 		 * could not completely fill the read buffer with maxlen bytes and we
1093 		 * don't know we've reached end of file. Added with non-blocking streams
1094 		 * in mind, where this situation is frequent */
1095 		if (STREAM_BUFFERED_AMOUNT(stream) < maxlen && !stream->eof) {
1096 			return NULL;
1097 		} else if (STREAM_BUFFERED_AMOUNT(stream) == 0 && stream->eof) {
1098 			/* refuse to return an empty string just because by accident
1099 			 * we knew of EOF in a read that returned no data */
1100 			return NULL;
1101 		} else {
1102 			tent_ret_len = MIN(STREAM_BUFFERED_AMOUNT(stream), maxlen);
1103 		}
1104 	}
1105 
1106 	ret_buf = zend_string_alloc(tent_ret_len, 0);
1107 	/* php_stream_read will not call ops->read here because the necessary
1108 	 * data is guaranteedly buffered */
1109 	ZSTR_LEN(ret_buf) = php_stream_read(stream, ZSTR_VAL(ret_buf), tent_ret_len);
1110 
1111 	if (found_delim) {
1112 		stream->readpos += delim_len;
1113 		stream->position += delim_len;
1114 	}
1115 	ZSTR_VAL(ret_buf)[ZSTR_LEN(ret_buf)] = '\0';
1116 	return ret_buf;
1117 }
1118 
1119 /* Writes a buffer directly to a stream, using multiple of the chunk size */
_php_stream_write_buffer(php_stream * stream,const char * buf,size_t count)1120 static ssize_t _php_stream_write_buffer(php_stream *stream, const char *buf, size_t count)
1121 {
1122 	ssize_t didwrite = 0;
1123 
1124  	/* if we have a seekable stream we need to ensure that data is written at the
1125  	 * current stream->position. This means invalidating the read buffer and then
1126 	 * performing a low-level seek */
1127 	if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && stream->readpos != stream->writepos) {
1128 		stream->readpos = stream->writepos = 0;
1129 
1130 		stream->ops->seek(stream, stream->position, SEEK_SET, &stream->position);
1131 	}
1132 
1133 	while (count > 0) {
1134 		ssize_t justwrote = stream->ops->write(stream, buf, count);
1135 		if (justwrote <= 0) {
1136 			/* If we already successfully wrote some bytes and a write error occurred
1137 			 * later, report the successfully written bytes. */
1138 			if (didwrite == 0) {
1139 				return justwrote;
1140 			}
1141 			return didwrite;
1142 		}
1143 
1144 		buf += justwrote;
1145 		count -= justwrote;
1146 		didwrite += justwrote;
1147 		stream->position += justwrote;
1148 	}
1149 
1150 	return didwrite;
1151 }
1152 
1153 /* push some data through the write filter chain.
1154  * buf may be NULL, if flags are set to indicate a flush.
1155  * This may trigger a real write to the stream.
1156  * Returns the number of bytes consumed from buf by the first filter in the chain.
1157  * */
_php_stream_write_filtered(php_stream * stream,const char * buf,size_t count,int flags)1158 static ssize_t _php_stream_write_filtered(php_stream *stream, const char *buf, size_t count, int flags)
1159 {
1160 	size_t consumed = 0;
1161 	php_stream_bucket *bucket;
1162 	php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL };
1163 	php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap;
1164 	php_stream_filter_status_t status = PSFS_ERR_FATAL;
1165 	php_stream_filter *filter;
1166 
1167 	if (buf) {
1168 		bucket = php_stream_bucket_new(stream, (char *)buf, count, 0, 0);
1169 		php_stream_bucket_append(&brig_in, bucket);
1170 	}
1171 
1172 	for (filter = stream->writefilters.head; filter; filter = filter->next) {
1173 		/* for our return value, we are interested in the number of bytes consumed from
1174 		 * the first filter in the chain */
1175 		status = filter->fops->filter(stream, filter, brig_inp, brig_outp,
1176 				filter == stream->writefilters.head ? &consumed : NULL, flags);
1177 
1178 		if (status != PSFS_PASS_ON) {
1179 			break;
1180 		}
1181 		/* brig_out becomes brig_in.
1182 		 * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets
1183 		 * to its own brigade */
1184 		brig_swap = brig_inp;
1185 		brig_inp = brig_outp;
1186 		brig_outp = brig_swap;
1187 		memset(brig_outp, 0, sizeof(*brig_outp));
1188 	}
1189 
1190 	switch (status) {
1191 		case PSFS_PASS_ON:
1192 			/* filter chain generated some output; push it through to the
1193 			 * underlying stream */
1194 			while (brig_inp->head) {
1195 				bucket = brig_inp->head;
1196 				if (_php_stream_write_buffer(stream, bucket->buf, bucket->buflen) < 0) {
1197 					consumed = (ssize_t) -1;
1198 				}
1199 
1200 				/* Potential error situation - eg: no space on device. Perhaps we should keep this brigade
1201 				 * hanging around and try to write it later.
1202 				 * At the moment, we just drop it on the floor
1203 				 * */
1204 
1205 				php_stream_bucket_unlink(bucket);
1206 				php_stream_bucket_delref(bucket);
1207 			}
1208 			break;
1209 		case PSFS_FEED_ME:
1210 			/* need more data before we can push data through to the stream */
1211 			break;
1212 
1213 		case PSFS_ERR_FATAL:
1214 			/* some fatal error.  Theoretically, the stream is borked, so all
1215 			 * further writes should fail. */
1216 			return (ssize_t) -1;
1217 	}
1218 
1219 	return consumed;
1220 }
1221 
_php_stream_flush(php_stream * stream,int closing)1222 PHPAPI int _php_stream_flush(php_stream *stream, int closing)
1223 {
1224 	int ret = 0;
1225 
1226 	if (stream->writefilters.head) {
1227 		_php_stream_write_filtered(stream, NULL, 0, closing ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC );
1228 	}
1229 
1230 	stream->flags &= ~PHP_STREAM_FLAG_WAS_WRITTEN;
1231 
1232 	if (stream->ops->flush) {
1233 		ret = stream->ops->flush(stream);
1234 	}
1235 
1236 	return ret;
1237 }
1238 
_php_stream_write(php_stream * stream,const char * buf,size_t count)1239 PHPAPI ssize_t _php_stream_write(php_stream *stream, const char *buf, size_t count)
1240 {
1241 	ssize_t bytes;
1242 
1243 	if (count == 0) {
1244 		return 0;
1245 	}
1246 
1247 	ZEND_ASSERT(buf != NULL);
1248 	if (stream->ops->write == NULL) {
1249 		php_error_docref(NULL, E_NOTICE, "Stream is not writable");
1250 		return (ssize_t) -1;
1251 	}
1252 
1253 	if (stream->writefilters.head) {
1254 		bytes = _php_stream_write_filtered(stream, buf, count, PSFS_FLAG_NORMAL);
1255 	} else {
1256 		bytes = _php_stream_write_buffer(stream, buf, count);
1257 	}
1258 
1259 	if (bytes) {
1260 		stream->flags |= PHP_STREAM_FLAG_WAS_WRITTEN;
1261 	}
1262 
1263 	return bytes;
1264 }
1265 
_php_stream_printf(php_stream * stream,const char * fmt,...)1266 PHPAPI ssize_t _php_stream_printf(php_stream *stream, const char *fmt, ...)
1267 {
1268 	ssize_t count;
1269 	char *buf;
1270 	va_list ap;
1271 
1272 	va_start(ap, fmt);
1273 	count = vspprintf(&buf, 0, fmt, ap);
1274 	va_end(ap);
1275 
1276 	if (!buf) {
1277 		return -1; /* error condition */
1278 	}
1279 
1280 	count = php_stream_write(stream, buf, count);
1281 	efree(buf);
1282 
1283 	return count;
1284 }
1285 
_php_stream_tell(php_stream * stream)1286 PHPAPI zend_off_t _php_stream_tell(php_stream *stream)
1287 {
1288 	return stream->position;
1289 }
1290 
_php_stream_seek(php_stream * stream,zend_off_t offset,int whence)1291 PHPAPI int _php_stream_seek(php_stream *stream, zend_off_t offset, int whence)
1292 {
1293 	if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) {
1294 		/* flush to commit data written to the fopencookie FILE* */
1295 		fflush(stream->stdiocast);
1296 	}
1297 
1298 	/* handle the case where we are in the buffer */
1299 	if ((stream->flags & PHP_STREAM_FLAG_NO_BUFFER) == 0) {
1300 		switch(whence) {
1301 			case SEEK_CUR:
1302 				if (offset > 0 && offset <= stream->writepos - stream->readpos) {
1303 					stream->readpos += offset; /* if offset = ..., then readpos = writepos */
1304 					stream->position += offset;
1305 					stream->eof = 0;
1306 					return 0;
1307 				}
1308 				break;
1309 			case SEEK_SET:
1310 				if (offset > stream->position &&
1311 						offset <= stream->position + stream->writepos - stream->readpos) {
1312 					stream->readpos += offset - stream->position;
1313 					stream->position = offset;
1314 					stream->eof = 0;
1315 					return 0;
1316 				}
1317 				break;
1318 		}
1319 	}
1320 
1321 
1322 	if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) {
1323 		int ret;
1324 
1325 		if (stream->writefilters.head) {
1326 			_php_stream_flush(stream, 0);
1327 		}
1328 
1329 		switch(whence) {
1330 			case SEEK_CUR:
1331 				offset = stream->position + offset;
1332 				whence = SEEK_SET;
1333 				break;
1334 		}
1335 		ret = stream->ops->seek(stream, offset, whence, &stream->position);
1336 
1337 		if (((stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) || ret == 0) {
1338 			if (ret == 0) {
1339 				stream->eof = 0;
1340 			}
1341 
1342 			/* invalidate the buffer contents */
1343 			stream->readpos = stream->writepos = 0;
1344 
1345 			return ret;
1346 		}
1347 		/* else the stream has decided that it can't support seeking after all;
1348 		 * fall through to attempt emulation */
1349 	}
1350 
1351 	/* emulate forward moving seeks with reads */
1352 	if (whence == SEEK_CUR && offset >= 0) {
1353 		char tmp[1024];
1354 		ssize_t didread;
1355 		while (offset > 0) {
1356 			if ((didread = php_stream_read(stream, tmp, MIN(offset, sizeof(tmp)))) <= 0) {
1357 				return -1;
1358 			}
1359 			offset -= didread;
1360 		}
1361 		stream->eof = 0;
1362 		return 0;
1363 	}
1364 
1365 	php_error_docref(NULL, E_WARNING, "Stream does not support seeking");
1366 
1367 	return -1;
1368 }
1369 
_php_stream_set_option(php_stream * stream,int option,int value,void * ptrparam)1370 PHPAPI int _php_stream_set_option(php_stream *stream, int option, int value, void *ptrparam)
1371 {
1372 	int ret = PHP_STREAM_OPTION_RETURN_NOTIMPL;
1373 
1374 	if (stream->ops->set_option) {
1375 		ret = stream->ops->set_option(stream, option, value, ptrparam);
1376 	}
1377 
1378 	if (ret == PHP_STREAM_OPTION_RETURN_NOTIMPL) {
1379 		switch(option) {
1380 			case PHP_STREAM_OPTION_SET_CHUNK_SIZE:
1381 				/* XXX chunk size itself is of size_t, that might be ok or not for a particular case*/
1382 				ret = stream->chunk_size > INT_MAX ? INT_MAX : (int)stream->chunk_size;
1383 				stream->chunk_size = value;
1384 				return ret;
1385 
1386 			case PHP_STREAM_OPTION_READ_BUFFER:
1387 				/* try to match the buffer mode as best we can */
1388 				if (value == PHP_STREAM_BUFFER_NONE) {
1389 					stream->flags |= PHP_STREAM_FLAG_NO_BUFFER;
1390 				} else if (stream->flags & PHP_STREAM_FLAG_NO_BUFFER) {
1391 					stream->flags ^= PHP_STREAM_FLAG_NO_BUFFER;
1392 				}
1393 				ret = PHP_STREAM_OPTION_RETURN_OK;
1394 				break;
1395 
1396 			default:
1397 				;
1398 		}
1399 	}
1400 
1401 	return ret;
1402 }
1403 
_php_stream_truncate_set_size(php_stream * stream,size_t newsize)1404 PHPAPI int _php_stream_truncate_set_size(php_stream *stream, size_t newsize)
1405 {
1406 	return php_stream_set_option(stream, PHP_STREAM_OPTION_TRUNCATE_API, PHP_STREAM_TRUNCATE_SET_SIZE, &newsize);
1407 }
1408 
_php_stream_passthru(php_stream * stream STREAMS_DC)1409 PHPAPI ssize_t _php_stream_passthru(php_stream * stream STREAMS_DC)
1410 {
1411 	size_t bcount = 0;
1412 	char buf[8192];
1413 	ssize_t b;
1414 
1415 	if (php_stream_mmap_possible(stream)) {
1416 		char *p;
1417 		size_t mapped;
1418 
1419 		p = php_stream_mmap_range(stream, php_stream_tell(stream), PHP_STREAM_MMAP_ALL, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped);
1420 
1421 		if (p) {
1422 			do {
1423 				/* output functions return int, so pass in int max */
1424 				if (0 < (b = PHPWRITE(p + bcount, MIN(mapped - bcount, INT_MAX)))) {
1425 					bcount += b;
1426 				}
1427 			} while (b > 0 && mapped > bcount);
1428 
1429 			php_stream_mmap_unmap_ex(stream, mapped);
1430 
1431 			return bcount;
1432 		}
1433 	}
1434 
1435 	while ((b = php_stream_read(stream, buf, sizeof(buf))) > 0) {
1436 		PHPWRITE(buf, b);
1437 		bcount += b;
1438 	}
1439 
1440 	if (b < 0 && bcount == 0) {
1441 		return b;
1442 	}
1443 
1444 	return bcount;
1445 }
1446 
1447 
_php_stream_copy_to_mem(php_stream * src,size_t maxlen,int persistent STREAMS_DC)1448 PHPAPI zend_string *_php_stream_copy_to_mem(php_stream *src, size_t maxlen, int persistent STREAMS_DC)
1449 {
1450 	ssize_t ret = 0;
1451 	char *ptr;
1452 	size_t len = 0, max_len;
1453 	int step = CHUNK_SIZE;
1454 	int min_room = CHUNK_SIZE / 4;
1455 	php_stream_statbuf ssbuf;
1456 	zend_string *result;
1457 
1458 	if (maxlen == 0) {
1459 		return ZSTR_EMPTY_ALLOC();
1460 	}
1461 
1462 	if (maxlen == PHP_STREAM_COPY_ALL) {
1463 		maxlen = 0;
1464 	}
1465 
1466 	if (maxlen > 0) {
1467 		result = zend_string_alloc(maxlen, persistent);
1468 		ptr = ZSTR_VAL(result);
1469 		while ((len < maxlen) && !php_stream_eof(src)) {
1470 			ret = php_stream_read(src, ptr, maxlen - len);
1471 			if (ret <= 0) {
1472 				// TODO: Propagate error?
1473 				break;
1474 			}
1475 			len += ret;
1476 			ptr += ret;
1477 		}
1478 		if (len) {
1479 			ZSTR_LEN(result) = len;
1480 			ZSTR_VAL(result)[len] = '\0';
1481 
1482 			/* Only truncate if the savings are large enough */
1483 			if (len < maxlen / 2) {
1484 				result = zend_string_truncate(result, len, persistent);
1485 			}
1486 		} else {
1487 			zend_string_free(result);
1488 			result = NULL;
1489 		}
1490 		return result;
1491 	}
1492 
1493 	/* avoid many reallocs by allocating a good sized chunk to begin with, if
1494 	 * we can.  Note that the stream may be filtered, in which case the stat
1495 	 * result may be inaccurate, as the filter may inflate or deflate the
1496 	 * number of bytes that we can read.  In order to avoid an upsize followed
1497 	 * by a downsize of the buffer, overestimate by the step size (which is
1498 	 * 8K).  */
1499 	if (php_stream_stat(src, &ssbuf) == 0 && ssbuf.sb.st_size > 0) {
1500 		max_len = MAX(ssbuf.sb.st_size - src->position, 0) + step;
1501 	} else {
1502 		max_len = step;
1503 	}
1504 
1505 	result = zend_string_alloc(max_len, persistent);
1506 	ptr = ZSTR_VAL(result);
1507 
1508 	// TODO: Propagate error?
1509 	while ((ret = php_stream_read(src, ptr, max_len - len)) > 0){
1510 		len += ret;
1511 		if (len + min_room >= max_len) {
1512 			result = zend_string_extend(result, max_len + step, persistent);
1513 			max_len += step;
1514 			ptr = ZSTR_VAL(result) + len;
1515 		} else {
1516 			ptr += ret;
1517 		}
1518 	}
1519 	if (len) {
1520 		result = zend_string_truncate(result, len, persistent);
1521 		ZSTR_VAL(result)[len] = '\0';
1522 	} else {
1523 		zend_string_free(result);
1524 		result = NULL;
1525 	}
1526 
1527 	return result;
1528 }
1529 
1530 /* Returns SUCCESS/FAILURE and sets *len to the number of bytes moved */
_php_stream_copy_to_stream_ex(php_stream * src,php_stream * dest,size_t maxlen,size_t * len STREAMS_DC)1531 PHPAPI int _php_stream_copy_to_stream_ex(php_stream *src, php_stream *dest, size_t maxlen, size_t *len STREAMS_DC)
1532 {
1533 	char buf[CHUNK_SIZE];
1534 	size_t haveread = 0;
1535 	size_t towrite;
1536 	size_t dummy;
1537 
1538 	if (!len) {
1539 		len = &dummy;
1540 	}
1541 
1542 	if (maxlen == 0) {
1543 		*len = 0;
1544 		return SUCCESS;
1545 	}
1546 
1547 	if (maxlen == PHP_STREAM_COPY_ALL) {
1548 		maxlen = 0;
1549 	}
1550 
1551 	if (php_stream_mmap_possible(src)) {
1552 		char *p;
1553 
1554 		do {
1555 			size_t chunk_size = (maxlen == 0 || maxlen > PHP_STREAM_MMAP_MAX) ? PHP_STREAM_MMAP_MAX : maxlen;
1556 			size_t mapped;
1557 
1558 			p = php_stream_mmap_range(src, php_stream_tell(src), chunk_size, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped);
1559 
1560 			if (p) {
1561 				ssize_t didwrite;
1562 
1563 				if (php_stream_seek(src, mapped, SEEK_CUR) != 0) {
1564 					php_stream_mmap_unmap(src);
1565 					break;
1566 				}
1567 
1568 				didwrite = php_stream_write(dest, p, mapped);
1569 				if (didwrite < 0) {
1570 					*len = haveread;
1571 					return FAILURE;
1572 				}
1573 
1574 				php_stream_mmap_unmap(src);
1575 
1576 				*len = haveread += didwrite;
1577 
1578 				/* we've got at least 1 byte to read
1579 				 * less than 1 is an error
1580 				 * AND read bytes match written */
1581 				if (mapped == 0 || mapped != didwrite) {
1582 					return FAILURE;
1583 				}
1584 				if (mapped < chunk_size) {
1585 					return SUCCESS;
1586 				}
1587 				if (maxlen != 0) {
1588 					maxlen -= mapped;
1589 					if (maxlen == 0) {
1590 						return SUCCESS;
1591 					}
1592 				}
1593 			}
1594 		} while (p);
1595 	}
1596 
1597 	while(1) {
1598 		size_t readchunk = sizeof(buf);
1599 		ssize_t didread;
1600 		char *writeptr;
1601 
1602 		if (maxlen && (maxlen - haveread) < readchunk) {
1603 			readchunk = maxlen - haveread;
1604 		}
1605 
1606 		didread = php_stream_read(src, buf, readchunk);
1607 		if (didread <= 0) {
1608 			*len = haveread;
1609 			return didread < 0 ? FAILURE : SUCCESS;
1610 		}
1611 
1612 		towrite = didread;
1613 		writeptr = buf;
1614 		haveread += didread;
1615 
1616 		while (towrite) {
1617 			ssize_t didwrite = php_stream_write(dest, writeptr, towrite);
1618 			if (didwrite <= 0) {
1619 				*len = haveread - (didread - towrite);
1620 				return FAILURE;
1621 			}
1622 
1623 			towrite -= didwrite;
1624 			writeptr += didwrite;
1625 		}
1626 
1627 		if (maxlen && maxlen == haveread) {
1628 			break;
1629 		}
1630 	}
1631 
1632 	*len = haveread;
1633 	return SUCCESS;
1634 }
1635 
1636 /* Returns the number of bytes moved.
1637  * Returns 1 when source len is 0.
1638  * Deprecated in favor of php_stream_copy_to_stream_ex() */
1639 ZEND_ATTRIBUTE_DEPRECATED
_php_stream_copy_to_stream(php_stream * src,php_stream * dest,size_t maxlen STREAMS_DC)1640 PHPAPI size_t _php_stream_copy_to_stream(php_stream *src, php_stream *dest, size_t maxlen STREAMS_DC)
1641 {
1642 	size_t len;
1643 	int ret = _php_stream_copy_to_stream_ex(src, dest, maxlen, &len STREAMS_REL_CC);
1644 	if (ret == SUCCESS && len == 0 && maxlen != 0) {
1645 		return 1;
1646 	}
1647 	return len;
1648 }
1649 /* }}} */
1650 
1651 /* {{{ wrapper init and registration */
1652 
stream_resource_regular_dtor(zend_resource * rsrc)1653 static void stream_resource_regular_dtor(zend_resource *rsrc)
1654 {
1655 	php_stream *stream = (php_stream*)rsrc->ptr;
1656 	/* set the return value for pclose */
1657 	FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR);
1658 }
1659 
stream_resource_persistent_dtor(zend_resource * rsrc)1660 static void stream_resource_persistent_dtor(zend_resource *rsrc)
1661 {
1662 	php_stream *stream = (php_stream*)rsrc->ptr;
1663 	FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR);
1664 }
1665 
php_shutdown_stream_hashes(void)1666 void php_shutdown_stream_hashes(void)
1667 {
1668 	FG(user_stream_current_filename) = NULL;
1669 	if (FG(stream_wrappers)) {
1670 		zend_hash_destroy(FG(stream_wrappers));
1671 		efree(FG(stream_wrappers));
1672 		FG(stream_wrappers) = NULL;
1673 	}
1674 
1675 	if (FG(stream_filters)) {
1676 		zend_hash_destroy(FG(stream_filters));
1677 		efree(FG(stream_filters));
1678 		FG(stream_filters) = NULL;
1679 	}
1680 
1681     if (FG(wrapper_errors)) {
1682 		zend_hash_destroy(FG(wrapper_errors));
1683 		efree(FG(wrapper_errors));
1684 		FG(wrapper_errors) = NULL;
1685     }
1686 }
1687 
php_init_stream_wrappers(int module_number)1688 int php_init_stream_wrappers(int module_number)
1689 {
1690 	le_stream = zend_register_list_destructors_ex(stream_resource_regular_dtor, NULL, "stream", module_number);
1691 	le_pstream = zend_register_list_destructors_ex(NULL, stream_resource_persistent_dtor, "persistent stream", module_number);
1692 
1693 	/* Filters are cleaned up by the streams they're attached to */
1694 	le_stream_filter = zend_register_list_destructors_ex(NULL, NULL, "stream filter", module_number);
1695 
1696 	zend_hash_init(&url_stream_wrappers_hash, 8, NULL, NULL, 1);
1697 	zend_hash_init(php_get_stream_filters_hash_global(), 8, NULL, NULL, 1);
1698 	zend_hash_init(php_stream_xport_get_hash(), 8, NULL, NULL, 1);
1699 
1700 	return (php_stream_xport_register("tcp", php_stream_generic_socket_factory) == SUCCESS
1701 			&&
1702 			php_stream_xport_register("udp", php_stream_generic_socket_factory) == SUCCESS
1703 #if defined(AF_UNIX) && !(defined(PHP_WIN32) || defined(__riscos__))
1704 			&&
1705 			php_stream_xport_register("unix", php_stream_generic_socket_factory) == SUCCESS
1706 			&&
1707 			php_stream_xport_register("udg", php_stream_generic_socket_factory) == SUCCESS
1708 #endif
1709 		) ? SUCCESS : FAILURE;
1710 }
1711 
php_shutdown_stream_wrappers(int module_number)1712 int php_shutdown_stream_wrappers(int module_number)
1713 {
1714 	zend_hash_destroy(&url_stream_wrappers_hash);
1715 	zend_hash_destroy(php_get_stream_filters_hash_global());
1716 	zend_hash_destroy(php_stream_xport_get_hash());
1717 	return SUCCESS;
1718 }
1719 
1720 /* Validate protocol scheme names during registration
1721  * Must conform to /^[a-zA-Z0-9+.-]+$/
1722  */
php_stream_wrapper_scheme_validate(const char * protocol,unsigned int protocol_len)1723 static inline int php_stream_wrapper_scheme_validate(const char *protocol, unsigned int protocol_len)
1724 {
1725 	unsigned int i;
1726 
1727 	for(i = 0; i < protocol_len; i++) {
1728 		if (!isalnum((int)protocol[i]) &&
1729 			protocol[i] != '+' &&
1730 			protocol[i] != '-' &&
1731 			protocol[i] != '.') {
1732 			return FAILURE;
1733 		}
1734 	}
1735 
1736 	return SUCCESS;
1737 }
1738 
1739 /* API for registering GLOBAL wrappers */
php_register_url_stream_wrapper(const char * protocol,const php_stream_wrapper * wrapper)1740 PHPAPI int php_register_url_stream_wrapper(const char *protocol, const php_stream_wrapper *wrapper)
1741 {
1742 	unsigned int protocol_len = (unsigned int)strlen(protocol);
1743 	int ret;
1744 	zend_string *str;
1745 
1746 	if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) {
1747 		return FAILURE;
1748 	}
1749 
1750 	str = zend_string_init_interned(protocol, protocol_len, 1);
1751 	ret = zend_hash_add_ptr(&url_stream_wrappers_hash, str, (void*)wrapper) ? SUCCESS : FAILURE;
1752 	zend_string_release_ex(str, 1);
1753 	return ret;
1754 }
1755 
php_unregister_url_stream_wrapper(const char * protocol)1756 PHPAPI int php_unregister_url_stream_wrapper(const char *protocol)
1757 {
1758 	return zend_hash_str_del(&url_stream_wrappers_hash, protocol, strlen(protocol));
1759 }
1760 
clone_wrapper_hash(void)1761 static void clone_wrapper_hash(void)
1762 {
1763 	ALLOC_HASHTABLE(FG(stream_wrappers));
1764 	zend_hash_init(FG(stream_wrappers), zend_hash_num_elements(&url_stream_wrappers_hash), NULL, NULL, 0);
1765 	zend_hash_copy(FG(stream_wrappers), &url_stream_wrappers_hash, NULL);
1766 }
1767 
1768 /* API for registering VOLATILE wrappers */
php_register_url_stream_wrapper_volatile(zend_string * protocol,php_stream_wrapper * wrapper)1769 PHPAPI int php_register_url_stream_wrapper_volatile(zend_string *protocol, php_stream_wrapper *wrapper)
1770 {
1771 	if (php_stream_wrapper_scheme_validate(ZSTR_VAL(protocol), ZSTR_LEN(protocol)) == FAILURE) {
1772 		return FAILURE;
1773 	}
1774 
1775 	if (!FG(stream_wrappers)) {
1776 		clone_wrapper_hash();
1777 	}
1778 
1779 	return zend_hash_add_ptr(FG(stream_wrappers), protocol, wrapper) ? SUCCESS : FAILURE;
1780 }
1781 
php_unregister_url_stream_wrapper_volatile(zend_string * protocol)1782 PHPAPI int php_unregister_url_stream_wrapper_volatile(zend_string *protocol)
1783 {
1784 	if (!FG(stream_wrappers)) {
1785 		clone_wrapper_hash();
1786 	}
1787 
1788 	return zend_hash_del(FG(stream_wrappers), protocol);
1789 }
1790 /* }}} */
1791 
1792 /* {{{ php_stream_locate_url_wrapper */
php_stream_locate_url_wrapper(const char * path,const char ** path_for_open,int options)1793 PHPAPI php_stream_wrapper *php_stream_locate_url_wrapper(const char *path, const char **path_for_open, int options)
1794 {
1795 	HashTable *wrapper_hash = (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash);
1796 	php_stream_wrapper *wrapper = NULL;
1797 	const char *p, *protocol = NULL;
1798 	size_t n = 0;
1799 
1800 	if (path_for_open) {
1801 		*path_for_open = (char*)path;
1802 	}
1803 
1804 	if (options & IGNORE_URL) {
1805 		return (php_stream_wrapper*)((options & STREAM_LOCATE_WRAPPERS_ONLY) ? NULL : &php_plain_files_wrapper);
1806 	}
1807 
1808 	for (p = path; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++) {
1809 		n++;
1810 	}
1811 
1812 	if ((*p == ':') && (n > 1) && (!strncmp("//", p+1, 2) || (n == 4 && !memcmp("data:", path, 5)))) {
1813 		protocol = path;
1814 	}
1815 
1816 	if (protocol) {
1817 		if (NULL == (wrapper = zend_hash_str_find_ptr(wrapper_hash, protocol, n))) {
1818 			char *tmp = estrndup(protocol, n);
1819 
1820 			php_strtolower(tmp, n);
1821 			if (NULL == (wrapper = zend_hash_str_find_ptr(wrapper_hash, tmp, n))) {
1822 				char wrapper_name[32];
1823 
1824 				if (n >= sizeof(wrapper_name)) {
1825 					n = sizeof(wrapper_name) - 1;
1826 				}
1827 				PHP_STRLCPY(wrapper_name, protocol, sizeof(wrapper_name), n);
1828 
1829 				php_error_docref(NULL, E_WARNING, "Unable to find the wrapper \"%s\" - did you forget to enable it when you configured PHP?", wrapper_name);
1830 
1831 				wrapper = NULL;
1832 				protocol = NULL;
1833 			}
1834 			efree(tmp);
1835 		}
1836 	}
1837 	/* TODO: curl based streams probably support file:// properly */
1838 	if (!protocol || !strncasecmp(protocol, "file", n))	{
1839 		/* fall back on regular file access */
1840 		php_stream_wrapper *plain_files_wrapper = (php_stream_wrapper*)&php_plain_files_wrapper;
1841 
1842 		if (protocol) {
1843 			int localhost = 0;
1844 
1845 			if (!strncasecmp(path, "file://localhost/", 17)) {
1846 				localhost = 1;
1847 			}
1848 
1849 #ifdef PHP_WIN32
1850 			if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/' && path[n+4] != ':')	{
1851 #else
1852 			if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/') {
1853 #endif
1854 				if (options & REPORT_ERRORS) {
1855 					php_error_docref(NULL, E_WARNING, "Remote host file access not supported, %s", path);
1856 				}
1857 				return NULL;
1858 			}
1859 
1860 			if (path_for_open) {
1861 				/* skip past protocol and :/, but handle windows correctly */
1862 				*path_for_open = (char*)path + n + 1;
1863 				if (localhost == 1) {
1864 					(*path_for_open) += 11;
1865 				}
1866 				while (*(++*path_for_open)=='/') {
1867 					/* intentionally empty */
1868 				}
1869 #ifdef PHP_WIN32
1870 				if (*(*path_for_open + 1) != ':')
1871 #endif
1872 					(*path_for_open)--;
1873 			}
1874 		}
1875 
1876 		if (options & STREAM_LOCATE_WRAPPERS_ONLY) {
1877 			return NULL;
1878 		}
1879 
1880 		if (FG(stream_wrappers)) {
1881 		/* The file:// wrapper may have been disabled/overridden */
1882 
1883 			if (wrapper) {
1884 				/* It was found so go ahead and provide it */
1885 				return wrapper;
1886 			}
1887 
1888 			/* Check again, the original check might have not known the protocol name */
1889 			if ((wrapper = zend_hash_find_ex_ptr(wrapper_hash, ZSTR_KNOWN(ZEND_STR_FILE), 1)) != NULL) {
1890 				return wrapper;
1891 			}
1892 
1893 			if (options & REPORT_ERRORS) {
1894 				php_error_docref(NULL, E_WARNING, "file:// wrapper is disabled in the server configuration");
1895 			}
1896 			return NULL;
1897 		}
1898 
1899 		return plain_files_wrapper;
1900 	}
1901 
1902 	if (wrapper && wrapper->is_url &&
1903         (options & STREAM_DISABLE_URL_PROTECTION) == 0 &&
1904 	    (!PG(allow_url_fopen) ||
1905 	     (((options & STREAM_OPEN_FOR_INCLUDE) ||
1906 	       PG(in_user_include)) && !PG(allow_url_include)))) {
1907 		if (options & REPORT_ERRORS) {
1908 			/* protocol[n] probably isn't '\0' */
1909 			if (!PG(allow_url_fopen)) {
1910 				php_error_docref(NULL, E_WARNING, "%.*s:// wrapper is disabled in the server configuration by allow_url_fopen=0", (int)n, protocol);
1911 			} else {
1912 				php_error_docref(NULL, E_WARNING, "%.*s:// wrapper is disabled in the server configuration by allow_url_include=0", (int)n, protocol);
1913 			}
1914 		}
1915 		return NULL;
1916 	}
1917 
1918 	return wrapper;
1919 }
1920 /* }}} */
1921 
1922 /* {{{ _php_stream_mkdir */
1923 PHPAPI int _php_stream_mkdir(const char *path, int mode, int options, php_stream_context *context)
1924 {
1925 	php_stream_wrapper *wrapper = NULL;
1926 
1927 	wrapper = php_stream_locate_url_wrapper(path, NULL, 0);
1928 	if (!wrapper || !wrapper->wops || !wrapper->wops->stream_mkdir) {
1929 		return 0;
1930 	}
1931 
1932 	return wrapper->wops->stream_mkdir(wrapper, path, mode, options, context);
1933 }
1934 /* }}} */
1935 
1936 /* {{{ _php_stream_rmdir */
1937 PHPAPI int _php_stream_rmdir(const char *path, int options, php_stream_context *context)
1938 {
1939 	php_stream_wrapper *wrapper = NULL;
1940 
1941 	wrapper = php_stream_locate_url_wrapper(path, NULL, 0);
1942 	if (!wrapper || !wrapper->wops || !wrapper->wops->stream_rmdir) {
1943 		return 0;
1944 	}
1945 
1946 	return wrapper->wops->stream_rmdir(wrapper, path, options, context);
1947 }
1948 /* }}} */
1949 
1950 /* {{{ _php_stream_stat_path */
1951 PHPAPI int _php_stream_stat_path(const char *path, int flags, php_stream_statbuf *ssb, php_stream_context *context)
1952 {
1953 	php_stream_wrapper *wrapper = NULL;
1954 	const char *path_to_open = path;
1955 	int ret;
1956 
1957 	memset(ssb, 0, sizeof(*ssb));
1958 
1959 	if (!(flags & PHP_STREAM_URL_STAT_NOCACHE)) {
1960 		/* Try to hit the cache first */
1961 		if (flags & PHP_STREAM_URL_STAT_LINK) {
1962 			if (BG(CurrentLStatFile) && strcmp(path, BG(CurrentLStatFile)) == 0) {
1963 				memcpy(ssb, &BG(lssb), sizeof(php_stream_statbuf));
1964 				return 0;
1965 			}
1966 		} else {
1967 			if (BG(CurrentStatFile) && strcmp(path, BG(CurrentStatFile)) == 0) {
1968 				memcpy(ssb, &BG(ssb), sizeof(php_stream_statbuf));
1969 				return 0;
1970 			}
1971 		}
1972 	}
1973 
1974 	wrapper = php_stream_locate_url_wrapper(path, &path_to_open, 0);
1975 	if (wrapper && wrapper->wops->url_stat) {
1976 		ret = wrapper->wops->url_stat(wrapper, path_to_open, flags, ssb, context);
1977 		if (ret == 0) {
1978 		        if (!(flags & PHP_STREAM_URL_STAT_NOCACHE)) {
1979 				/* Drop into cache */
1980 				if (flags & PHP_STREAM_URL_STAT_LINK) {
1981 					if (BG(CurrentLStatFile)) {
1982 						efree(BG(CurrentLStatFile));
1983 					}
1984 					BG(CurrentLStatFile) = estrdup(path);
1985 					memcpy(&BG(lssb), ssb, sizeof(php_stream_statbuf));
1986 				} else {
1987 					if (BG(CurrentStatFile)) {
1988 						efree(BG(CurrentStatFile));
1989 					}
1990 					BG(CurrentStatFile) = estrdup(path);
1991 					memcpy(&BG(ssb), ssb, sizeof(php_stream_statbuf));
1992 				}
1993 			}
1994 		}
1995 		return ret;
1996 	}
1997 	return -1;
1998 }
1999 /* }}} */
2000 
2001 /* {{{ php_stream_opendir */
2002 PHPAPI php_stream *_php_stream_opendir(const char *path, int options,
2003 		php_stream_context *context STREAMS_DC)
2004 {
2005 	php_stream *stream = NULL;
2006 	php_stream_wrapper *wrapper = NULL;
2007 	const char *path_to_open;
2008 
2009 	if (!path || !*path) {
2010 		return NULL;
2011 	}
2012 
2013 	path_to_open = path;
2014 
2015 	wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options);
2016 
2017 	if (wrapper && wrapper->wops->dir_opener) {
2018 		stream = wrapper->wops->dir_opener(wrapper,
2019 				path_to_open, "r", options & ~REPORT_ERRORS, NULL,
2020 				context STREAMS_REL_CC);
2021 
2022 		if (stream) {
2023 			stream->wrapper = wrapper;
2024 			stream->flags |= PHP_STREAM_FLAG_NO_BUFFER | PHP_STREAM_FLAG_IS_DIR;
2025 		}
2026 	} else if (wrapper) {
2027 		php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS, "not implemented");
2028 	}
2029 	if (stream == NULL && (options & REPORT_ERRORS)) {
2030 		php_stream_display_wrapper_errors(wrapper, path, "Failed to open directory");
2031 	}
2032 	php_stream_tidy_wrapper_error_log(wrapper);
2033 
2034 	return stream;
2035 }
2036 /* }}} */
2037 
2038 /* {{{ _php_stream_readdir */
2039 PHPAPI php_stream_dirent *_php_stream_readdir(php_stream *dirstream, php_stream_dirent *ent)
2040 {
2041 
2042 	if (sizeof(php_stream_dirent) == php_stream_read(dirstream, (char*)ent, sizeof(php_stream_dirent))) {
2043 		return ent;
2044 	}
2045 
2046 	return NULL;
2047 }
2048 /* }}} */
2049 
2050 /* {{{ php_stream_open_wrapper_ex */
2051 PHPAPI php_stream *_php_stream_open_wrapper_ex(const char *path, const char *mode, int options,
2052 		zend_string **opened_path, php_stream_context *context STREAMS_DC)
2053 {
2054 	php_stream *stream = NULL;
2055 	php_stream_wrapper *wrapper = NULL;
2056 	const char *path_to_open;
2057 	int persistent = options & STREAM_OPEN_PERSISTENT;
2058 	zend_string *resolved_path = NULL;
2059 	char *copy_of_path = NULL;
2060 
2061 	if (opened_path) {
2062 		*opened_path = NULL;
2063 	}
2064 
2065 	if (!path || !*path) {
2066 		zend_value_error("Path cannot be empty");
2067 		return NULL;
2068 	}
2069 
2070 	if (options & USE_PATH) {
2071 		resolved_path = zend_resolve_path(path, strlen(path));
2072 		if (resolved_path) {
2073 			path = ZSTR_VAL(resolved_path);
2074 			/* we've found this file, don't re-check include_path or run realpath */
2075 			options |= STREAM_ASSUME_REALPATH;
2076 			options &= ~USE_PATH;
2077 		}
2078 		if (EG(exception)) {
2079 			return NULL;
2080 		}
2081 	}
2082 
2083 	path_to_open = path;
2084 
2085 	wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options);
2086 	if ((options & STREAM_USE_URL) && (!wrapper || !wrapper->is_url)) {
2087 		php_error_docref(NULL, E_WARNING, "This function may only be used against URLs");
2088 		if (resolved_path) {
2089 			zend_string_release_ex(resolved_path, 0);
2090 		}
2091 		return NULL;
2092 	}
2093 
2094 	if (wrapper) {
2095 		if (!wrapper->wops->stream_opener) {
2096 			php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS,
2097 					"wrapper does not support stream open");
2098 		} else {
2099 			stream = wrapper->wops->stream_opener(wrapper,
2100 				path_to_open, mode, options & ~REPORT_ERRORS,
2101 				opened_path, context STREAMS_REL_CC);
2102 		}
2103 
2104 		/* if the caller asked for a persistent stream but the wrapper did not
2105 		 * return one, force an error here */
2106 		if (stream && (options & STREAM_OPEN_PERSISTENT) && !stream->is_persistent) {
2107 			php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS,
2108 					"wrapper does not support persistent streams");
2109 			php_stream_close(stream);
2110 			stream = NULL;
2111 		}
2112 
2113 		if (stream) {
2114 			stream->wrapper = wrapper;
2115 		}
2116 	}
2117 
2118 	if (stream) {
2119 		if (opened_path && !*opened_path && resolved_path) {
2120 			*opened_path = resolved_path;
2121 			resolved_path = NULL;
2122 		}
2123 		if (stream->orig_path) {
2124 			pefree(stream->orig_path, persistent);
2125 		}
2126 		copy_of_path = pestrdup(path, persistent);
2127 		stream->orig_path = copy_of_path;
2128 #if ZEND_DEBUG
2129 		stream->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename;
2130 		stream->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno;
2131 #endif
2132 	}
2133 
2134 	if (stream != NULL && (options & STREAM_MUST_SEEK)) {
2135 		php_stream *newstream;
2136 
2137 		switch(php_stream_make_seekable_rel(stream, &newstream,
2138 					(options & STREAM_WILL_CAST)
2139 						? PHP_STREAM_PREFER_STDIO : PHP_STREAM_NO_PREFERENCE)) {
2140 			case PHP_STREAM_UNCHANGED:
2141 				if (resolved_path) {
2142 					zend_string_release_ex(resolved_path, 0);
2143 				}
2144 				return stream;
2145 			case PHP_STREAM_RELEASED:
2146 				if (newstream->orig_path) {
2147 					pefree(newstream->orig_path, persistent);
2148 				}
2149 				newstream->orig_path = pestrdup(path, persistent);
2150 				if (resolved_path) {
2151 					zend_string_release_ex(resolved_path, 0);
2152 				}
2153 				return newstream;
2154 			default:
2155 				php_stream_close(stream);
2156 				stream = NULL;
2157 				if (options & REPORT_ERRORS) {
2158 					char *tmp = estrdup(path);
2159 					php_strip_url_passwd(tmp);
2160 					php_error_docref1(NULL, tmp, E_WARNING, "could not make seekable - %s",
2161 							tmp);
2162 					efree(tmp);
2163 
2164 					options &= ~REPORT_ERRORS;
2165 				}
2166 		}
2167 	}
2168 
2169 	if (stream && stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && strchr(mode, 'a') && stream->position == 0) {
2170 		zend_off_t newpos = 0;
2171 
2172 		/* if opened for append, we need to revise our idea of the initial file position */
2173 		if (0 == stream->ops->seek(stream, 0, SEEK_CUR, &newpos)) {
2174 			stream->position = newpos;
2175 		}
2176 	}
2177 
2178 	if (stream == NULL && (options & REPORT_ERRORS)) {
2179 		php_stream_display_wrapper_errors(wrapper, path, "Failed to open stream");
2180 		if (opened_path && *opened_path) {
2181 			zend_string_release_ex(*opened_path, 0);
2182 			*opened_path = NULL;
2183 		}
2184 	}
2185 	php_stream_tidy_wrapper_error_log(wrapper);
2186 #if ZEND_DEBUG
2187 	if (stream == NULL && copy_of_path != NULL) {
2188 		pefree(copy_of_path, persistent);
2189 	}
2190 #endif
2191 	if (resolved_path) {
2192 		zend_string_release_ex(resolved_path, 0);
2193 	}
2194 	return stream;
2195 }
2196 /* }}} */
2197 
2198 /* {{{ context API */
2199 PHPAPI php_stream_context *php_stream_context_set(php_stream *stream, php_stream_context *context)
2200 {
2201 	php_stream_context *oldcontext = PHP_STREAM_CONTEXT(stream);
2202 
2203 	if (context) {
2204 		stream->ctx = context->res;
2205 		GC_ADDREF(context->res);
2206 	} else {
2207 		stream->ctx = NULL;
2208 	}
2209 	if (oldcontext) {
2210 		zend_list_delete(oldcontext->res);
2211 	}
2212 
2213 	return oldcontext;
2214 }
2215 
2216 PHPAPI void php_stream_notification_notify(php_stream_context *context, int notifycode, int severity,
2217 		char *xmsg, int xcode, size_t bytes_sofar, size_t bytes_max, void * ptr)
2218 {
2219 	if (context && context->notifier)
2220 		context->notifier->func(context, notifycode, severity, xmsg, xcode, bytes_sofar, bytes_max, ptr);
2221 }
2222 
2223 PHPAPI void php_stream_context_free(php_stream_context *context)
2224 {
2225 	if (Z_TYPE(context->options) != IS_UNDEF) {
2226 		zval_ptr_dtor(&context->options);
2227 		ZVAL_UNDEF(&context->options);
2228 	}
2229 	if (context->notifier) {
2230 		php_stream_notification_free(context->notifier);
2231 		context->notifier = NULL;
2232 	}
2233 	efree(context);
2234 }
2235 
2236 PHPAPI php_stream_context *php_stream_context_alloc(void)
2237 {
2238 	php_stream_context *context;
2239 
2240 	context = ecalloc(1, sizeof(php_stream_context));
2241 	context->notifier = NULL;
2242 	array_init(&context->options);
2243 
2244 	context->res = zend_register_resource(context, php_le_stream_context());
2245 	return context;
2246 }
2247 
2248 PHPAPI php_stream_notifier *php_stream_notification_alloc(void)
2249 {
2250 	return ecalloc(1, sizeof(php_stream_notifier));
2251 }
2252 
2253 PHPAPI void php_stream_notification_free(php_stream_notifier *notifier)
2254 {
2255 	if (notifier->dtor) {
2256 		notifier->dtor(notifier);
2257 	}
2258 	efree(notifier);
2259 }
2260 
2261 PHPAPI zval *php_stream_context_get_option(php_stream_context *context,
2262 		const char *wrappername, const char *optionname)
2263 {
2264 	zval *wrapperhash;
2265 
2266 	if (NULL == (wrapperhash = zend_hash_str_find(Z_ARRVAL(context->options), wrappername, strlen(wrappername)))) {
2267 		return NULL;
2268 	}
2269 	return zend_hash_str_find(Z_ARRVAL_P(wrapperhash), optionname, strlen(optionname));
2270 }
2271 
2272 PHPAPI int php_stream_context_set_option(php_stream_context *context,
2273 		const char *wrappername, const char *optionname, zval *optionvalue)
2274 {
2275 	zval *wrapperhash;
2276 	zval category;
2277 
2278 	SEPARATE_ARRAY(&context->options);
2279 	wrapperhash = zend_hash_str_find(Z_ARRVAL(context->options), wrappername, strlen(wrappername));
2280 	if (NULL == wrapperhash) {
2281 		array_init(&category);
2282 		wrapperhash = zend_hash_str_update(Z_ARRVAL(context->options), (char*)wrappername, strlen(wrappername), &category);
2283 	}
2284 	ZVAL_DEREF(optionvalue);
2285 	Z_TRY_ADDREF_P(optionvalue);
2286 	SEPARATE_ARRAY(wrapperhash);
2287 	zend_hash_str_update(Z_ARRVAL_P(wrapperhash), optionname, strlen(optionname), optionvalue);
2288 	return SUCCESS;
2289 }
2290 /* }}} */
2291 
2292 /* {{{ php_stream_dirent_alphasort */
2293 PHPAPI int php_stream_dirent_alphasort(const zend_string **a, const zend_string **b)
2294 {
2295 	return strcoll(ZSTR_VAL(*a), ZSTR_VAL(*b));
2296 }
2297 /* }}} */
2298 
2299 /* {{{ php_stream_dirent_alphasortr */
2300 PHPAPI int php_stream_dirent_alphasortr(const zend_string **a, const zend_string **b)
2301 {
2302 	return strcoll(ZSTR_VAL(*b), ZSTR_VAL(*a));
2303 }
2304 /* }}} */
2305 
2306 /* {{{ php_stream_scandir */
2307 PHPAPI int _php_stream_scandir(const char *dirname, zend_string **namelist[], int flags, php_stream_context *context,
2308 			  int (*compare) (const zend_string **a, const zend_string **b))
2309 {
2310 	php_stream *stream;
2311 	php_stream_dirent sdp;
2312 	zend_string **vector = NULL;
2313 	unsigned int vector_size = 0;
2314 	unsigned int nfiles = 0;
2315 
2316 	if (!namelist) {
2317 		return FAILURE;
2318 	}
2319 
2320 	stream = php_stream_opendir(dirname, REPORT_ERRORS, context);
2321 	if (!stream) {
2322 		return FAILURE;
2323 	}
2324 
2325 	while (php_stream_readdir(stream, &sdp)) {
2326 		if (nfiles == vector_size) {
2327 			if (vector_size == 0) {
2328 				vector_size = 10;
2329 			} else {
2330 				if(vector_size*2 < vector_size) {
2331 					/* overflow */
2332 					php_stream_closedir(stream);
2333 					efree(vector);
2334 					return FAILURE;
2335 				}
2336 				vector_size *= 2;
2337 			}
2338 			vector = (zend_string **) safe_erealloc(vector, vector_size, sizeof(char *), 0);
2339 		}
2340 
2341 		vector[nfiles] = zend_string_init(sdp.d_name, strlen(sdp.d_name), 0);
2342 
2343 		nfiles++;
2344 		if(vector_size < 10 || nfiles == 0) {
2345 			/* overflow */
2346 			php_stream_closedir(stream);
2347 			efree(vector);
2348 			return FAILURE;
2349 		}
2350 	}
2351 	php_stream_closedir(stream);
2352 
2353 	*namelist = vector;
2354 
2355 	if (nfiles > 0 && compare) {
2356 		qsort(*namelist, nfiles, sizeof(zend_string *), (int(*)(const void *, const void *))compare);
2357 	}
2358 	return nfiles;
2359 }
2360 /* }}} */
2361