Coverage Report

Created: 2026-07-25 06:39

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