Coverage Report

Created: 2025-12-31 07:28

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