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