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: 932 1030 90.5 %
Date: 2015-09-02 Functions: 70 72 97.2 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10

Generated at Wed, 02 Sep 2015 17:19:25 +0000 (2 days ago)

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