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: 927 1025 90.4 %
Date: 2015-05-21 Functions: 70 72 97.2 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10

Generated at Thu, 21 May 2015 19:59:10 +0000 (2 days ago)

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