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