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