Coverage Report

Created: 2026-10-28 06:20

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