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