PHP  
 PHP: Test and Code Coverage Analysis
downloads | QA | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
 

LCOV - code coverage report
Current view: top level - main/streams - streams.c (source / functions) Hit Total Coverage
Test: PHP Code Coverage Lines: 901 1035 87.1 %
Date: 2014-07-23 Functions: 68 73 93.2 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10

Generated at Wed, 23 Jul 2014 19:58:45 +0000 (21 hours ago)

Copyright © 2005-2014 The PHP Group
All rights reserved.