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