Coverage Report

Created: 2026-09-14 06:25

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