Coverage Report

Created: 2026-04-01 06:49

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