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