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