xref: /PHP-8.2/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 				Lets 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 	if (stream->readfilters.head) {
546 		size_t to_read_now = MIN(size, stream->chunk_size);
547 		char *chunk_buf;
548 		php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL };
549 		php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap;
550 
551 		/* allocate a buffer for reading chunks */
552 		chunk_buf = emalloc(stream->chunk_size);
553 
554 		while (!stream->eof && (stream->writepos - stream->readpos < (zend_off_t)to_read_now)) {
555 			ssize_t justread = 0;
556 			int flags;
557 			php_stream_bucket *bucket;
558 			php_stream_filter_status_t status = PSFS_ERR_FATAL;
559 			php_stream_filter *filter;
560 
561 			/* read a chunk into a bucket */
562 			justread = stream->ops->read(stream, chunk_buf, stream->chunk_size);
563 			if (justread < 0 && stream->writepos == stream->readpos) {
564 				efree(chunk_buf);
565 				return FAILURE;
566 			} else if (justread > 0) {
567 				bucket = php_stream_bucket_new(stream, chunk_buf, justread, 0, 0);
568 
569 				/* after this call, bucket is owned by the brigade */
570 				php_stream_bucket_append(brig_inp, bucket);
571 
572 				flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_NORMAL;
573 			} else {
574 				flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC;
575 			}
576 
577 			/* wind the handle... */
578 			for (filter = stream->readfilters.head; filter; filter = filter->next) {
579 				status = filter->fops->filter(stream, filter, brig_inp, brig_outp, NULL, flags);
580 
581 				if (status != PSFS_PASS_ON) {
582 					break;
583 				}
584 
585 				/* brig_out becomes brig_in.
586 				 * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets
587 				 * to its own brigade */
588 				brig_swap = brig_inp;
589 				brig_inp = brig_outp;
590 				brig_outp = brig_swap;
591 				memset(brig_outp, 0, sizeof(*brig_outp));
592 			}
593 
594 			switch (status) {
595 				case PSFS_PASS_ON:
596 					/* we get here when the last filter in the chain has data to pass on.
597 					 * in this situation, we are passing the brig_in brigade into the
598 					 * stream read buffer */
599 					while (brig_inp->head) {
600 						bucket = brig_inp->head;
601 						/* reduce buffer memory consumption if possible, to avoid a realloc */
602 						if (stream->readbuf && stream->readbuflen - stream->writepos < bucket->buflen) {
603 							if (stream->writepos > stream->readpos) {
604 								memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->writepos - stream->readpos);
605 							}
606 							stream->writepos -= stream->readpos;
607 							stream->readpos = 0;
608 						}
609 						/* grow buffer to hold this bucket */
610 						if (stream->readbuflen - stream->writepos < bucket->buflen) {
611 							stream->readbuflen += bucket->buflen;
612 							stream->readbuf = perealloc(stream->readbuf, stream->readbuflen,
613 									stream->is_persistent);
614 						}
615 						if (bucket->buflen) {
616 							memcpy(stream->readbuf + stream->writepos, bucket->buf, bucket->buflen);
617 						}
618 						stream->writepos += bucket->buflen;
619 
620 						php_stream_bucket_unlink(bucket);
621 						php_stream_bucket_delref(bucket);
622 					}
623 					break;
624 
625 				case PSFS_FEED_ME:
626 					/* when a filter needs feeding, there is no brig_out to deal with.
627 					 * we simply continue the loop; if the caller needs more data,
628 					 * we will read again, otherwise out job is done here */
629 					break;
630 
631 				case PSFS_ERR_FATAL:
632 					/* some fatal error. Theoretically, the stream is borked, so all
633 					 * further reads should fail. */
634 					stream->eof = 1;
635 					/* free all data left in brigades */
636 					while ((bucket = brig_inp->head)) {
637 						/* Remove unconsumed buckets from the input brigade */
638 						php_stream_bucket_unlink(bucket);
639 						php_stream_bucket_delref(bucket);
640 					}
641 					while ((bucket = brig_outp->head)) {
642 						/* Remove unconsumed buckets from the output brigade */
643 						php_stream_bucket_unlink(bucket);
644 						php_stream_bucket_delref(bucket);
645 					}
646 					efree(chunk_buf);
647 					return FAILURE;
648 			}
649 
650 			if (justread <= 0) {
651 				break;
652 			}
653 		}
654 
655 		efree(chunk_buf);
656 		return SUCCESS;
657 
658 	} else {
659 		/* is there enough data in the buffer ? */
660 		if (stream->writepos - stream->readpos < (zend_off_t)size) {
661 			ssize_t justread = 0;
662 
663 			/* reduce buffer memory consumption if possible, to avoid a realloc */
664 			if (stream->readbuf && stream->readbuflen - stream->writepos < stream->chunk_size) {
665 				if (stream->writepos > stream->readpos) {
666 					memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->writepos - stream->readpos);
667 				}
668 				stream->writepos -= stream->readpos;
669 				stream->readpos = 0;
670 			}
671 
672 			/* grow the buffer if required
673 			 * TODO: this can fail for persistent streams */
674 			if (stream->readbuflen - stream->writepos < stream->chunk_size) {
675 				stream->readbuflen += stream->chunk_size;
676 				stream->readbuf = perealloc(stream->readbuf, stream->readbuflen,
677 						stream->is_persistent);
678 			}
679 
680 			justread = stream->ops->read(stream, (char*)stream->readbuf + stream->writepos,
681 					stream->readbuflen - stream->writepos
682 					);
683 			if (justread < 0) {
684 				return FAILURE;
685 			}
686 			stream->writepos += justread;
687 		}
688 		return SUCCESS;
689 	}
690 }
691 
_php_stream_read(php_stream * stream,char * buf,size_t size)692 PHPAPI ssize_t _php_stream_read(php_stream *stream, char *buf, size_t size)
693 {
694 	ssize_t toread = 0, didread = 0;
695 
696 	while (size > 0) {
697 
698 		/* take from the read buffer first.
699 		 * It is possible that a buffered stream was switched to non-buffered, so we
700 		 * drain the remainder of the buffer before using the "raw" read mode for
701 		 * the excess */
702 		if (stream->writepos > stream->readpos) {
703 
704 			toread = stream->writepos - stream->readpos;
705 			if (toread > size) {
706 				toread = size;
707 			}
708 
709 			memcpy(buf, stream->readbuf + stream->readpos, toread);
710 			stream->readpos += toread;
711 			size -= toread;
712 			buf += toread;
713 			didread += toread;
714 		}
715 
716 		/* ignore eof here; the underlying state might have changed */
717 		if (size == 0) {
718 			break;
719 		}
720 
721 		if (!stream->readfilters.head && ((stream->flags & PHP_STREAM_FLAG_NO_BUFFER) || stream->chunk_size == 1)) {
722 			toread = stream->ops->read(stream, buf, size);
723 			if (toread < 0) {
724 				/* Report an error if the read failed and we did not read any data
725 				 * before that. Otherwise return the data we did read. */
726 				if (didread == 0) {
727 					return toread;
728 				}
729 				break;
730 			}
731 		} else {
732 			if (php_stream_fill_read_buffer(stream, size) != SUCCESS) {
733 				if (didread == 0) {
734 					return -1;
735 				}
736 				break;
737 			}
738 
739 			toread = stream->writepos - stream->readpos;
740 			if ((size_t) toread > size) {
741 				toread = size;
742 			}
743 
744 			if (toread > 0) {
745 				memcpy(buf, stream->readbuf + stream->readpos, toread);
746 				stream->readpos += toread;
747 			}
748 		}
749 		if (toread > 0) {
750 			didread += toread;
751 			buf += toread;
752 			size -= toread;
753 		} else {
754 			/* EOF, or temporary end of data (for non-blocking mode). */
755 			break;
756 		}
757 
758 		/* just break anyway, to avoid greedy read for file://, php://memory, and php://temp */
759 		if ((stream->wrapper != &php_plain_files_wrapper) &&
760 			(stream->ops != &php_stream_memory_ops) &&
761 			(stream->ops != &php_stream_temp_ops)) {
762 			break;
763 		}
764 	}
765 
766 	if (didread > 0) {
767 		stream->position += didread;
768 	}
769 
770 	return didread;
771 }
772 
773 /* Like php_stream_read(), but reading into a zend_string buffer. This has some similarity
774  * to the copy_to_mem() operation, but only performs a single direct read. */
php_stream_read_to_str(php_stream * stream,size_t len)775 PHPAPI zend_string *php_stream_read_to_str(php_stream *stream, size_t len)
776 {
777 	zend_string *str = zend_string_alloc(len, 0);
778 	ssize_t read = php_stream_read(stream, ZSTR_VAL(str), len);
779 	if (read < 0) {
780 		zend_string_efree(str);
781 		return NULL;
782 	}
783 
784 	ZSTR_LEN(str) = read;
785 	ZSTR_VAL(str)[read] = 0;
786 
787 	if ((size_t) read < len / 2) {
788 		return zend_string_truncate(str, read, 0);
789 	}
790 	return str;
791 }
792 
_php_stream_eof(php_stream * stream)793 PHPAPI bool _php_stream_eof(php_stream *stream)
794 {
795 	/* if there is data in the buffer, it's not EOF */
796 	if (stream->writepos - stream->readpos > 0) {
797 		return 0;
798 	}
799 
800 	/* use the configured timeout when checking eof */
801 	if (!stream->eof && PHP_STREAM_OPTION_RETURN_ERR ==
802 		   	php_stream_set_option(stream, PHP_STREAM_OPTION_CHECK_LIVENESS,
803 		   	0, NULL)) {
804 		stream->eof = 1;
805 	}
806 
807 	return stream->eof;
808 }
809 
_php_stream_putc(php_stream * stream,int c)810 PHPAPI int _php_stream_putc(php_stream *stream, int c)
811 {
812 	unsigned char buf = c;
813 
814 	if (php_stream_write(stream, (char*)&buf, 1) > 0) {
815 		return 1;
816 	}
817 	return EOF;
818 }
819 
_php_stream_getc(php_stream * stream)820 PHPAPI int _php_stream_getc(php_stream *stream)
821 {
822 	char buf;
823 
824 	if (php_stream_read(stream, &buf, 1) > 0) {
825 		return buf & 0xff;
826 	}
827 	return EOF;
828 }
829 
_php_stream_puts(php_stream * stream,const char * buf)830 PHPAPI bool _php_stream_puts(php_stream *stream, const char *buf)
831 {
832 	size_t len;
833 	char newline[2] = "\n"; /* is this OK for Win? */
834 	len = strlen(buf);
835 
836 	if (len > 0 && php_stream_write(stream, buf, len) > 0 && php_stream_write(stream, newline, 1) > 0) {
837 		return 1;
838 	}
839 	return 0;
840 }
841 
_php_stream_stat(php_stream * stream,php_stream_statbuf * ssb)842 PHPAPI int _php_stream_stat(php_stream *stream, php_stream_statbuf *ssb)
843 {
844 	memset(ssb, 0, sizeof(*ssb));
845 
846 	/* if the stream was wrapped, allow the wrapper to stat it */
847 	if (stream->wrapper && stream->wrapper->wops->stream_stat != NULL) {
848 		return stream->wrapper->wops->stream_stat(stream->wrapper, stream, ssb);
849 	}
850 
851 	/* if the stream doesn't directly support stat-ing, return with failure.
852 	 * We could try and emulate this by casting to a FD and fstat-ing it,
853 	 * but since the fd might not represent the actual underlying content
854 	 * this would give bogus results. */
855 	if (stream->ops->stat == NULL) {
856 		return -1;
857 	}
858 
859 	return (stream->ops->stat)(stream, ssb);
860 }
861 
php_stream_locate_eol(php_stream * stream,zend_string * buf)862 PHPAPI const char *php_stream_locate_eol(php_stream *stream, zend_string *buf)
863 {
864 	size_t avail;
865 	const char *cr, *lf, *eol = NULL;
866 	const char *readptr;
867 
868 	if (!buf) {
869 		readptr = (char*)stream->readbuf + stream->readpos;
870 		avail = stream->writepos - stream->readpos;
871 	} else {
872 		readptr = ZSTR_VAL(buf);
873 		avail = ZSTR_LEN(buf);
874 	}
875 
876 	/* Look for EOL */
877 	if (stream->flags & PHP_STREAM_FLAG_DETECT_EOL) {
878 		cr = memchr(readptr, '\r', avail);
879 		lf = memchr(readptr, '\n', avail);
880 
881 		if (cr && lf != cr + 1 && !(lf && lf < cr)) {
882 			/* mac */
883 			stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL;
884 			stream->flags |= PHP_STREAM_FLAG_EOL_MAC;
885 			eol = cr;
886 		} else if ((cr && lf && cr == lf - 1) || (lf)) {
887 			/* dos or unix endings */
888 			stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL;
889 			eol = lf;
890 		}
891 	} else if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) {
892 		eol = memchr(readptr, '\r', avail);
893 	} else {
894 		/* unix (and dos) line endings */
895 		eol = memchr(readptr, '\n', avail);
896 	}
897 
898 	return eol;
899 }
900 
901 /* If buf == NULL, the buffer will be allocated automatically and will be of an
902  * appropriate length to hold the line, regardless of the line length, memory
903  * permitting */
_php_stream_get_line(php_stream * stream,char * buf,size_t maxlen,size_t * returned_len)904 PHPAPI char *_php_stream_get_line(php_stream *stream, char *buf, size_t maxlen,
905 		size_t *returned_len)
906 {
907 	size_t avail = 0;
908 	size_t current_buf_size = 0;
909 	size_t total_copied = 0;
910 	int grow_mode = 0;
911 	char *bufstart = buf;
912 
913 	if (buf == NULL) {
914 		grow_mode = 1;
915 	} else if (maxlen == 0) {
916 		return NULL;
917 	}
918 
919 	/*
920 	 * If the underlying stream operations block when no new data is readable,
921 	 * we need to take extra precautions.
922 	 *
923 	 * If there is buffered data available, we check for a EOL. If it exists,
924 	 * we pass the data immediately back to the caller. This saves a call
925 	 * to the read implementation and will not block where blocking
926 	 * is not necessary at all.
927 	 *
928 	 * If the stream buffer contains more data than the caller requested,
929 	 * we can also avoid that costly step and simply return that data.
930 	 */
931 
932 	for (;;) {
933 		avail = stream->writepos - stream->readpos;
934 
935 		if (avail > 0) {
936 			size_t cpysz = 0;
937 			char *readptr;
938 			const char *eol;
939 			int done = 0;
940 
941 			readptr = (char*)stream->readbuf + stream->readpos;
942 			eol = php_stream_locate_eol(stream, NULL);
943 
944 			if (eol) {
945 				cpysz = eol - readptr + 1;
946 				done = 1;
947 			} else {
948 				cpysz = avail;
949 			}
950 
951 			if (grow_mode) {
952 				/* allow room for a NUL. If this realloc is really a realloc
953 				 * (ie: second time around), we get an extra byte. In most
954 				 * cases, with the default chunk size of 8K, we will only
955 				 * incur that overhead once.  When people have lines longer
956 				 * than 8K, we waste 1 byte per additional 8K or so.
957 				 * That seems acceptable to me, to avoid making this code
958 				 * hard to follow */
959 				bufstart = erealloc(bufstart, current_buf_size + cpysz + 1);
960 				current_buf_size += cpysz + 1;
961 				buf = bufstart + total_copied;
962 			} else {
963 				if (cpysz >= maxlen - 1) {
964 					cpysz = maxlen - 1;
965 					done = 1;
966 				}
967 			}
968 
969 			memcpy(buf, readptr, cpysz);
970 
971 			stream->position += cpysz;
972 			stream->readpos += cpysz;
973 			buf += cpysz;
974 			maxlen -= cpysz;
975 			total_copied += cpysz;
976 
977 			if (done) {
978 				break;
979 			}
980 		} else if (stream->eof) {
981 			break;
982 		} else {
983 			/* XXX: Should be fine to always read chunk_size */
984 			size_t toread;
985 
986 			if (grow_mode) {
987 				toread = stream->chunk_size;
988 			} else {
989 				toread = maxlen - 1;
990 				if (toread > stream->chunk_size) {
991 					toread = stream->chunk_size;
992 				}
993 			}
994 
995 			php_stream_fill_read_buffer(stream, toread);
996 
997 			if (stream->writepos - stream->readpos == 0) {
998 				break;
999 			}
1000 		}
1001 	}
1002 
1003 	if (total_copied == 0) {
1004 		if (grow_mode) {
1005 			assert(bufstart == NULL);
1006 		}
1007 		return NULL;
1008 	}
1009 
1010 	buf[0] = '\0';
1011 	if (returned_len) {
1012 		*returned_len = total_copied;
1013 	}
1014 
1015 	return bufstart;
1016 }
1017 
1018 #define STREAM_BUFFERED_AMOUNT(stream) \
1019 	((size_t)(((stream)->writepos) - (stream)->readpos))
1020 
_php_stream_search_delim(php_stream * stream,size_t maxlen,size_t skiplen,const char * delim,size_t delim_len)1021 static const char *_php_stream_search_delim(php_stream *stream,
1022 											size_t maxlen,
1023 											size_t skiplen,
1024 											const char *delim, /* non-empty! */
1025 											size_t delim_len)
1026 {
1027 	size_t	seek_len;
1028 
1029 	/* set the maximum number of bytes we're allowed to read from buffer */
1030 	seek_len = MIN(STREAM_BUFFERED_AMOUNT(stream), maxlen);
1031 	if (seek_len <= skiplen) {
1032 		return NULL;
1033 	}
1034 
1035 	if (delim_len == 1) {
1036 		return memchr(&stream->readbuf[stream->readpos + skiplen],
1037 			delim[0], seek_len - skiplen);
1038 	} else {
1039 		return php_memnstr((char*)&stream->readbuf[stream->readpos + skiplen],
1040 				delim, delim_len,
1041 				(char*)&stream->readbuf[stream->readpos + seek_len]);
1042 	}
1043 }
1044 
php_stream_get_record(php_stream * stream,size_t maxlen,const char * delim,size_t delim_len)1045 PHPAPI zend_string *php_stream_get_record(php_stream *stream, size_t maxlen, const char *delim, size_t delim_len)
1046 {
1047 	zend_string	*ret_buf;				/* returned buffer */
1048 	const char *found_delim = NULL;
1049 	size_t	buffered_len,
1050 			tent_ret_len;			/* tentative returned length */
1051 	bool	has_delim = delim_len > 0;
1052 
1053 	if (maxlen == 0) {
1054 		return NULL;
1055 	}
1056 
1057 	if (has_delim) {
1058 		found_delim = _php_stream_search_delim(
1059 			stream, maxlen, 0, delim, delim_len);
1060 	}
1061 
1062 	buffered_len = STREAM_BUFFERED_AMOUNT(stream);
1063 	/* try to read up to maxlen length bytes while we don't find the delim */
1064 	while (!found_delim && buffered_len < maxlen) {
1065 		size_t	just_read,
1066 				to_read_now;
1067 
1068 		to_read_now = MIN(maxlen - buffered_len, stream->chunk_size);
1069 
1070 		php_stream_fill_read_buffer(stream, buffered_len + to_read_now);
1071 
1072 		just_read = STREAM_BUFFERED_AMOUNT(stream) - buffered_len;
1073 
1074 		/* Assume the stream is temporarily or permanently out of data */
1075 		if (just_read == 0) {
1076 			break;
1077 		}
1078 
1079 		if (has_delim) {
1080 			/* search for delimiter, but skip buffered_len (the number of bytes
1081 			 * buffered before this loop iteration), as they have already been
1082 			 * searched for the delimiter.
1083 			 * The left part of the delimiter may still remain in the buffer,
1084 			 * so subtract up to <delim_len - 1> from buffered_len, which is
1085 			 * the amount of data we skip on this search  as an optimization
1086 			 */
1087 			found_delim = _php_stream_search_delim(
1088 				stream, maxlen,
1089 				buffered_len >= (delim_len - 1)
1090 						? buffered_len - (delim_len - 1)
1091 						: 0,
1092 				delim, delim_len);
1093 			if (found_delim) {
1094 				break;
1095 			}
1096 		}
1097 		buffered_len += just_read;
1098 	}
1099 
1100 	if (has_delim && found_delim) {
1101 		tent_ret_len = found_delim - (char*)&stream->readbuf[stream->readpos];
1102 	} else if (!has_delim && STREAM_BUFFERED_AMOUNT(stream) >= maxlen) {
1103 		tent_ret_len = maxlen;
1104 	} else {
1105 		/* return with error if the delimiter string (if any) was not found, we
1106 		 * could not completely fill the read buffer with maxlen bytes and we
1107 		 * don't know we've reached end of file. Added with non-blocking streams
1108 		 * in mind, where this situation is frequent */
1109 		if (STREAM_BUFFERED_AMOUNT(stream) < maxlen && !stream->eof) {
1110 			return NULL;
1111 		} else if (STREAM_BUFFERED_AMOUNT(stream) == 0 && stream->eof) {
1112 			/* refuse to return an empty string just because by accident
1113 			 * we knew of EOF in a read that returned no data */
1114 			return NULL;
1115 		} else {
1116 			tent_ret_len = MIN(STREAM_BUFFERED_AMOUNT(stream), maxlen);
1117 		}
1118 	}
1119 
1120 	ret_buf = zend_string_alloc(tent_ret_len, 0);
1121 	/* php_stream_read will not call ops->read here because the necessary
1122 	 * data is guaranteed to be buffered */
1123 	ZSTR_LEN(ret_buf) = php_stream_read(stream, ZSTR_VAL(ret_buf), tent_ret_len);
1124 
1125 	if (found_delim) {
1126 		stream->readpos += delim_len;
1127 		stream->position += delim_len;
1128 	}
1129 	ZSTR_VAL(ret_buf)[ZSTR_LEN(ret_buf)] = '\0';
1130 	return ret_buf;
1131 }
1132 
1133 /* 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)1134 static ssize_t _php_stream_write_buffer(php_stream *stream, const char *buf, size_t count)
1135 {
1136 	ssize_t didwrite = 0;
1137 
1138 	/* if we have a seekable stream we need to ensure that data is written at the
1139 	 * current stream->position. This means invalidating the read buffer and then
1140 	 * performing a low-level seek */
1141 	if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && stream->readpos != stream->writepos) {
1142 		stream->readpos = stream->writepos = 0;
1143 
1144 		stream->ops->seek(stream, stream->position, SEEK_SET, &stream->position);
1145 	}
1146 
1147 	/* See GH-13071: userspace stream is subject to the memory limit. */
1148 	size_t chunk_size = count;
1149 	if (php_stream_is(stream, PHP_STREAM_IS_USERSPACE)) {
1150 		/* If the stream is unbuffered, we can only write one byte at a time. */
1151 		chunk_size = stream->chunk_size;
1152 	}
1153 
1154 	while (count > 0) {
1155 		ssize_t justwrote = stream->ops->write(stream, buf, MIN(chunk_size, count));
1156 		if (justwrote <= 0) {
1157 			/* If we already successfully wrote some bytes and a write error occurred
1158 			 * later, report the successfully written bytes. */
1159 			if (didwrite == 0) {
1160 				return justwrote;
1161 			}
1162 			return didwrite;
1163 		}
1164 
1165 		buf += justwrote;
1166 		count -= justwrote;
1167 		didwrite += justwrote;
1168 		stream->position += justwrote;
1169 	}
1170 
1171 	return didwrite;
1172 }
1173 
1174 /* push some data through the write filter chain.
1175  * buf may be NULL, if flags are set to indicate a flush.
1176  * This may trigger a real write to the stream.
1177  * Returns the number of bytes consumed from buf by the first filter in the chain.
1178  * */
_php_stream_write_filtered(php_stream * stream,const char * buf,size_t count,int flags)1179 static ssize_t _php_stream_write_filtered(php_stream *stream, const char *buf, size_t count, int flags)
1180 {
1181 	size_t consumed = 0;
1182 	php_stream_bucket *bucket;
1183 	php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL };
1184 	php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap;
1185 	php_stream_filter_status_t status = PSFS_ERR_FATAL;
1186 	php_stream_filter *filter;
1187 
1188 	if (buf) {
1189 		bucket = php_stream_bucket_new(stream, (char *)buf, count, 0, 0);
1190 		php_stream_bucket_append(&brig_in, bucket);
1191 	}
1192 
1193 	for (filter = stream->writefilters.head; filter; filter = filter->next) {
1194 		/* for our return value, we are interested in the number of bytes consumed from
1195 		 * the first filter in the chain */
1196 		status = filter->fops->filter(stream, filter, brig_inp, brig_outp,
1197 				filter == stream->writefilters.head ? &consumed : NULL, flags);
1198 
1199 		if (status != PSFS_PASS_ON) {
1200 			break;
1201 		}
1202 		/* brig_out becomes brig_in.
1203 		 * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets
1204 		 * to its own brigade */
1205 		brig_swap = brig_inp;
1206 		brig_inp = brig_outp;
1207 		brig_outp = brig_swap;
1208 		memset(brig_outp, 0, sizeof(*brig_outp));
1209 	}
1210 
1211 	switch (status) {
1212 		case PSFS_PASS_ON:
1213 			/* filter chain generated some output; push it through to the
1214 			 * underlying stream */
1215 			while (brig_inp->head) {
1216 				bucket = brig_inp->head;
1217 				if (_php_stream_write_buffer(stream, bucket->buf, bucket->buflen) < 0) {
1218 					consumed = (ssize_t) -1;
1219 				}
1220 
1221 				/* Potential error situation - eg: no space on device. Perhaps we should keep this brigade
1222 				 * hanging around and try to write it later.
1223 				 * At the moment, we just drop it on the floor
1224 				 * */
1225 
1226 				php_stream_bucket_unlink(bucket);
1227 				php_stream_bucket_delref(bucket);
1228 			}
1229 			break;
1230 		case PSFS_FEED_ME:
1231 			/* need more data before we can push data through to the stream */
1232 			break;
1233 
1234 		case PSFS_ERR_FATAL:
1235 			/* some fatal error.  Theoretically, the stream is borked, so all
1236 			 * further writes should fail. */
1237 			return (ssize_t) -1;
1238 	}
1239 
1240 	return consumed;
1241 }
1242 
_php_stream_flush(php_stream * stream,int closing)1243 PHPAPI int _php_stream_flush(php_stream *stream, int closing)
1244 {
1245 	int ret = 0;
1246 
1247 	if (stream->writefilters.head) {
1248 		_php_stream_write_filtered(stream, NULL, 0, closing ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC );
1249 	}
1250 
1251 	stream->flags &= ~PHP_STREAM_FLAG_WAS_WRITTEN;
1252 
1253 	if (stream->ops->flush) {
1254 		ret = stream->ops->flush(stream);
1255 	}
1256 
1257 	return ret;
1258 }
1259 
_php_stream_write(php_stream * stream,const char * buf,size_t count)1260 PHPAPI ssize_t _php_stream_write(php_stream *stream, const char *buf, size_t count)
1261 {
1262 	ssize_t bytes;
1263 
1264 	if (count == 0) {
1265 		return 0;
1266 	}
1267 
1268 	ZEND_ASSERT(buf != NULL);
1269 	if (stream->ops->write == NULL) {
1270 		php_error_docref(NULL, E_NOTICE, "Stream is not writable");
1271 		return (ssize_t) -1;
1272 	}
1273 
1274 	if (stream->writefilters.head) {
1275 		bytes = _php_stream_write_filtered(stream, buf, count, PSFS_FLAG_NORMAL);
1276 	} else {
1277 		bytes = _php_stream_write_buffer(stream, buf, count);
1278 	}
1279 
1280 	if (bytes) {
1281 		stream->flags |= PHP_STREAM_FLAG_WAS_WRITTEN;
1282 	}
1283 
1284 	return bytes;
1285 }
1286 
_php_stream_printf(php_stream * stream,const char * fmt,...)1287 PHPAPI ssize_t _php_stream_printf(php_stream *stream, const char *fmt, ...)
1288 {
1289 	ssize_t count;
1290 	char *buf;
1291 	va_list ap;
1292 
1293 	va_start(ap, fmt);
1294 	count = vspprintf(&buf, 0, fmt, ap);
1295 	va_end(ap);
1296 
1297 	if (!buf) {
1298 		return -1; /* error condition */
1299 	}
1300 
1301 	count = php_stream_write(stream, buf, count);
1302 	efree(buf);
1303 
1304 	return count;
1305 }
1306 
_php_stream_tell(php_stream * stream)1307 PHPAPI zend_off_t _php_stream_tell(php_stream *stream)
1308 {
1309 	return stream->position;
1310 }
1311 
_php_stream_seek(php_stream * stream,zend_off_t offset,int whence)1312 PHPAPI int _php_stream_seek(php_stream *stream, zend_off_t offset, int whence)
1313 {
1314 	if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) {
1315 		/* flush can call seek internally so we need to prevent an infinite loop */
1316 		if (!stream->fclose_stdiocast_flush_in_progress) {
1317 			stream->fclose_stdiocast_flush_in_progress = 1;
1318 			/* flush to commit data written to the fopencookie FILE* */
1319 			fflush(stream->stdiocast);
1320 			stream->fclose_stdiocast_flush_in_progress = 0;
1321 		}
1322 	}
1323 
1324 	/* handle the case where we are in the buffer */
1325 	if ((stream->flags & PHP_STREAM_FLAG_NO_BUFFER) == 0) {
1326 		switch(whence) {
1327 			case SEEK_CUR:
1328 				if (offset > 0 && offset <= stream->writepos - stream->readpos) {
1329 					stream->readpos += offset; /* if offset = ..., then readpos = writepos */
1330 					stream->position += offset;
1331 					stream->eof = 0;
1332 					return 0;
1333 				}
1334 				break;
1335 			case SEEK_SET:
1336 				if (offset > stream->position &&
1337 						offset <= stream->position + stream->writepos - stream->readpos) {
1338 					stream->readpos += offset - stream->position;
1339 					stream->position = offset;
1340 					stream->eof = 0;
1341 					return 0;
1342 				}
1343 				break;
1344 		}
1345 	}
1346 
1347 
1348 	if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) {
1349 		int ret;
1350 
1351 		if (stream->writefilters.head) {
1352 			_php_stream_flush(stream, 0);
1353 		}
1354 
1355 		switch(whence) {
1356 			case SEEK_CUR:
1357 				offset = stream->position + offset;
1358 				whence = SEEK_SET;
1359 				break;
1360 		}
1361 		ret = stream->ops->seek(stream, offset, whence, &stream->position);
1362 
1363 		if (((stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) || ret == 0) {
1364 			if (ret == 0) {
1365 				stream->eof = 0;
1366 			}
1367 
1368 			/* invalidate the buffer contents */
1369 			stream->readpos = stream->writepos = 0;
1370 
1371 			return ret;
1372 		}
1373 		/* else the stream has decided that it can't support seeking after all;
1374 		 * fall through to attempt emulation */
1375 	}
1376 
1377 	/* emulate forward moving seeks with reads */
1378 	if (whence == SEEK_CUR && offset >= 0) {
1379 		char tmp[1024];
1380 		ssize_t didread;
1381 		while (offset > 0) {
1382 			if ((didread = php_stream_read(stream, tmp, MIN(offset, sizeof(tmp)))) <= 0) {
1383 				return -1;
1384 			}
1385 			offset -= didread;
1386 		}
1387 		stream->eof = 0;
1388 		return 0;
1389 	}
1390 
1391 	php_error_docref(NULL, E_WARNING, "Stream does not support seeking");
1392 
1393 	return -1;
1394 }
1395 
_php_stream_set_option(php_stream * stream,int option,int value,void * ptrparam)1396 PHPAPI int _php_stream_set_option(php_stream *stream, int option, int value, void *ptrparam)
1397 {
1398 	int ret = PHP_STREAM_OPTION_RETURN_NOTIMPL;
1399 
1400 	if (stream->ops->set_option) {
1401 		ret = stream->ops->set_option(stream, option, value, ptrparam);
1402 	}
1403 
1404 	if (ret == PHP_STREAM_OPTION_RETURN_NOTIMPL) {
1405 		switch(option) {
1406 			case PHP_STREAM_OPTION_SET_CHUNK_SIZE:
1407 				/* XXX chunk size itself is of size_t, that might be ok or not for a particular case*/
1408 				ret = stream->chunk_size > INT_MAX ? INT_MAX : (int)stream->chunk_size;
1409 				stream->chunk_size = value;
1410 				return ret;
1411 
1412 			case PHP_STREAM_OPTION_READ_BUFFER:
1413 				/* try to match the buffer mode as best we can */
1414 				if (value == PHP_STREAM_BUFFER_NONE) {
1415 					stream->flags |= PHP_STREAM_FLAG_NO_BUFFER;
1416 				} else if (stream->flags & PHP_STREAM_FLAG_NO_BUFFER) {
1417 					stream->flags ^= PHP_STREAM_FLAG_NO_BUFFER;
1418 				}
1419 				ret = PHP_STREAM_OPTION_RETURN_OK;
1420 				break;
1421 
1422 			default:
1423 				;
1424 		}
1425 	}
1426 
1427 	return ret;
1428 }
1429 
_php_stream_sync(php_stream * stream,bool data_only)1430 PHPAPI int _php_stream_sync(php_stream *stream, bool data_only)
1431 {
1432 	int op = PHP_STREAM_SYNC_FSYNC;
1433 	if (data_only) {
1434 		op = PHP_STREAM_SYNC_FDSYNC;
1435 	}
1436 	return php_stream_set_option(stream, PHP_STREAM_OPTION_SYNC_API, op, NULL);
1437 }
1438 
_php_stream_truncate_set_size(php_stream * stream,size_t newsize)1439 PHPAPI int _php_stream_truncate_set_size(php_stream *stream, size_t newsize)
1440 {
1441 	return php_stream_set_option(stream, PHP_STREAM_OPTION_TRUNCATE_API, PHP_STREAM_TRUNCATE_SET_SIZE, &newsize);
1442 }
1443 
_php_stream_passthru(php_stream * stream STREAMS_DC)1444 PHPAPI ssize_t _php_stream_passthru(php_stream * stream STREAMS_DC)
1445 {
1446 	size_t bcount = 0;
1447 	char buf[8192];
1448 	ssize_t b;
1449 
1450 	if (php_stream_mmap_possible(stream)) {
1451 		char *p;
1452 		size_t mapped;
1453 
1454 		p = php_stream_mmap_range(stream, php_stream_tell(stream), PHP_STREAM_MMAP_ALL, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped);
1455 
1456 		if (p) {
1457 			do {
1458 				/* output functions return int, so pass in int max */
1459 				if (0 < (b = PHPWRITE(p + bcount, MIN(mapped - bcount, INT_MAX)))) {
1460 					bcount += b;
1461 				}
1462 			} while (b > 0 && mapped > bcount);
1463 
1464 			php_stream_mmap_unmap_ex(stream, mapped);
1465 
1466 			return bcount;
1467 		}
1468 	}
1469 
1470 	while ((b = php_stream_read(stream, buf, sizeof(buf))) > 0) {
1471 		PHPWRITE(buf, b);
1472 		bcount += b;
1473 	}
1474 
1475 	if (b < 0 && bcount == 0) {
1476 		return b;
1477 	}
1478 
1479 	return bcount;
1480 }
1481 
1482 
_php_stream_copy_to_mem(php_stream * src,size_t maxlen,int persistent STREAMS_DC)1483 PHPAPI zend_string *_php_stream_copy_to_mem(php_stream *src, size_t maxlen, int persistent STREAMS_DC)
1484 {
1485 	ssize_t ret = 0;
1486 	char *ptr;
1487 	size_t len = 0, max_len;
1488 	int step = CHUNK_SIZE;
1489 	int min_room = CHUNK_SIZE / 4;
1490 	php_stream_statbuf ssbuf;
1491 	zend_string *result;
1492 
1493 	if (maxlen == 0) {
1494 		return ZSTR_EMPTY_ALLOC();
1495 	}
1496 
1497 	if (maxlen == PHP_STREAM_COPY_ALL) {
1498 		maxlen = 0;
1499 	}
1500 
1501 	if (maxlen > 0) {
1502 		result = zend_string_alloc(maxlen, persistent);
1503 		ptr = ZSTR_VAL(result);
1504 		while ((len < maxlen) && !php_stream_eof(src)) {
1505 			ret = php_stream_read(src, ptr, maxlen - len);
1506 			if (ret <= 0) {
1507 				// TODO: Propagate error?
1508 				break;
1509 			}
1510 			len += ret;
1511 			ptr += ret;
1512 		}
1513 		if (len) {
1514 			ZSTR_LEN(result) = len;
1515 			ZSTR_VAL(result)[len] = '\0';
1516 
1517 			/* Only truncate if the savings are large enough */
1518 			if (len < maxlen / 2) {
1519 				result = zend_string_truncate(result, len, persistent);
1520 			}
1521 		} else {
1522 			zend_string_free(result);
1523 			result = NULL;
1524 		}
1525 		return result;
1526 	}
1527 
1528 	/* avoid many reallocs by allocating a good sized chunk to begin with, if
1529 	 * we can.  Note that the stream may be filtered, in which case the stat
1530 	 * result may be inaccurate, as the filter may inflate or deflate the
1531 	 * number of bytes that we can read.  In order to avoid an upsize followed
1532 	 * by a downsize of the buffer, overestimate by the step size (which is
1533 	 * 8K).  */
1534 	if (php_stream_stat(src, &ssbuf) == 0 && ssbuf.sb.st_size > 0) {
1535 		max_len = MAX(ssbuf.sb.st_size - src->position, 0) + step;
1536 	} else {
1537 		max_len = step;
1538 	}
1539 
1540 	result = zend_string_alloc(max_len, persistent);
1541 	ptr = ZSTR_VAL(result);
1542 
1543 	// TODO: Propagate error?
1544 	while ((ret = php_stream_read(src, ptr, max_len - len)) > 0){
1545 		len += ret;
1546 		if (len + min_room >= max_len) {
1547 			result = zend_string_extend(result, max_len + step, persistent);
1548 			max_len += step;
1549 			ptr = ZSTR_VAL(result) + len;
1550 		} else {
1551 			ptr += ret;
1552 		}
1553 	}
1554 	if (len) {
1555 		result = zend_string_truncate(result, len, persistent);
1556 		ZSTR_VAL(result)[len] = '\0';
1557 	} else {
1558 		zend_string_free(result);
1559 		result = NULL;
1560 	}
1561 
1562 	return result;
1563 }
1564 
1565 /* 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)1566 PHPAPI zend_result _php_stream_copy_to_stream_ex(php_stream *src, php_stream *dest, size_t maxlen, size_t *len STREAMS_DC)
1567 {
1568 	char buf[CHUNK_SIZE];
1569 	size_t haveread = 0;
1570 	size_t towrite;
1571 	size_t dummy;
1572 
1573 	if (!len) {
1574 		len = &dummy;
1575 	}
1576 
1577 	if (maxlen == 0) {
1578 		*len = 0;
1579 		return SUCCESS;
1580 	}
1581 
1582 #ifdef HAVE_COPY_FILE_RANGE
1583 	if (php_stream_is(src, PHP_STREAM_IS_STDIO) &&
1584 			php_stream_is(dest, PHP_STREAM_IS_STDIO) &&
1585 			src->writepos == src->readpos) {
1586 		/* both php_stream instances are backed by a file descriptor, are not filtered and the
1587 		 * read buffer is empty: we can use copy_file_range() */
1588 		int src_fd, dest_fd, dest_open_flags = 0;
1589 
1590 		/* get dest open flags to check if the stream is open in append mode */
1591 		php_stream_parse_fopen_modes(dest->mode, &dest_open_flags);
1592 
1593 		/* copy_file_range does not work with O_APPEND */
1594 		if (php_stream_cast(src, PHP_STREAM_AS_FD, (void*)&src_fd, 0) == SUCCESS &&
1595 				php_stream_cast(dest, PHP_STREAM_AS_FD, (void*)&dest_fd, 0) == SUCCESS &&
1596 				php_stream_parse_fopen_modes(dest->mode, &dest_open_flags) == SUCCESS &&
1597 				!(dest_open_flags & O_APPEND)) {
1598 
1599 			/* clamp to INT_MAX to avoid EOVERFLOW */
1600 			const size_t cfr_max = MIN(maxlen, (size_t)SSIZE_MAX);
1601 
1602 			/* copy_file_range() is a Linux-specific system call which allows efficient copying
1603 			 * between two file descriptors, eliminating the need to transfer data from the kernel
1604 			 * to userspace and back. For networking file systems like NFS and Ceph, it even
1605 			 * eliminates copying data to the client, and local filesystems like Btrfs and XFS can
1606 			 * create shared extents. */
1607 			ssize_t result = copy_file_range(src_fd, NULL, dest_fd, NULL, cfr_max, 0);
1608 			if (result > 0) {
1609 				size_t nbytes = (size_t)result;
1610 				haveread += nbytes;
1611 
1612 				src->position += nbytes;
1613 				dest->position += nbytes;
1614 
1615 				if ((maxlen != PHP_STREAM_COPY_ALL && nbytes == maxlen) || php_stream_eof(src)) {
1616 					/* the whole request was satisfied or end-of-file reached - done */
1617 					*len = haveread;
1618 					return SUCCESS;
1619 				}
1620 
1621 				/* there may be more data; continue copying using the fallback code below */
1622 			} else if (result == 0) {
1623 				/* end of file */
1624 				*len = haveread;
1625 				return SUCCESS;
1626 			} else if (result < 0) {
1627 				switch (errno) {
1628 					case EINVAL:
1629 						/* some formal error, e.g. overlapping file ranges */
1630 						break;
1631 
1632 					case EXDEV:
1633 						/* pre Linux 5.3 error */
1634 						break;
1635 
1636 					case ENOSYS:
1637 						/* not implemented by this Linux kernel */
1638 						break;
1639 
1640 					case EIO:
1641 						/* Some filesystems will cause failures if the max length is greater than the file length
1642 						 * in certain circumstances and configuration. In those cases the errno is EIO and we will
1643 						 * fall back to other methods. We cannot use stat to determine the file length upfront because
1644 						 * that is prone to races and outdated caching. */
1645 						break;
1646 
1647 					default:
1648 						/* unexpected I/O error - give up, no fallback */
1649 						*len = haveread;
1650 						return FAILURE;
1651 				}
1652 
1653 				/* fall back to classic copying */
1654 			}
1655 		}
1656 	}
1657 #endif // HAVE_COPY_FILE_RANGE
1658 
1659 	if (maxlen == PHP_STREAM_COPY_ALL) {
1660 		maxlen = 0;
1661 	}
1662 
1663 	if (php_stream_mmap_possible(src)) {
1664 		char *p;
1665 
1666 		do {
1667 			/* We must not modify maxlen here, because otherwise the file copy fallback below can fail */
1668 			size_t chunk_size, must_read, mapped;
1669 			if (maxlen == 0) {
1670 				/* Unlimited read */
1671 				must_read = chunk_size = PHP_STREAM_MMAP_MAX;
1672 			} else {
1673 				must_read = maxlen - haveread;
1674 				if (must_read >= PHP_STREAM_MMAP_MAX) {
1675 					chunk_size = PHP_STREAM_MMAP_MAX;
1676 				} else {
1677 					/* In case the length we still have to read from the file could be smaller than the file size,
1678 					 * chunk_size must not get bigger the size we're trying to read. */
1679 					chunk_size = must_read;
1680 				}
1681 			}
1682 
1683 			p = php_stream_mmap_range(src, php_stream_tell(src), chunk_size, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped);
1684 
1685 			if (p) {
1686 				ssize_t didwrite;
1687 
1688 				if (php_stream_seek(src, mapped, SEEK_CUR) != 0) {
1689 					php_stream_mmap_unmap(src);
1690 					break;
1691 				}
1692 
1693 				didwrite = php_stream_write(dest, p, mapped);
1694 				if (didwrite < 0) {
1695 					*len = haveread;
1696 					php_stream_mmap_unmap(src);
1697 					return FAILURE;
1698 				}
1699 
1700 				php_stream_mmap_unmap(src);
1701 
1702 				*len = haveread += didwrite;
1703 
1704 				/* we've got at least 1 byte to read
1705 				 * less than 1 is an error
1706 				 * AND read bytes match written */
1707 				if (mapped == 0 || mapped != didwrite) {
1708 					return FAILURE;
1709 				}
1710 				if (mapped < chunk_size) {
1711 					return SUCCESS;
1712 				}
1713 				/* If we're not reading as much as possible, so a bounded read */
1714 				if (maxlen != 0) {
1715 					must_read -= mapped;
1716 					if (must_read == 0) {
1717 						return SUCCESS;
1718 					}
1719 				}
1720 			}
1721 		} while (p);
1722 	}
1723 
1724 	while(1) {
1725 		size_t readchunk = sizeof(buf);
1726 		ssize_t didread;
1727 		char *writeptr;
1728 
1729 		if (maxlen && (maxlen - haveread) < readchunk) {
1730 			readchunk = maxlen - haveread;
1731 		}
1732 
1733 		didread = php_stream_read(src, buf, readchunk);
1734 		if (didread <= 0) {
1735 			*len = haveread;
1736 			return didread < 0 ? FAILURE : SUCCESS;
1737 		}
1738 
1739 		towrite = didread;
1740 		writeptr = buf;
1741 		haveread += didread;
1742 
1743 		while (towrite) {
1744 			ssize_t didwrite = php_stream_write(dest, writeptr, towrite);
1745 			if (didwrite <= 0) {
1746 				*len = haveread - (didread - towrite);
1747 				return FAILURE;
1748 			}
1749 
1750 			towrite -= didwrite;
1751 			writeptr += didwrite;
1752 		}
1753 
1754 		if (maxlen && maxlen == haveread) {
1755 			break;
1756 		}
1757 	}
1758 
1759 	*len = haveread;
1760 	return SUCCESS;
1761 }
1762 
1763 /* Returns the number of bytes moved.
1764  * Returns 1 when source len is 0.
1765  * Deprecated in favor of php_stream_copy_to_stream_ex() */
1766 ZEND_ATTRIBUTE_DEPRECATED
_php_stream_copy_to_stream(php_stream * src,php_stream * dest,size_t maxlen STREAMS_DC)1767 PHPAPI size_t _php_stream_copy_to_stream(php_stream *src, php_stream *dest, size_t maxlen STREAMS_DC)
1768 {
1769 	size_t len;
1770 	zend_result ret = _php_stream_copy_to_stream_ex(src, dest, maxlen, &len STREAMS_REL_CC);
1771 	if (ret == SUCCESS && len == 0 && maxlen != 0) {
1772 		return 1;
1773 	}
1774 	return len;
1775 }
1776 /* }}} */
1777 
1778 /* {{{ wrapper init and registration */
1779 
stream_resource_regular_dtor(zend_resource * rsrc)1780 static void stream_resource_regular_dtor(zend_resource *rsrc)
1781 {
1782 	php_stream *stream = (php_stream*)rsrc->ptr;
1783 	/* set the return value for pclose */
1784 	FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR);
1785 }
1786 
stream_resource_persistent_dtor(zend_resource * rsrc)1787 static void stream_resource_persistent_dtor(zend_resource *rsrc)
1788 {
1789 	php_stream *stream = (php_stream*)rsrc->ptr;
1790 	FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR);
1791 }
1792 
php_shutdown_stream_hashes(void)1793 void php_shutdown_stream_hashes(void)
1794 {
1795 	FG(user_stream_current_filename) = NULL;
1796 	if (FG(stream_wrappers)) {
1797 		zend_hash_destroy(FG(stream_wrappers));
1798 		efree(FG(stream_wrappers));
1799 		FG(stream_wrappers) = NULL;
1800 	}
1801 
1802 	if (FG(stream_filters)) {
1803 		zend_hash_destroy(FG(stream_filters));
1804 		efree(FG(stream_filters));
1805 		FG(stream_filters) = NULL;
1806 	}
1807 
1808 	if (FG(wrapper_errors)) {
1809 		zend_hash_destroy(FG(wrapper_errors));
1810 		efree(FG(wrapper_errors));
1811 		FG(wrapper_errors) = NULL;
1812 	}
1813 }
1814 
php_init_stream_wrappers(int module_number)1815 int php_init_stream_wrappers(int module_number)
1816 {
1817 	le_stream = zend_register_list_destructors_ex(stream_resource_regular_dtor, NULL, "stream", module_number);
1818 	le_pstream = zend_register_list_destructors_ex(NULL, stream_resource_persistent_dtor, "persistent stream", module_number);
1819 
1820 	/* Filters are cleaned up by the streams they're attached to */
1821 	le_stream_filter = zend_register_list_destructors_ex(NULL, NULL, "stream filter", module_number);
1822 
1823 	zend_hash_init(&url_stream_wrappers_hash, 8, NULL, NULL, 1);
1824 	zend_hash_init(php_get_stream_filters_hash_global(), 8, NULL, NULL, 1);
1825 	zend_hash_init(php_stream_xport_get_hash(), 8, NULL, NULL, 1);
1826 
1827 	return (php_stream_xport_register("tcp", php_stream_generic_socket_factory) == SUCCESS
1828 			&&
1829 			php_stream_xport_register("udp", php_stream_generic_socket_factory) == SUCCESS
1830 #if defined(AF_UNIX) && !(defined(PHP_WIN32) || defined(__riscos__))
1831 			&&
1832 			php_stream_xport_register("unix", php_stream_generic_socket_factory) == SUCCESS
1833 			&&
1834 			php_stream_xport_register("udg", php_stream_generic_socket_factory) == SUCCESS
1835 #endif
1836 		) ? SUCCESS : FAILURE;
1837 }
1838 
php_shutdown_stream_wrappers(int module_number)1839 void php_shutdown_stream_wrappers(int module_number)
1840 {
1841 	zend_hash_destroy(&url_stream_wrappers_hash);
1842 	zend_hash_destroy(php_get_stream_filters_hash_global());
1843 	zend_hash_destroy(php_stream_xport_get_hash());
1844 }
1845 
1846 /* Validate protocol scheme names during registration
1847  * Must conform to /^[a-zA-Z0-9+.-]+$/
1848  */
php_stream_wrapper_scheme_validate(const char * protocol,unsigned int protocol_len)1849 static inline zend_result php_stream_wrapper_scheme_validate(const char *protocol, unsigned int protocol_len)
1850 {
1851 	unsigned int i;
1852 
1853 	for(i = 0; i < protocol_len; i++) {
1854 		if (!isalnum((int)protocol[i]) &&
1855 			protocol[i] != '+' &&
1856 			protocol[i] != '-' &&
1857 			protocol[i] != '.') {
1858 			return FAILURE;
1859 		}
1860 	}
1861 
1862 	return SUCCESS;
1863 }
1864 
1865 /* API for registering GLOBAL wrappers */
php_register_url_stream_wrapper(const char * protocol,const php_stream_wrapper * wrapper)1866 PHPAPI zend_result php_register_url_stream_wrapper(const char *protocol, const php_stream_wrapper *wrapper)
1867 {
1868 	size_t protocol_len = strlen(protocol);
1869 	zend_result ret;
1870 	zend_string *str;
1871 
1872 	if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) {
1873 		return FAILURE;
1874 	}
1875 
1876 	str = zend_string_init_interned(protocol, protocol_len, 1);
1877 	ret = zend_hash_add_ptr(&url_stream_wrappers_hash, str, (void*)wrapper) ? SUCCESS : FAILURE;
1878 	zend_string_release_ex(str, 1);
1879 	return ret;
1880 }
1881 
php_unregister_url_stream_wrapper(const char * protocol)1882 PHPAPI zend_result php_unregister_url_stream_wrapper(const char *protocol)
1883 {
1884 	return zend_hash_str_del(&url_stream_wrappers_hash, protocol, strlen(protocol));
1885 }
1886 
clone_wrapper_hash(void)1887 static void clone_wrapper_hash(void)
1888 {
1889 	ALLOC_HASHTABLE(FG(stream_wrappers));
1890 	zend_hash_init(FG(stream_wrappers), zend_hash_num_elements(&url_stream_wrappers_hash), NULL, NULL, 0);
1891 	zend_hash_copy(FG(stream_wrappers), &url_stream_wrappers_hash, NULL);
1892 }
1893 
1894 /* API for registering VOLATILE wrappers */
php_register_url_stream_wrapper_volatile(zend_string * protocol,php_stream_wrapper * wrapper)1895 PHPAPI zend_result php_register_url_stream_wrapper_volatile(zend_string *protocol, php_stream_wrapper *wrapper)
1896 {
1897 	if (php_stream_wrapper_scheme_validate(ZSTR_VAL(protocol), ZSTR_LEN(protocol)) == FAILURE) {
1898 		return FAILURE;
1899 	}
1900 
1901 	if (!FG(stream_wrappers)) {
1902 		clone_wrapper_hash();
1903 	}
1904 
1905 	return zend_hash_add_ptr(FG(stream_wrappers), protocol, wrapper) ? SUCCESS : FAILURE;
1906 }
1907 
php_unregister_url_stream_wrapper_volatile(zend_string * protocol)1908 PHPAPI zend_result php_unregister_url_stream_wrapper_volatile(zend_string *protocol)
1909 {
1910 	if (!FG(stream_wrappers)) {
1911 		clone_wrapper_hash();
1912 	}
1913 
1914 	return zend_hash_del(FG(stream_wrappers), protocol);
1915 }
1916 /* }}} */
1917 
1918 /* {{{ php_stream_locate_url_wrapper */
php_stream_locate_url_wrapper(const char * path,const char ** path_for_open,int options)1919 PHPAPI php_stream_wrapper *php_stream_locate_url_wrapper(const char *path, const char **path_for_open, int options)
1920 {
1921 	HashTable *wrapper_hash = (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash);
1922 	php_stream_wrapper *wrapper = NULL;
1923 	const char *p, *protocol = NULL;
1924 	size_t n = 0;
1925 
1926 	if (path_for_open) {
1927 		*path_for_open = (char*)path;
1928 	}
1929 
1930 	if (options & IGNORE_URL) {
1931 		return (php_stream_wrapper*)((options & STREAM_LOCATE_WRAPPERS_ONLY) ? NULL : &php_plain_files_wrapper);
1932 	}
1933 
1934 	for (p = path; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++) {
1935 		n++;
1936 	}
1937 
1938 	if ((*p == ':') && (n > 1) && (!strncmp("//", p+1, 2) || (n == 4 && !memcmp("data:", path, 5)))) {
1939 		protocol = path;
1940 	}
1941 
1942 	if (protocol) {
1943 		if (NULL == (wrapper = zend_hash_str_find_ptr(wrapper_hash, protocol, n))) {
1944 			char *tmp = estrndup(protocol, n);
1945 
1946 			zend_str_tolower(tmp, n);
1947 			if (NULL == (wrapper = zend_hash_str_find_ptr(wrapper_hash, tmp, n))) {
1948 				char wrapper_name[32];
1949 
1950 				if (n >= sizeof(wrapper_name)) {
1951 					n = sizeof(wrapper_name) - 1;
1952 				}
1953 				PHP_STRLCPY(wrapper_name, protocol, sizeof(wrapper_name), n);
1954 
1955 				php_error_docref(NULL, E_WARNING, "Unable to find the wrapper \"%s\" - did you forget to enable it when you configured PHP?", wrapper_name);
1956 
1957 				wrapper = NULL;
1958 				protocol = NULL;
1959 			}
1960 			efree(tmp);
1961 		}
1962 	}
1963 	/* TODO: curl based streams probably support file:// properly */
1964 	if (!protocol || !strncasecmp(protocol, "file", n))	{
1965 		/* fall back on regular file access */
1966 		php_stream_wrapper *plain_files_wrapper = (php_stream_wrapper*)&php_plain_files_wrapper;
1967 
1968 		if (protocol) {
1969 			int localhost = 0;
1970 
1971 			if (!strncasecmp(path, "file://localhost/", 17)) {
1972 				localhost = 1;
1973 			}
1974 
1975 #ifdef PHP_WIN32
1976 			if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/' && path[n+4] != ':')	{
1977 #else
1978 			if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/') {
1979 #endif
1980 				if (options & REPORT_ERRORS) {
1981 					php_error_docref(NULL, E_WARNING, "Remote host file access not supported, %s", path);
1982 				}
1983 				return NULL;
1984 			}
1985 
1986 			if (path_for_open) {
1987 				/* skip past protocol and :/, but handle windows correctly */
1988 				*path_for_open = (char*)path + n + 1;
1989 				if (localhost == 1) {
1990 					(*path_for_open) += 11;
1991 				}
1992 				while (*(++*path_for_open)=='/') {
1993 					/* intentionally empty */
1994 				}
1995 #ifdef PHP_WIN32
1996 				if (*(*path_for_open + 1) != ':')
1997 #endif
1998 					(*path_for_open)--;
1999 			}
2000 		}
2001 
2002 		if (options & STREAM_LOCATE_WRAPPERS_ONLY) {
2003 			return NULL;
2004 		}
2005 
2006 		if (FG(stream_wrappers)) {
2007 		/* The file:// wrapper may have been disabled/overridden */
2008 
2009 			if (wrapper) {
2010 				/* It was found so go ahead and provide it */
2011 				return wrapper;
2012 			}
2013 
2014 			/* Check again, the original check might have not known the protocol name */
2015 			if ((wrapper = zend_hash_find_ex_ptr(wrapper_hash, ZSTR_KNOWN(ZEND_STR_FILE), 1)) != NULL) {
2016 				return wrapper;
2017 			}
2018 
2019 			if (options & REPORT_ERRORS) {
2020 				php_error_docref(NULL, E_WARNING, "file:// wrapper is disabled in the server configuration");
2021 			}
2022 			return NULL;
2023 		}
2024 
2025 		return plain_files_wrapper;
2026 	}
2027 
2028 	if (wrapper && wrapper->is_url &&
2029 	    (options & STREAM_DISABLE_URL_PROTECTION) == 0 &&
2030 	    (!PG(allow_url_fopen) ||
2031 	     (((options & STREAM_OPEN_FOR_INCLUDE) ||
2032 	       PG(in_user_include)) && !PG(allow_url_include)))) {
2033 		if (options & REPORT_ERRORS) {
2034 			/* protocol[n] probably isn't '\0' */
2035 			if (!PG(allow_url_fopen)) {
2036 				php_error_docref(NULL, E_WARNING, "%.*s:// wrapper is disabled in the server configuration by allow_url_fopen=0", (int)n, protocol);
2037 			} else {
2038 				php_error_docref(NULL, E_WARNING, "%.*s:// wrapper is disabled in the server configuration by allow_url_include=0", (int)n, protocol);
2039 			}
2040 		}
2041 		return NULL;
2042 	}
2043 
2044 	return wrapper;
2045 }
2046 /* }}} */
2047 
2048 /* {{{ _php_stream_mkdir */
2049 PHPAPI int _php_stream_mkdir(const char *path, int mode, int options, php_stream_context *context)
2050 {
2051 	php_stream_wrapper *wrapper = NULL;
2052 
2053 	wrapper = php_stream_locate_url_wrapper(path, NULL, 0);
2054 	if (!wrapper || !wrapper->wops || !wrapper->wops->stream_mkdir) {
2055 		return 0;
2056 	}
2057 
2058 	return wrapper->wops->stream_mkdir(wrapper, path, mode, options, context);
2059 }
2060 /* }}} */
2061 
2062 /* {{{ _php_stream_rmdir */
2063 PHPAPI int _php_stream_rmdir(const char *path, int options, php_stream_context *context)
2064 {
2065 	php_stream_wrapper *wrapper = NULL;
2066 
2067 	wrapper = php_stream_locate_url_wrapper(path, NULL, 0);
2068 	if (!wrapper || !wrapper->wops || !wrapper->wops->stream_rmdir) {
2069 		return 0;
2070 	}
2071 
2072 	return wrapper->wops->stream_rmdir(wrapper, path, options, context);
2073 }
2074 /* }}} */
2075 
2076 /* {{{ _php_stream_stat_path */
2077 PHPAPI int _php_stream_stat_path(const char *path, int flags, php_stream_statbuf *ssb, php_stream_context *context)
2078 {
2079 	php_stream_wrapper *wrapper = NULL;
2080 	const char *path_to_open = path;
2081 
2082 	memset(ssb, 0, sizeof(*ssb));
2083 
2084 	wrapper = php_stream_locate_url_wrapper(path, &path_to_open, 0);
2085 	if (wrapper && wrapper->wops->url_stat) {
2086 		return wrapper->wops->url_stat(wrapper, path_to_open, flags, ssb, context);
2087 	}
2088 	return -1;
2089 }
2090 /* }}} */
2091 
2092 /* {{{ php_stream_opendir */
2093 PHPAPI php_stream *_php_stream_opendir(const char *path, int options,
2094 		php_stream_context *context STREAMS_DC)
2095 {
2096 	php_stream *stream = NULL;
2097 	php_stream_wrapper *wrapper = NULL;
2098 	const char *path_to_open;
2099 
2100 	if (!path || !*path) {
2101 		return NULL;
2102 	}
2103 
2104 	path_to_open = path;
2105 
2106 	wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options);
2107 
2108 	if (wrapper && wrapper->wops->dir_opener) {
2109 		stream = wrapper->wops->dir_opener(wrapper,
2110 				path_to_open, "r", options & ~REPORT_ERRORS, NULL,
2111 				context STREAMS_REL_CC);
2112 
2113 		if (stream) {
2114 			stream->wrapper = wrapper;
2115 			stream->flags |= PHP_STREAM_FLAG_NO_BUFFER | PHP_STREAM_FLAG_IS_DIR;
2116 		}
2117 	} else if (wrapper) {
2118 		php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS, "not implemented");
2119 	}
2120 	if (stream == NULL && (options & REPORT_ERRORS)) {
2121 		php_stream_display_wrapper_errors(wrapper, path, "Failed to open directory");
2122 	}
2123 	php_stream_tidy_wrapper_error_log(wrapper);
2124 
2125 	return stream;
2126 }
2127 /* }}} */
2128 
2129 /* {{{ _php_stream_readdir */
2130 PHPAPI php_stream_dirent *_php_stream_readdir(php_stream *dirstream, php_stream_dirent *ent)
2131 {
2132 
2133 	if (sizeof(php_stream_dirent) == php_stream_read(dirstream, (char*)ent, sizeof(php_stream_dirent))) {
2134 		return ent;
2135 	}
2136 
2137 	return NULL;
2138 }
2139 /* }}} */
2140 
2141 /* {{{ php_stream_open_wrapper_ex */
2142 PHPAPI php_stream *_php_stream_open_wrapper_ex(const char *path, const char *mode, int options,
2143 		zend_string **opened_path, php_stream_context *context STREAMS_DC)
2144 {
2145 	php_stream *stream = NULL;
2146 	php_stream_wrapper *wrapper = NULL;
2147 	const char *path_to_open;
2148 	int persistent = options & STREAM_OPEN_PERSISTENT;
2149 	zend_string *path_str = NULL;
2150 	zend_string *resolved_path = NULL;
2151 	char *copy_of_path = NULL;
2152 
2153 	if (opened_path) {
2154 		if (options & STREAM_OPEN_FOR_ZEND_STREAM) {
2155 			path_str = *opened_path;
2156 		}
2157 		*opened_path = NULL;
2158 	}
2159 
2160 	if (!path || !*path) {
2161 		zend_value_error("Path cannot be empty");
2162 		return NULL;
2163 	}
2164 
2165 	if (options & USE_PATH) {
2166 		if (path_str) {
2167 			resolved_path = zend_resolve_path(path_str);
2168 		} else {
2169 			resolved_path = php_resolve_path(path, strlen(path), PG(include_path));
2170 		}
2171 		if (resolved_path) {
2172 			path = ZSTR_VAL(resolved_path);
2173 			/* we've found this file, don't re-check include_path or run realpath */
2174 			options |= STREAM_ASSUME_REALPATH;
2175 			options &= ~USE_PATH;
2176 		}
2177 		if (EG(exception)) {
2178 			return NULL;
2179 		}
2180 	}
2181 
2182 	path_to_open = path;
2183 
2184 	wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options);
2185 	if ((options & STREAM_USE_URL) && (!wrapper || !wrapper->is_url)) {
2186 		php_error_docref(NULL, E_WARNING, "This function may only be used against URLs");
2187 		if (resolved_path) {
2188 			zend_string_release_ex(resolved_path, 0);
2189 		}
2190 		return NULL;
2191 	}
2192 
2193 	if (wrapper) {
2194 		if (!wrapper->wops->stream_opener) {
2195 			php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS,
2196 					"wrapper does not support stream open");
2197 		} else {
2198 			stream = wrapper->wops->stream_opener(wrapper,
2199 				path_to_open, mode, options & ~REPORT_ERRORS,
2200 				opened_path, context STREAMS_REL_CC);
2201 		}
2202 
2203 		/* if the caller asked for a persistent stream but the wrapper did not
2204 		 * return one, force an error here */
2205 		if (stream && (options & STREAM_OPEN_PERSISTENT) && !stream->is_persistent) {
2206 			php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS,
2207 					"wrapper does not support persistent streams");
2208 			php_stream_close(stream);
2209 			stream = NULL;
2210 		}
2211 
2212 		if (stream) {
2213 			stream->wrapper = wrapper;
2214 		}
2215 	}
2216 
2217 	if (stream) {
2218 		if (opened_path && !*opened_path && resolved_path) {
2219 			*opened_path = resolved_path;
2220 			resolved_path = NULL;
2221 		}
2222 		if (stream->orig_path) {
2223 			pefree(stream->orig_path, persistent);
2224 		}
2225 		copy_of_path = pestrdup(path, persistent);
2226 		stream->orig_path = copy_of_path;
2227 #if ZEND_DEBUG
2228 		stream->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename;
2229 		stream->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno;
2230 #endif
2231 	}
2232 
2233 	if (stream != NULL && (options & STREAM_MUST_SEEK)) {
2234 		php_stream *newstream;
2235 
2236 		switch(php_stream_make_seekable_rel(stream, &newstream,
2237 					(options & STREAM_WILL_CAST)
2238 						? PHP_STREAM_PREFER_STDIO : PHP_STREAM_NO_PREFERENCE)) {
2239 			case PHP_STREAM_UNCHANGED:
2240 				if (resolved_path) {
2241 					zend_string_release_ex(resolved_path, 0);
2242 				}
2243 				return stream;
2244 			case PHP_STREAM_RELEASED:
2245 				if (newstream->orig_path) {
2246 					pefree(newstream->orig_path, persistent);
2247 				}
2248 				newstream->orig_path = pestrdup(path, persistent);
2249 				if (resolved_path) {
2250 					zend_string_release_ex(resolved_path, 0);
2251 				}
2252 				return newstream;
2253 			default:
2254 				php_stream_close(stream);
2255 				stream = NULL;
2256 				if (options & REPORT_ERRORS) {
2257 					char *tmp = estrdup(path);
2258 					php_strip_url_passwd(tmp);
2259 					php_error_docref1(NULL, tmp, E_WARNING, "could not make seekable - %s",
2260 							tmp);
2261 					efree(tmp);
2262 
2263 					options &= ~REPORT_ERRORS;
2264 				}
2265 		}
2266 	}
2267 
2268 	if (stream && stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && strchr(mode, 'a') && stream->position == 0) {
2269 		zend_off_t newpos = 0;
2270 
2271 		/* if opened for append, we need to revise our idea of the initial file position */
2272 		if (0 == stream->ops->seek(stream, 0, SEEK_CUR, &newpos)) {
2273 			stream->position = newpos;
2274 		}
2275 	}
2276 
2277 	if (stream == NULL && (options & REPORT_ERRORS)) {
2278 		php_stream_display_wrapper_errors(wrapper, path, "Failed to open stream");
2279 		if (opened_path && *opened_path) {
2280 			zend_string_release_ex(*opened_path, 0);
2281 			*opened_path = NULL;
2282 		}
2283 	}
2284 	php_stream_tidy_wrapper_error_log(wrapper);
2285 #if ZEND_DEBUG
2286 	if (stream == NULL && copy_of_path != NULL) {
2287 		pefree(copy_of_path, persistent);
2288 	}
2289 #endif
2290 	if (resolved_path) {
2291 		zend_string_release_ex(resolved_path, 0);
2292 	}
2293 	return stream;
2294 }
2295 /* }}} */
2296 
2297 /* {{{ context API */
2298 PHPAPI php_stream_context *php_stream_context_set(php_stream *stream, php_stream_context *context)
2299 {
2300 	php_stream_context *oldcontext = PHP_STREAM_CONTEXT(stream);
2301 
2302 	if (context) {
2303 		stream->ctx = context->res;
2304 		GC_ADDREF(context->res);
2305 	} else {
2306 		stream->ctx = NULL;
2307 	}
2308 	if (oldcontext) {
2309 		zend_list_delete(oldcontext->res);
2310 	}
2311 
2312 	return oldcontext;
2313 }
2314 
2315 PHPAPI void php_stream_notification_notify(php_stream_context *context, int notifycode, int severity,
2316 		char *xmsg, int xcode, size_t bytes_sofar, size_t bytes_max, void * ptr)
2317 {
2318 	if (context && context->notifier)
2319 		context->notifier->func(context, notifycode, severity, xmsg, xcode, bytes_sofar, bytes_max, ptr);
2320 }
2321 
2322 PHPAPI void php_stream_context_free(php_stream_context *context)
2323 {
2324 	if (Z_TYPE(context->options) != IS_UNDEF) {
2325 		zval_ptr_dtor(&context->options);
2326 		ZVAL_UNDEF(&context->options);
2327 	}
2328 	if (context->notifier) {
2329 		php_stream_notification_free(context->notifier);
2330 		context->notifier = NULL;
2331 	}
2332 	efree(context);
2333 }
2334 
2335 PHPAPI php_stream_context *php_stream_context_alloc(void)
2336 {
2337 	php_stream_context *context;
2338 
2339 	context = ecalloc(1, sizeof(php_stream_context));
2340 	context->notifier = NULL;
2341 	array_init(&context->options);
2342 
2343 	context->res = zend_register_resource(context, php_le_stream_context());
2344 	return context;
2345 }
2346 
2347 PHPAPI php_stream_notifier *php_stream_notification_alloc(void)
2348 {
2349 	return ecalloc(1, sizeof(php_stream_notifier));
2350 }
2351 
2352 PHPAPI void php_stream_notification_free(php_stream_notifier *notifier)
2353 {
2354 	if (notifier->dtor) {
2355 		notifier->dtor(notifier);
2356 	}
2357 	efree(notifier);
2358 }
2359 
2360 PHPAPI zval *php_stream_context_get_option(php_stream_context *context,
2361 		const char *wrappername, const char *optionname)
2362 {
2363 	zval *wrapperhash;
2364 
2365 	if (NULL == (wrapperhash = zend_hash_str_find(Z_ARRVAL(context->options), wrappername, strlen(wrappername)))) {
2366 		return NULL;
2367 	}
2368 	return zend_hash_str_find(Z_ARRVAL_P(wrapperhash), optionname, strlen(optionname));
2369 }
2370 
2371 PHPAPI void php_stream_context_set_option(php_stream_context *context,
2372 		const char *wrappername, const char *optionname, zval *optionvalue)
2373 {
2374 	zval *wrapperhash;
2375 	zval category;
2376 
2377 	SEPARATE_ARRAY(&context->options);
2378 	wrapperhash = zend_hash_str_find(Z_ARRVAL(context->options), wrappername, strlen(wrappername));
2379 	if (NULL == wrapperhash) {
2380 		array_init(&category);
2381 		wrapperhash = zend_hash_str_update(Z_ARRVAL(context->options), (char*)wrappername, strlen(wrappername), &category);
2382 	}
2383 	ZVAL_DEREF(optionvalue);
2384 	Z_TRY_ADDREF_P(optionvalue);
2385 	SEPARATE_ARRAY(wrapperhash);
2386 	zend_hash_str_update(Z_ARRVAL_P(wrapperhash), optionname, strlen(optionname), optionvalue);
2387 }
2388 /* }}} */
2389 
2390 /* {{{ php_stream_dirent_alphasort */
2391 PHPAPI int php_stream_dirent_alphasort(const zend_string **a, const zend_string **b)
2392 {
2393 	return strcoll(ZSTR_VAL(*a), ZSTR_VAL(*b));
2394 }
2395 /* }}} */
2396 
2397 /* {{{ php_stream_dirent_alphasortr */
2398 PHPAPI int php_stream_dirent_alphasortr(const zend_string **a, const zend_string **b)
2399 {
2400 	return strcoll(ZSTR_VAL(*b), ZSTR_VAL(*a));
2401 }
2402 /* }}} */
2403 
2404 /* {{{ php_stream_scandir */
2405 PHPAPI int _php_stream_scandir(const char *dirname, zend_string **namelist[], int flags, php_stream_context *context,
2406 			  int (*compare) (const zend_string **a, const zend_string **b))
2407 {
2408 	php_stream *stream;
2409 	php_stream_dirent sdp;
2410 	zend_string **vector = NULL;
2411 	unsigned int vector_size = 0;
2412 	unsigned int nfiles = 0;
2413 
2414 	if (!namelist) {
2415 		return -1;
2416 	}
2417 
2418 	stream = php_stream_opendir(dirname, REPORT_ERRORS, context);
2419 	if (!stream) {
2420 		return -1;
2421 	}
2422 
2423 	while (php_stream_readdir(stream, &sdp)) {
2424 		if (nfiles == vector_size) {
2425 			if (vector_size == 0) {
2426 				vector_size = 10;
2427 			} else {
2428 				if(vector_size*2 < vector_size) {
2429 					/* overflow */
2430 					php_stream_closedir(stream);
2431 					efree(vector);
2432 					return -1;
2433 				}
2434 				vector_size *= 2;
2435 			}
2436 			vector = (zend_string **) safe_erealloc(vector, vector_size, sizeof(char *), 0);
2437 		}
2438 
2439 		vector[nfiles] = zend_string_init(sdp.d_name, strlen(sdp.d_name), 0);
2440 
2441 		nfiles++;
2442 		if(vector_size < 10 || nfiles == 0) {
2443 			/* overflow */
2444 			php_stream_closedir(stream);
2445 			efree(vector);
2446 			return -1;
2447 		}
2448 	}
2449 	php_stream_closedir(stream);
2450 
2451 	*namelist = vector;
2452 
2453 	if (nfiles > 0 && compare) {
2454 		qsort(*namelist, nfiles, sizeof(zend_string *), (int(*)(const void *, const void *))compare);
2455 	}
2456 	return nfiles;
2457 }
2458 /* }}} */
2459