xref: /PHP-8.4/main/streams/streams.c (revision 81916758)
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 				ZEND_ASSERT(stream->position >= 0);
1386 				if (UNEXPECTED(offset > ZEND_LONG_MAX - stream->position)) {
1387 					offset = ZEND_LONG_MAX;
1388 				} else {
1389 					offset = stream->position + offset;
1390 				}
1391  				whence = SEEK_SET;
1392 				break;
1393 		}
1394 		ret = stream->ops->seek(stream, offset, whence, &stream->position);
1395 
1396 		if (((stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) || ret == 0) {
1397 			if (ret == 0) {
1398 				stream->eof = 0;
1399 			}
1400 
1401 			/* invalidate the buffer contents */
1402 			stream->readpos = stream->writepos = 0;
1403 
1404 			return ret;
1405 		}
1406 		/* else the stream has decided that it can't support seeking after all;
1407 		 * fall through to attempt emulation */
1408 	}
1409 
1410 	/* emulate forward moving seeks with reads */
1411 	if (whence == SEEK_CUR && offset >= 0) {
1412 		char tmp[1024];
1413 		ssize_t didread;
1414 		while (offset > 0) {
1415 			if ((didread = php_stream_read(stream, tmp, MIN(offset, sizeof(tmp)))) <= 0) {
1416 				return -1;
1417 			}
1418 			offset -= didread;
1419 		}
1420 		stream->eof = 0;
1421 		return 0;
1422 	}
1423 
1424 	php_error_docref(NULL, E_WARNING, "Stream does not support seeking");
1425 
1426 	return -1;
1427 }
1428 
_php_stream_set_option(php_stream * stream,int option,int value,void * ptrparam)1429 PHPAPI int _php_stream_set_option(php_stream *stream, int option, int value, void *ptrparam)
1430 {
1431 	int ret = PHP_STREAM_OPTION_RETURN_NOTIMPL;
1432 
1433 	if (stream->ops->set_option) {
1434 		ret = stream->ops->set_option(stream, option, value, ptrparam);
1435 	}
1436 
1437 	if (ret == PHP_STREAM_OPTION_RETURN_NOTIMPL) {
1438 		switch(option) {
1439 			case PHP_STREAM_OPTION_SET_CHUNK_SIZE:
1440 				/* XXX chunk size itself is of size_t, that might be ok or not for a particular case*/
1441 				ret = stream->chunk_size > INT_MAX ? INT_MAX : (int)stream->chunk_size;
1442 				stream->chunk_size = value;
1443 				return ret;
1444 
1445 			case PHP_STREAM_OPTION_READ_BUFFER:
1446 				/* try to match the buffer mode as best we can */
1447 				if (value == PHP_STREAM_BUFFER_NONE) {
1448 					stream->flags |= PHP_STREAM_FLAG_NO_BUFFER;
1449 				} else if (stream->flags & PHP_STREAM_FLAG_NO_BUFFER) {
1450 					stream->flags ^= PHP_STREAM_FLAG_NO_BUFFER;
1451 				}
1452 				ret = PHP_STREAM_OPTION_RETURN_OK;
1453 				break;
1454 
1455 			default:
1456 				;
1457 		}
1458 	}
1459 
1460 	return ret;
1461 }
1462 
_php_stream_sync(php_stream * stream,bool data_only)1463 PHPAPI int _php_stream_sync(php_stream *stream, bool data_only)
1464 {
1465 	int op = PHP_STREAM_SYNC_FSYNC;
1466 	if (data_only) {
1467 		op = PHP_STREAM_SYNC_FDSYNC;
1468 	}
1469 	return php_stream_set_option(stream, PHP_STREAM_OPTION_SYNC_API, op, NULL);
1470 }
1471 
_php_stream_truncate_set_size(php_stream * stream,size_t newsize)1472 PHPAPI int _php_stream_truncate_set_size(php_stream *stream, size_t newsize)
1473 {
1474 	return php_stream_set_option(stream, PHP_STREAM_OPTION_TRUNCATE_API, PHP_STREAM_TRUNCATE_SET_SIZE, &newsize);
1475 }
1476 
_php_stream_passthru(php_stream * stream STREAMS_DC)1477 PHPAPI ssize_t _php_stream_passthru(php_stream * stream STREAMS_DC)
1478 {
1479 	size_t bcount = 0;
1480 	char buf[8192];
1481 	ssize_t b;
1482 
1483 	if (php_stream_mmap_possible(stream)) {
1484 		char *p;
1485 		size_t mapped;
1486 
1487 		p = php_stream_mmap_range(stream, php_stream_tell(stream), PHP_STREAM_MMAP_ALL, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped);
1488 
1489 		if (p) {
1490 			do {
1491 				/* output functions return int, so pass in int max */
1492 				if (0 < (b = PHPWRITE(p + bcount, MIN(mapped - bcount, INT_MAX)))) {
1493 					bcount += b;
1494 				}
1495 			} while (b > 0 && mapped > bcount);
1496 
1497 			php_stream_mmap_unmap_ex(stream, mapped);
1498 
1499 			return bcount;
1500 		}
1501 	}
1502 
1503 	while ((b = php_stream_read(stream, buf, sizeof(buf))) > 0) {
1504 		PHPWRITE(buf, b);
1505 		bcount += b;
1506 	}
1507 
1508 	if (b < 0 && bcount == 0) {
1509 		return b;
1510 	}
1511 
1512 	return bcount;
1513 }
1514 
1515 
_php_stream_copy_to_mem(php_stream * src,size_t maxlen,int persistent STREAMS_DC)1516 PHPAPI zend_string *_php_stream_copy_to_mem(php_stream *src, size_t maxlen, int persistent STREAMS_DC)
1517 {
1518 	ssize_t ret = 0;
1519 	char *ptr;
1520 	size_t len = 0, buflen;
1521 	int step = CHUNK_SIZE;
1522 	int min_room = CHUNK_SIZE / 4;
1523 	php_stream_statbuf ssbuf;
1524 	zend_string *result;
1525 
1526 	if (maxlen == 0) {
1527 		return ZSTR_EMPTY_ALLOC();
1528 	}
1529 
1530 	if (maxlen == PHP_STREAM_COPY_ALL) {
1531 		maxlen = 0;
1532 	}
1533 
1534 	if (maxlen > 0 && maxlen < 4 * CHUNK_SIZE) {
1535 		result = zend_string_alloc(maxlen, persistent);
1536 		ptr = ZSTR_VAL(result);
1537 		while ((len < maxlen) && !php_stream_eof(src)) {
1538 			ret = php_stream_read(src, ptr, maxlen - len);
1539 			if (ret <= 0) {
1540 				// TODO: Propagate error?
1541 				break;
1542 			}
1543 			len += ret;
1544 			ptr += ret;
1545 		}
1546 		if (len) {
1547 			ZSTR_LEN(result) = len;
1548 			ZSTR_VAL(result)[len] = '\0';
1549 
1550 			/* Only truncate if the savings are large enough */
1551 			if (len < maxlen / 2) {
1552 				result = zend_string_truncate(result, len, persistent);
1553 			}
1554 		} else {
1555 			zend_string_free(result);
1556 			result = NULL;
1557 		}
1558 		return result;
1559 	}
1560 
1561 	/* avoid many reallocs by allocating a good-sized chunk to begin with, if
1562 	 * we can.  Note that the stream may be filtered, in which case the stat
1563 	 * result may be inaccurate, as the filter may inflate or deflate the
1564 	 * number of bytes that we can read.  In order to avoid an upsize followed
1565 	 * by a downsize of the buffer, overestimate by the step size (which is
1566 	 * 8K).  */
1567 	if (php_stream_stat(src, &ssbuf) == 0 && ssbuf.sb.st_size > 0) {
1568 		buflen = MAX(ssbuf.sb.st_size - src->position, 0) + step;
1569 		if (maxlen > 0 && buflen > maxlen) {
1570 			buflen = maxlen;
1571 		}
1572 	} else {
1573 		buflen = step;
1574 	}
1575 
1576 	result = zend_string_alloc(buflen, persistent);
1577 	ptr = ZSTR_VAL(result);
1578 
1579 	// TODO: Propagate error?
1580 	while ((ret = php_stream_read(src, ptr, buflen - len)) > 0) {
1581 		len += ret;
1582 		if (len + min_room >= buflen) {
1583 			if (maxlen == len) {
1584 				break;
1585 			}
1586 			if (maxlen > 0 && buflen + step > maxlen) {
1587 				buflen = maxlen;
1588 			} else {
1589 				buflen += step;
1590 			}
1591 			result = zend_string_extend(result, buflen, persistent);
1592 			ptr = ZSTR_VAL(result) + len;
1593 		} else {
1594 			ptr += ret;
1595 		}
1596 	}
1597 	if (len) {
1598 		result = zend_string_truncate(result, len, persistent);
1599 		ZSTR_VAL(result)[len] = '\0';
1600 	} else {
1601 		zend_string_free(result);
1602 		result = NULL;
1603 	}
1604 
1605 	return result;
1606 }
1607 
1608 /* 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)1609 PHPAPI zend_result _php_stream_copy_to_stream_ex(php_stream *src, php_stream *dest, size_t maxlen, size_t *len STREAMS_DC)
1610 {
1611 	char buf[CHUNK_SIZE];
1612 	size_t haveread = 0;
1613 	size_t towrite;
1614 	size_t dummy;
1615 
1616 	if (!len) {
1617 		len = &dummy;
1618 	}
1619 
1620 	if (maxlen == 0) {
1621 		*len = 0;
1622 		return SUCCESS;
1623 	}
1624 
1625 #ifdef HAVE_COPY_FILE_RANGE
1626 	if (php_stream_is(src, PHP_STREAM_IS_STDIO) &&
1627 			php_stream_is(dest, PHP_STREAM_IS_STDIO) &&
1628 			src->writepos == src->readpos) {
1629 		/* both php_stream instances are backed by a file descriptor, are not filtered and the
1630 		 * read buffer is empty: we can use copy_file_range() */
1631 		int src_fd, dest_fd, dest_open_flags = 0;
1632 
1633 		/* copy_file_range does not work with O_APPEND */
1634 		if (php_stream_cast(src, PHP_STREAM_AS_FD, (void*)&src_fd, 0) == SUCCESS &&
1635 				php_stream_cast(dest, PHP_STREAM_AS_FD, (void*)&dest_fd, 0) == SUCCESS &&
1636 				/* get dest open flags to check if the stream is open in append mode */
1637 				php_stream_parse_fopen_modes(dest->mode, &dest_open_flags) == SUCCESS &&
1638 				!(dest_open_flags & O_APPEND)) {
1639 
1640 			/* clamp to INT_MAX to avoid EOVERFLOW */
1641 			const size_t cfr_max = MIN(maxlen, (size_t)SSIZE_MAX);
1642 
1643 			/* copy_file_range() is a Linux-specific system call which allows efficient copying
1644 			 * between two file descriptors, eliminating the need to transfer data from the kernel
1645 			 * to userspace and back. For networking file systems like NFS and Ceph, it even
1646 			 * eliminates copying data to the client, and local filesystems like Btrfs and XFS can
1647 			 * create shared extents. */
1648 			ssize_t result = copy_file_range(src_fd, NULL, dest_fd, NULL, cfr_max, 0);
1649 			if (result > 0) {
1650 				size_t nbytes = (size_t)result;
1651 				haveread += nbytes;
1652 
1653 				src->position += nbytes;
1654 				dest->position += nbytes;
1655 
1656 				if ((maxlen != PHP_STREAM_COPY_ALL && nbytes == maxlen) || php_stream_eof(src)) {
1657 					/* the whole request was satisfied or end-of-file reached - done */
1658 					*len = haveread;
1659 					return SUCCESS;
1660 				}
1661 
1662 				/* there may be more data; continue copying using the fallback code below */
1663 			} else if (result == 0) {
1664 				/* end of file */
1665 				*len = haveread;
1666 				return SUCCESS;
1667 			} else if (result < 0) {
1668 				switch (errno) {
1669 					case EINVAL:
1670 						/* some formal error, e.g. overlapping file ranges */
1671 						break;
1672 
1673 					case EXDEV:
1674 						/* pre Linux 5.3 error */
1675 						break;
1676 
1677 					case ENOSYS:
1678 						/* not implemented by this Linux kernel */
1679 						break;
1680 
1681 					case EIO:
1682 						/* Some filesystems will cause failures if the max length is greater than the file length
1683 						 * in certain circumstances and configuration. In those cases the errno is EIO and we will
1684 						 * fall back to other methods. We cannot use stat to determine the file length upfront because
1685 						 * that is prone to races and outdated caching. */
1686 						break;
1687 
1688 					default:
1689 						/* unexpected I/O error - give up, no fallback */
1690 						*len = haveread;
1691 						return FAILURE;
1692 				}
1693 
1694 				/* fall back to classic copying */
1695 			}
1696 		}
1697 	}
1698 #endif // HAVE_COPY_FILE_RANGE
1699 
1700 	if (maxlen == PHP_STREAM_COPY_ALL) {
1701 		maxlen = 0;
1702 	}
1703 
1704 	if (php_stream_mmap_possible(src)) {
1705 		char *p;
1706 
1707 		do {
1708 			/* We must not modify maxlen here, because otherwise the file copy fallback below can fail */
1709 			size_t chunk_size, must_read, mapped;
1710 			if (maxlen == 0) {
1711 				/* Unlimited read */
1712 				must_read = chunk_size = PHP_STREAM_MMAP_MAX;
1713 			} else {
1714 				must_read = maxlen - haveread;
1715 				if (must_read >= PHP_STREAM_MMAP_MAX) {
1716 					chunk_size = PHP_STREAM_MMAP_MAX;
1717 				} else {
1718 					/* In case the length we still have to read from the file could be smaller than the file size,
1719 					 * chunk_size must not get bigger the size we're trying to read. */
1720 					chunk_size = must_read;
1721 				}
1722 			}
1723 
1724 			p = php_stream_mmap_range(src, php_stream_tell(src), chunk_size, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped);
1725 
1726 			if (p) {
1727 				ssize_t didwrite;
1728 
1729 				if (php_stream_seek(src, mapped, SEEK_CUR) != 0) {
1730 					php_stream_mmap_unmap(src);
1731 					break;
1732 				}
1733 
1734 				didwrite = php_stream_write(dest, p, mapped);
1735 				if (didwrite < 0) {
1736 					*len = haveread;
1737 					php_stream_mmap_unmap(src);
1738 					return FAILURE;
1739 				}
1740 
1741 				php_stream_mmap_unmap(src);
1742 
1743 				*len = haveread += didwrite;
1744 
1745 				/* we've got at least 1 byte to read
1746 				 * less than 1 is an error
1747 				 * AND read bytes match written */
1748 				if (mapped == 0 || mapped != didwrite) {
1749 					return FAILURE;
1750 				}
1751 				if (mapped < chunk_size) {
1752 					return SUCCESS;
1753 				}
1754 				/* If we're not reading as much as possible, so a bounded read */
1755 				if (maxlen != 0) {
1756 					must_read -= mapped;
1757 					if (must_read == 0) {
1758 						return SUCCESS;
1759 					}
1760 				}
1761 			}
1762 		} while (p);
1763 	}
1764 
1765 	while(1) {
1766 		size_t readchunk = sizeof(buf);
1767 		ssize_t didread;
1768 		char *writeptr;
1769 
1770 		if (maxlen && (maxlen - haveread) < readchunk) {
1771 			readchunk = maxlen - haveread;
1772 		}
1773 
1774 		didread = php_stream_read(src, buf, readchunk);
1775 		if (didread <= 0) {
1776 			*len = haveread;
1777 			return didread < 0 ? FAILURE : SUCCESS;
1778 		}
1779 
1780 		towrite = didread;
1781 		writeptr = buf;
1782 		haveread += didread;
1783 
1784 		while (towrite) {
1785 			ssize_t didwrite = php_stream_write(dest, writeptr, towrite);
1786 			if (didwrite <= 0) {
1787 				*len = haveread - (didread - towrite);
1788 				return FAILURE;
1789 			}
1790 
1791 			towrite -= didwrite;
1792 			writeptr += didwrite;
1793 		}
1794 
1795 		if (maxlen && maxlen == haveread) {
1796 			break;
1797 		}
1798 	}
1799 
1800 	*len = haveread;
1801 	return SUCCESS;
1802 }
1803 
1804 /* Returns the number of bytes moved.
1805  * Returns 1 when source len is 0.
1806  * Deprecated in favor of php_stream_copy_to_stream_ex() */
1807 ZEND_ATTRIBUTE_DEPRECATED
_php_stream_copy_to_stream(php_stream * src,php_stream * dest,size_t maxlen STREAMS_DC)1808 PHPAPI size_t _php_stream_copy_to_stream(php_stream *src, php_stream *dest, size_t maxlen STREAMS_DC)
1809 {
1810 	size_t len;
1811 	zend_result ret = _php_stream_copy_to_stream_ex(src, dest, maxlen, &len STREAMS_REL_CC);
1812 	if (ret == SUCCESS && len == 0 && maxlen != 0) {
1813 		return 1;
1814 	}
1815 	return len;
1816 }
1817 /* }}} */
1818 
1819 /* {{{ wrapper init and registration */
1820 
stream_resource_regular_dtor(zend_resource * rsrc)1821 static void stream_resource_regular_dtor(zend_resource *rsrc)
1822 {
1823 	php_stream *stream = (php_stream*)rsrc->ptr;
1824 	/* set the return value for pclose */
1825 	FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR);
1826 }
1827 
stream_resource_persistent_dtor(zend_resource * rsrc)1828 static void stream_resource_persistent_dtor(zend_resource *rsrc)
1829 {
1830 	php_stream *stream = (php_stream*)rsrc->ptr;
1831 	FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR);
1832 }
1833 
php_shutdown_stream_hashes(void)1834 void php_shutdown_stream_hashes(void)
1835 {
1836 	FG(user_stream_current_filename) = NULL;
1837 	if (FG(stream_wrappers)) {
1838 		zend_hash_destroy(FG(stream_wrappers));
1839 		efree(FG(stream_wrappers));
1840 		FG(stream_wrappers) = NULL;
1841 	}
1842 
1843 	if (FG(stream_filters)) {
1844 		zend_hash_destroy(FG(stream_filters));
1845 		efree(FG(stream_filters));
1846 		FG(stream_filters) = NULL;
1847 	}
1848 
1849 	if (FG(wrapper_errors)) {
1850 		zend_hash_destroy(FG(wrapper_errors));
1851 		efree(FG(wrapper_errors));
1852 		FG(wrapper_errors) = NULL;
1853 	}
1854 }
1855 
php_init_stream_wrappers(int module_number)1856 int php_init_stream_wrappers(int module_number)
1857 {
1858 	le_stream = zend_register_list_destructors_ex(stream_resource_regular_dtor, NULL, "stream", module_number);
1859 	le_pstream = zend_register_list_destructors_ex(NULL, stream_resource_persistent_dtor, "persistent stream", module_number);
1860 
1861 	/* Filters are cleaned up by the streams they're attached to */
1862 	le_stream_filter = zend_register_list_destructors_ex(NULL, NULL, "stream filter", module_number);
1863 
1864 	zend_hash_init(&url_stream_wrappers_hash, 8, NULL, NULL, 1);
1865 	zend_hash_init(php_get_stream_filters_hash_global(), 8, NULL, NULL, 1);
1866 	zend_hash_init(php_stream_xport_get_hash(), 8, NULL, NULL, 1);
1867 
1868 	return (php_stream_xport_register("tcp", php_stream_generic_socket_factory) == SUCCESS
1869 			&&
1870 			php_stream_xport_register("udp", php_stream_generic_socket_factory) == SUCCESS
1871 #if defined(AF_UNIX) && !(defined(PHP_WIN32) || defined(__riscos__))
1872 			&&
1873 			php_stream_xport_register("unix", php_stream_generic_socket_factory) == SUCCESS
1874 			&&
1875 			php_stream_xport_register("udg", php_stream_generic_socket_factory) == SUCCESS
1876 #endif
1877 		) ? SUCCESS : FAILURE;
1878 }
1879 
php_shutdown_stream_wrappers(int module_number)1880 void php_shutdown_stream_wrappers(int module_number)
1881 {
1882 	zend_hash_destroy(&url_stream_wrappers_hash);
1883 	zend_hash_destroy(php_get_stream_filters_hash_global());
1884 	zend_hash_destroy(php_stream_xport_get_hash());
1885 }
1886 
1887 /* Validate protocol scheme names during registration
1888  * Must conform to /^[a-zA-Z0-9+.-]+$/
1889  */
php_stream_wrapper_scheme_validate(const char * protocol,unsigned int protocol_len)1890 static inline zend_result php_stream_wrapper_scheme_validate(const char *protocol, unsigned int protocol_len)
1891 {
1892 	unsigned int i;
1893 
1894 	for(i = 0; i < protocol_len; i++) {
1895 		if (!isalnum((int)protocol[i]) &&
1896 			protocol[i] != '+' &&
1897 			protocol[i] != '-' &&
1898 			protocol[i] != '.') {
1899 			return FAILURE;
1900 		}
1901 	}
1902 
1903 	return SUCCESS;
1904 }
1905 
1906 /* API for registering GLOBAL wrappers */
php_register_url_stream_wrapper(const char * protocol,const php_stream_wrapper * wrapper)1907 PHPAPI zend_result php_register_url_stream_wrapper(const char *protocol, const php_stream_wrapper *wrapper)
1908 {
1909 	size_t protocol_len = strlen(protocol);
1910 	zend_result ret;
1911 	zend_string *str;
1912 
1913 	if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) {
1914 		return FAILURE;
1915 	}
1916 
1917 	str = zend_string_init_interned(protocol, protocol_len, 1);
1918 	ret = zend_hash_add_ptr(&url_stream_wrappers_hash, str, (void*)wrapper) ? SUCCESS : FAILURE;
1919 	zend_string_release_ex(str, 1);
1920 	return ret;
1921 }
1922 
php_unregister_url_stream_wrapper(const char * protocol)1923 PHPAPI zend_result php_unregister_url_stream_wrapper(const char *protocol)
1924 {
1925 	return zend_hash_str_del(&url_stream_wrappers_hash, protocol, strlen(protocol));
1926 }
1927 
clone_wrapper_hash(void)1928 static void clone_wrapper_hash(void)
1929 {
1930 	ALLOC_HASHTABLE(FG(stream_wrappers));
1931 	zend_hash_init(FG(stream_wrappers), zend_hash_num_elements(&url_stream_wrappers_hash), NULL, NULL, 0);
1932 	zend_hash_copy(FG(stream_wrappers), &url_stream_wrappers_hash, NULL);
1933 }
1934 
1935 /* API for registering VOLATILE wrappers */
php_register_url_stream_wrapper_volatile(zend_string * protocol,php_stream_wrapper * wrapper)1936 PHPAPI zend_result php_register_url_stream_wrapper_volatile(zend_string *protocol, php_stream_wrapper *wrapper)
1937 {
1938 	if (php_stream_wrapper_scheme_validate(ZSTR_VAL(protocol), ZSTR_LEN(protocol)) == FAILURE) {
1939 		return FAILURE;
1940 	}
1941 
1942 	if (!FG(stream_wrappers)) {
1943 		clone_wrapper_hash();
1944 	}
1945 
1946 	return zend_hash_add_ptr(FG(stream_wrappers), protocol, wrapper) ? SUCCESS : FAILURE;
1947 }
1948 
php_unregister_url_stream_wrapper_volatile(zend_string * protocol)1949 PHPAPI zend_result php_unregister_url_stream_wrapper_volatile(zend_string *protocol)
1950 {
1951 	if (!FG(stream_wrappers)) {
1952 		clone_wrapper_hash();
1953 	}
1954 
1955 	return zend_hash_del(FG(stream_wrappers), protocol);
1956 }
1957 /* }}} */
1958 
1959 /* {{{ php_stream_locate_url_wrapper */
php_stream_locate_url_wrapper(const char * path,const char ** path_for_open,int options)1960 PHPAPI php_stream_wrapper *php_stream_locate_url_wrapper(const char *path, const char **path_for_open, int options)
1961 {
1962 	HashTable *wrapper_hash = (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash);
1963 	php_stream_wrapper *wrapper = NULL;
1964 	const char *p, *protocol = NULL;
1965 	size_t n = 0;
1966 
1967 	if (path_for_open) {
1968 		*path_for_open = (char*)path;
1969 	}
1970 
1971 	if (options & IGNORE_URL) {
1972 		return (php_stream_wrapper*)((options & STREAM_LOCATE_WRAPPERS_ONLY) ? NULL : &php_plain_files_wrapper);
1973 	}
1974 
1975 	for (p = path; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++) {
1976 		n++;
1977 	}
1978 
1979 	if ((*p == ':') && (n > 1) && (!strncmp("//", p+1, 2) || (n == 4 && !memcmp("data:", path, 5)))) {
1980 		protocol = path;
1981 	}
1982 
1983 	if (protocol) {
1984 		if (NULL == (wrapper = zend_hash_str_find_ptr(wrapper_hash, protocol, n))) {
1985 			char *tmp = estrndup(protocol, n);
1986 
1987 			zend_str_tolower(tmp, n);
1988 			if (NULL == (wrapper = zend_hash_str_find_ptr(wrapper_hash, tmp, n))) {
1989 				char wrapper_name[32];
1990 
1991 				if (n >= sizeof(wrapper_name)) {
1992 					n = sizeof(wrapper_name) - 1;
1993 				}
1994 				PHP_STRLCPY(wrapper_name, protocol, sizeof(wrapper_name), n);
1995 
1996 				php_error_docref(NULL, E_WARNING, "Unable to find the wrapper \"%s\" - did you forget to enable it when you configured PHP?", wrapper_name);
1997 
1998 				wrapper = NULL;
1999 				protocol = NULL;
2000 			}
2001 			efree(tmp);
2002 		}
2003 	}
2004 	/* TODO: curl based streams probably support file:// properly */
2005 	if (!protocol || !strncasecmp(protocol, "file", n))	{
2006 		/* fall back on regular file access */
2007 		php_stream_wrapper *plain_files_wrapper = (php_stream_wrapper*)&php_plain_files_wrapper;
2008 
2009 		if (protocol) {
2010 			int localhost = 0;
2011 
2012 			if (!strncasecmp(path, "file://localhost/", 17)) {
2013 				localhost = 1;
2014 			}
2015 
2016 #ifdef PHP_WIN32
2017 			if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/' && path[n+4] != ':')	{
2018 #else
2019 			if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/') {
2020 #endif
2021 				if (options & REPORT_ERRORS) {
2022 					php_error_docref(NULL, E_WARNING, "Remote host file access not supported, %s", path);
2023 				}
2024 				return NULL;
2025 			}
2026 
2027 			if (path_for_open) {
2028 				/* skip past protocol and :/, but handle windows correctly */
2029 				*path_for_open = (char*)path + n + 1;
2030 				if (localhost == 1) {
2031 					(*path_for_open) += 11;
2032 				}
2033 				while (*(++*path_for_open)=='/') {
2034 					/* intentionally empty */
2035 				}
2036 #ifdef PHP_WIN32
2037 				if (*(*path_for_open + 1) != ':')
2038 #endif
2039 					(*path_for_open)--;
2040 			}
2041 		}
2042 
2043 		if (options & STREAM_LOCATE_WRAPPERS_ONLY) {
2044 			return NULL;
2045 		}
2046 
2047 		if (FG(stream_wrappers)) {
2048 		/* The file:// wrapper may have been disabled/overridden */
2049 
2050 			if (wrapper) {
2051 				/* It was found so go ahead and provide it */
2052 				return wrapper;
2053 			}
2054 
2055 			/* Check again, the original check might have not known the protocol name */
2056 			if ((wrapper = zend_hash_find_ex_ptr(wrapper_hash, ZSTR_KNOWN(ZEND_STR_FILE), 1)) != NULL) {
2057 				return wrapper;
2058 			}
2059 
2060 			if (options & REPORT_ERRORS) {
2061 				php_error_docref(NULL, E_WARNING, "file:// wrapper is disabled in the server configuration");
2062 			}
2063 			return NULL;
2064 		}
2065 
2066 		return plain_files_wrapper;
2067 	}
2068 
2069 	if (wrapper && wrapper->is_url &&
2070 	    (options & STREAM_DISABLE_URL_PROTECTION) == 0 &&
2071 	    (!PG(allow_url_fopen) ||
2072 	     (((options & STREAM_OPEN_FOR_INCLUDE) ||
2073 	       PG(in_user_include)) && !PG(allow_url_include)))) {
2074 		if (options & REPORT_ERRORS) {
2075 			/* protocol[n] probably isn't '\0' */
2076 			if (!PG(allow_url_fopen)) {
2077 				php_error_docref(NULL, E_WARNING, "%.*s:// wrapper is disabled in the server configuration by allow_url_fopen=0", (int)n, protocol);
2078 			} else {
2079 				php_error_docref(NULL, E_WARNING, "%.*s:// wrapper is disabled in the server configuration by allow_url_include=0", (int)n, protocol);
2080 			}
2081 		}
2082 		return NULL;
2083 	}
2084 
2085 	return wrapper;
2086 }
2087 /* }}} */
2088 
2089 /* {{{ _php_stream_mkdir */
2090 PHPAPI int _php_stream_mkdir(const char *path, int mode, int options, php_stream_context *context)
2091 {
2092 	php_stream_wrapper *wrapper = NULL;
2093 
2094 	wrapper = php_stream_locate_url_wrapper(path, NULL, 0);
2095 	if (!wrapper || !wrapper->wops || !wrapper->wops->stream_mkdir) {
2096 		return 0;
2097 	}
2098 
2099 	return wrapper->wops->stream_mkdir(wrapper, path, mode, options, context);
2100 }
2101 /* }}} */
2102 
2103 /* {{{ _php_stream_rmdir */
2104 PHPAPI int _php_stream_rmdir(const char *path, int options, php_stream_context *context)
2105 {
2106 	php_stream_wrapper *wrapper = NULL;
2107 
2108 	wrapper = php_stream_locate_url_wrapper(path, NULL, 0);
2109 	if (!wrapper || !wrapper->wops || !wrapper->wops->stream_rmdir) {
2110 		return 0;
2111 	}
2112 
2113 	return wrapper->wops->stream_rmdir(wrapper, path, options, context);
2114 }
2115 /* }}} */
2116 
2117 /* {{{ _php_stream_stat_path */
2118 PHPAPI int _php_stream_stat_path(const char *path, int flags, php_stream_statbuf *ssb, php_stream_context *context)
2119 {
2120 	php_stream_wrapper *wrapper = NULL;
2121 	const char *path_to_open = path;
2122 
2123 	memset(ssb, 0, sizeof(*ssb));
2124 
2125 	wrapper = php_stream_locate_url_wrapper(path, &path_to_open, 0);
2126 	if (wrapper && wrapper->wops->url_stat) {
2127 		return wrapper->wops->url_stat(wrapper, path_to_open, flags, ssb, context);
2128 	}
2129 	return -1;
2130 }
2131 /* }}} */
2132 
2133 /* {{{ php_stream_opendir */
2134 PHPAPI php_stream *_php_stream_opendir(const char *path, int options,
2135 		php_stream_context *context STREAMS_DC)
2136 {
2137 	php_stream *stream = NULL;
2138 	php_stream_wrapper *wrapper = NULL;
2139 	const char *path_to_open;
2140 
2141 	if (!path || !*path) {
2142 		return NULL;
2143 	}
2144 
2145 	path_to_open = path;
2146 
2147 	wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options);
2148 
2149 	if (wrapper && wrapper->wops->dir_opener) {
2150 		stream = wrapper->wops->dir_opener(wrapper,
2151 				path_to_open, "r", options & ~REPORT_ERRORS, NULL,
2152 				context STREAMS_REL_CC);
2153 
2154 		if (stream) {
2155 			stream->wrapper = wrapper;
2156 			stream->flags |= PHP_STREAM_FLAG_NO_BUFFER | PHP_STREAM_FLAG_IS_DIR;
2157 		}
2158 	} else if (wrapper) {
2159 		php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS, "not implemented");
2160 	}
2161 	if (stream == NULL && (options & REPORT_ERRORS)) {
2162 		php_stream_display_wrapper_errors(wrapper, path, "Failed to open directory");
2163 	}
2164 	php_stream_tidy_wrapper_error_log(wrapper);
2165 
2166 	return stream;
2167 }
2168 /* }}} */
2169 
2170 /* {{{ _php_stream_readdir */
2171 PHPAPI php_stream_dirent *_php_stream_readdir(php_stream *dirstream, php_stream_dirent *ent)
2172 {
2173 
2174 	if (sizeof(php_stream_dirent) == php_stream_read(dirstream, (char*)ent, sizeof(php_stream_dirent))) {
2175 		return ent;
2176 	}
2177 
2178 	return NULL;
2179 }
2180 /* }}} */
2181 
2182 /* {{{ php_stream_open_wrapper_ex */
2183 PHPAPI php_stream *_php_stream_open_wrapper_ex(const char *path, const char *mode, int options,
2184 		zend_string **opened_path, php_stream_context *context STREAMS_DC)
2185 {
2186 	php_stream *stream = NULL;
2187 	php_stream_wrapper *wrapper = NULL;
2188 	const char *path_to_open;
2189 	int persistent = options & STREAM_OPEN_PERSISTENT;
2190 	zend_string *path_str = NULL;
2191 	zend_string *resolved_path = NULL;
2192 	char *copy_of_path = NULL;
2193 
2194 	if (opened_path) {
2195 		if (options & STREAM_OPEN_FOR_ZEND_STREAM) {
2196 			path_str = *opened_path;
2197 		}
2198 		*opened_path = NULL;
2199 	}
2200 
2201 	if (!path || !*path) {
2202 		zend_value_error("Path must not be empty");
2203 		return NULL;
2204 	}
2205 
2206 	if (options & USE_PATH) {
2207 		if (path_str) {
2208 			resolved_path = zend_resolve_path(path_str);
2209 		} else {
2210 			resolved_path = php_resolve_path(path, strlen(path), PG(include_path));
2211 		}
2212 		if (resolved_path) {
2213 			path = ZSTR_VAL(resolved_path);
2214 			/* we've found this file, don't re-check include_path or run realpath */
2215 			options |= STREAM_ASSUME_REALPATH;
2216 			options &= ~USE_PATH;
2217 		}
2218 		if (EG(exception)) {
2219 			if (resolved_path) {
2220 				zend_string_release_ex(resolved_path, false);
2221 			}
2222 			return NULL;
2223 		}
2224 	}
2225 
2226 	path_to_open = path;
2227 
2228 	wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options);
2229 	if ((options & STREAM_USE_URL) && (!wrapper || !wrapper->is_url)) {
2230 		php_error_docref(NULL, E_WARNING, "This function may only be used against URLs");
2231 		if (resolved_path) {
2232 			zend_string_release_ex(resolved_path, 0);
2233 		}
2234 		return NULL;
2235 	}
2236 
2237 	if (wrapper) {
2238 		if (!wrapper->wops->stream_opener) {
2239 			php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS,
2240 					"wrapper does not support stream open");
2241 		} else {
2242 			stream = wrapper->wops->stream_opener(wrapper,
2243 				path_to_open, mode, options & ~REPORT_ERRORS,
2244 				opened_path, context STREAMS_REL_CC);
2245 		}
2246 
2247 		/* if the caller asked for a persistent stream but the wrapper did not
2248 		 * return one, force an error here */
2249 		if (stream && (options & STREAM_OPEN_PERSISTENT) && !stream->is_persistent) {
2250 			php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS,
2251 					"wrapper does not support persistent streams");
2252 			php_stream_close(stream);
2253 			stream = NULL;
2254 		}
2255 
2256 		if (stream) {
2257 			stream->wrapper = wrapper;
2258 		}
2259 	}
2260 
2261 	if (stream) {
2262 		if (opened_path && !*opened_path && resolved_path) {
2263 			*opened_path = resolved_path;
2264 			resolved_path = NULL;
2265 		}
2266 		if (stream->orig_path) {
2267 			pefree(stream->orig_path, persistent);
2268 		}
2269 		copy_of_path = pestrdup(path, persistent);
2270 		stream->orig_path = copy_of_path;
2271 #if ZEND_DEBUG
2272 		stream->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename;
2273 		stream->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno;
2274 #endif
2275 	}
2276 
2277 	if (stream != NULL && (options & STREAM_MUST_SEEK)) {
2278 		php_stream *newstream;
2279 
2280 		switch(php_stream_make_seekable_rel(stream, &newstream,
2281 					(options & STREAM_WILL_CAST)
2282 						? PHP_STREAM_PREFER_STDIO : PHP_STREAM_NO_PREFERENCE)) {
2283 			case PHP_STREAM_UNCHANGED:
2284 				if (resolved_path) {
2285 					zend_string_release_ex(resolved_path, 0);
2286 				}
2287 				return stream;
2288 			case PHP_STREAM_RELEASED:
2289 				if (newstream->orig_path) {
2290 					pefree(newstream->orig_path, persistent);
2291 				}
2292 				newstream->orig_path = pestrdup(path, persistent);
2293 				if (resolved_path) {
2294 					zend_string_release_ex(resolved_path, 0);
2295 				}
2296 				return newstream;
2297 			default:
2298 				php_stream_close(stream);
2299 				stream = NULL;
2300 				if (options & REPORT_ERRORS) {
2301 					char *tmp = estrdup(path);
2302 					php_strip_url_passwd(tmp);
2303 					php_error_docref1(NULL, tmp, E_WARNING, "could not make seekable - %s",
2304 							tmp);
2305 					efree(tmp);
2306 
2307 					options &= ~REPORT_ERRORS;
2308 				}
2309 		}
2310 	}
2311 
2312 	if (stream && stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && strchr(mode, 'a') && stream->position == 0) {
2313 		zend_off_t newpos = 0;
2314 
2315 		/* if opened for append, we need to revise our idea of the initial file position */
2316 		if (0 == stream->ops->seek(stream, 0, SEEK_CUR, &newpos)) {
2317 			stream->position = newpos;
2318 		}
2319 	}
2320 
2321 	if (stream == NULL && (options & REPORT_ERRORS)) {
2322 		php_stream_display_wrapper_errors(wrapper, path, "Failed to open stream");
2323 		if (opened_path && *opened_path) {
2324 			zend_string_release_ex(*opened_path, 0);
2325 			*opened_path = NULL;
2326 		}
2327 	}
2328 	php_stream_tidy_wrapper_error_log(wrapper);
2329 #if ZEND_DEBUG
2330 	if (stream == NULL && copy_of_path != NULL) {
2331 		pefree(copy_of_path, persistent);
2332 	}
2333 #endif
2334 	if (resolved_path) {
2335 		zend_string_release_ex(resolved_path, 0);
2336 	}
2337 	return stream;
2338 }
2339 /* }}} */
2340 
2341 /* {{{ context API */
2342 PHPAPI php_stream_context *php_stream_context_set(php_stream *stream, php_stream_context *context)
2343 {
2344 	php_stream_context *oldcontext = PHP_STREAM_CONTEXT(stream);
2345 
2346 	if (context) {
2347 		stream->ctx = context->res;
2348 		GC_ADDREF(context->res);
2349 	} else {
2350 		stream->ctx = NULL;
2351 	}
2352 	if (oldcontext) {
2353 		zend_list_delete(oldcontext->res);
2354 	}
2355 
2356 	return oldcontext;
2357 }
2358 
2359 PHPAPI void php_stream_notification_notify(php_stream_context *context, int notifycode, int severity,
2360 		char *xmsg, int xcode, size_t bytes_sofar, size_t bytes_max, void * ptr)
2361 {
2362 	if (context && context->notifier)
2363 		context->notifier->func(context, notifycode, severity, xmsg, xcode, bytes_sofar, bytes_max, ptr);
2364 }
2365 
2366 PHPAPI void php_stream_context_free(php_stream_context *context)
2367 {
2368 	if (Z_TYPE(context->options) != IS_UNDEF) {
2369 		zval_ptr_dtor(&context->options);
2370 		ZVAL_UNDEF(&context->options);
2371 	}
2372 	if (context->notifier) {
2373 		php_stream_notification_free(context->notifier);
2374 		context->notifier = NULL;
2375 	}
2376 	efree(context);
2377 }
2378 
2379 PHPAPI php_stream_context *php_stream_context_alloc(void)
2380 {
2381 	php_stream_context *context;
2382 
2383 	context = ecalloc(1, sizeof(php_stream_context));
2384 	array_init(&context->options);
2385 
2386 	context->res = zend_register_resource(context, php_le_stream_context());
2387 	return context;
2388 }
2389 
2390 PHPAPI php_stream_notifier *php_stream_notification_alloc(void)
2391 {
2392 	return ecalloc(1, sizeof(php_stream_notifier));
2393 }
2394 
2395 PHPAPI void php_stream_notification_free(php_stream_notifier *notifier)
2396 {
2397 	if (notifier->dtor) {
2398 		notifier->dtor(notifier);
2399 	}
2400 	efree(notifier);
2401 }
2402 
2403 PHPAPI zval *php_stream_context_get_option(php_stream_context *context,
2404 		const char *wrappername, const char *optionname)
2405 {
2406 	zval *wrapperhash;
2407 
2408 	if (NULL == (wrapperhash = zend_hash_str_find(Z_ARRVAL(context->options), wrappername, strlen(wrappername)))) {
2409 		return NULL;
2410 	}
2411 	return zend_hash_str_find(Z_ARRVAL_P(wrapperhash), optionname, strlen(optionname));
2412 }
2413 
2414 PHPAPI void php_stream_context_set_option(php_stream_context *context,
2415 		const char *wrappername, const char *optionname, zval *optionvalue)
2416 {
2417 	zval *wrapperhash;
2418 	zval category;
2419 
2420 	SEPARATE_ARRAY(&context->options);
2421 	wrapperhash = zend_hash_str_find(Z_ARRVAL(context->options), wrappername, strlen(wrappername));
2422 	if (NULL == wrapperhash) {
2423 		array_init(&category);
2424 		wrapperhash = zend_hash_str_update(Z_ARRVAL(context->options), (char*)wrappername, strlen(wrappername), &category);
2425 	}
2426 	ZVAL_DEREF(optionvalue);
2427 	Z_TRY_ADDREF_P(optionvalue);
2428 	SEPARATE_ARRAY(wrapperhash);
2429 	zend_hash_str_update(Z_ARRVAL_P(wrapperhash), optionname, strlen(optionname), optionvalue);
2430 }
2431 /* }}} */
2432 
2433 /* {{{ php_stream_dirent_alphasort */
2434 PHPAPI int php_stream_dirent_alphasort(const zend_string **a, const zend_string **b)
2435 {
2436 	return strcoll(ZSTR_VAL(*a), ZSTR_VAL(*b));
2437 }
2438 /* }}} */
2439 
2440 /* {{{ php_stream_dirent_alphasortr */
2441 PHPAPI int php_stream_dirent_alphasortr(const zend_string **a, const zend_string **b)
2442 {
2443 	return strcoll(ZSTR_VAL(*b), ZSTR_VAL(*a));
2444 }
2445 /* }}} */
2446 
2447 /* {{{ php_stream_scandir */
2448 PHPAPI int _php_stream_scandir(const char *dirname, zend_string **namelist[], int flags, php_stream_context *context,
2449 			  int (*compare) (const zend_string **a, const zend_string **b))
2450 {
2451 	php_stream *stream;
2452 	php_stream_dirent sdp;
2453 	zend_string **vector = NULL;
2454 	unsigned int vector_size = 0;
2455 	unsigned int nfiles = 0;
2456 
2457 	if (!namelist) {
2458 		return -1;
2459 	}
2460 
2461 	stream = php_stream_opendir(dirname, REPORT_ERRORS, context);
2462 	if (!stream) {
2463 		return -1;
2464 	}
2465 
2466 	while (php_stream_readdir(stream, &sdp)) {
2467 		if (nfiles == vector_size) {
2468 			if (vector_size == 0) {
2469 				vector_size = 10;
2470 			} else {
2471 				if(vector_size*2 < vector_size) {
2472 					/* overflow */
2473 					php_stream_closedir(stream);
2474 					efree(vector);
2475 					return -1;
2476 				}
2477 				vector_size *= 2;
2478 			}
2479 			vector = (zend_string **) safe_erealloc(vector, vector_size, sizeof(char *), 0);
2480 		}
2481 
2482 		vector[nfiles] = zend_string_init(sdp.d_name, strlen(sdp.d_name), 0);
2483 
2484 		nfiles++;
2485 		if(vector_size < 10 || nfiles == 0) {
2486 			/* overflow */
2487 			php_stream_closedir(stream);
2488 			efree(vector);
2489 			return -1;
2490 		}
2491 	}
2492 	php_stream_closedir(stream);
2493 
2494 	*namelist = vector;
2495 
2496 	if (nfiles > 0 && compare) {
2497 		qsort(*namelist, nfiles, sizeof(zend_string *), (int(*)(const void *, const void *))compare);
2498 	}
2499 	return nfiles;
2500 }
2501 /* }}} */
2502