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

Generated by: LCOV version 1.10

Generated at Sun, 28 Aug 2016 17:10:17 +0000 (5 hours ago)

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