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