Coverage Report

Created: 2025-11-16 06:23

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
6.32k
{
45
6.32k
  return le_stream;
46
6.32k
}
47
48
PHPAPI int php_file_le_pstream(void)
49
6.02k
{
50
6.02k
  return le_pstream;
51
6.02k
}
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
157
{
60
157
  return (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash);
61
157
}
62
63
PHPAPI HashTable *php_stream_get_url_stream_wrappers_hash_global(void)
64
16
{
65
16
  return &url_stream_wrappers_hash;
66
16
}
67
68
static int forget_persistent_resource_id_numbers(zval *el)
69
0
{
70
0
  php_stream *stream;
71
0
  zend_resource *rsrc = Z_RES_P(el);
72
73
0
  if (rsrc->type != le_pstream) {
74
0
    return 0;
75
0
  }
76
77
0
  stream = (php_stream*)rsrc->ptr;
78
79
#if STREAM_DEBUG
80
fprintf(stderr, "forget_persistent: %s:%p\n", stream->ops->label, stream);
81
#endif
82
83
0
  stream->res = NULL;
84
85
0
  if (stream->ctx) {
86
0
    zend_list_delete(stream->ctx);
87
0
    stream->ctx = NULL;
88
0
  }
89
90
0
  return 0;
91
0
}
92
93
PHP_RSHUTDOWN_FUNCTION(streams)
94
247k
{
95
247k
  zval *el;
96
97
247k
  ZEND_HASH_FOREACH_VAL(&EG(persistent_list), el) {
98
247k
    forget_persistent_resource_id_numbers(el);
99
247k
  } ZEND_HASH_FOREACH_END();
100
247k
  return SUCCESS;
101
247k
}
102
103
PHPAPI php_stream *php_stream_encloses(php_stream *enclosing, php_stream *enclosed)
104
2
{
105
2
  php_stream *orig = enclosed->enclosing_stream;
106
107
2
  php_stream_auto_cleanup(enclosed);
108
2
  enclosed->enclosing_stream = enclosing;
109
2
  return orig;
110
2
}
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
2.33k
{
146
2.33k
  if (!FG(wrapper_errors)) {
147
1.66k
    return NULL;
148
1.66k
  } else {
149
670
    return (zend_llist*) zend_hash_str_find_ptr(FG(wrapper_errors), (const char*)&wrapper, sizeof(wrapper));
150
670
  }
151
2.33k
}
152
153
/* {{{ wrapper error reporting */
154
static void php_stream_display_wrapper_errors(php_stream_wrapper *wrapper, const char *path, const char *caption)
155
2.36k
{
156
2.36k
  char *tmp;
157
2.36k
  char *msg;
158
2.36k
  char errstr[256];
159
2.36k
  int free_msg = 0;
160
161
2.36k
  if (EG(exception)) {
162
    /* Don't emit additional warnings if an exception has already been thrown. */
163
12
    return;
164
12
  }
165
166
2.35k
  tmp = estrdup(path);
167
2.35k
  if (wrapper) {
168
2.33k
    zend_llist *err_list = php_get_wrapper_errors_list(wrapper);
169
2.33k
    if (err_list) {
170
670
      size_t l = 0;
171
670
      int brlen;
172
670
      int i;
173
670
      int count = (int)zend_llist_count(err_list);
174
670
      const char *br;
175
670
      const char **err_buf_p;
176
670
      zend_llist_position pos;
177
178
670
      if (PG(html_errors)) {
179
0
        brlen = 7;
180
0
        br = "<br />\n";
181
670
      } else {
182
670
        brlen = 1;
183
670
        br = "\n";
184
670
      }
185
186
670
      for (err_buf_p = zend_llist_get_first_ex(err_list, &pos), i = 0;
187
1.34k
          err_buf_p;
188
670
          err_buf_p = zend_llist_get_next_ex(err_list, &pos), i++) {
189
670
        l += strlen(*err_buf_p);
190
670
        if (i < count - 1) {
191
0
          l += brlen;
192
0
        }
193
670
      }
194
670
      msg = emalloc(l + 1);
195
670
      msg[0] = '\0';
196
670
      for (err_buf_p = zend_llist_get_first_ex(err_list, &pos), i = 0;
197
1.34k
          err_buf_p;
198
670
          err_buf_p = zend_llist_get_next_ex(err_list, &pos), i++) {
199
670
        strcat(msg, *err_buf_p);
200
670
        if (i < count - 1) {
201
0
          strcat(msg, br);
202
0
        }
203
670
      }
204
205
670
      free_msg = 1;
206
1.66k
    } else {
207
1.66k
      if (wrapper == &php_plain_files_wrapper) {
208
1.66k
        msg = php_socket_strerror_s(errno, errstr, sizeof(errstr));
209
1.66k
      } else {
210
7
        msg = "operation failed";
211
7
      }
212
1.66k
    }
213
2.33k
  } else {
214
15
    msg = "no suitable wrapper could be found";
215
15
  }
216
217
2.35k
  php_strip_url_passwd(tmp);
218
2.35k
  php_error_docref1(NULL, tmp, E_WARNING, "%s: %s", caption, msg);
219
2.35k
  efree(tmp);
220
2.35k
  if (free_msg) {
221
670
    efree(msg);
222
670
  }
223
2.35k
}
224
225
static void php_stream_tidy_wrapper_error_log(php_stream_wrapper *wrapper)
226
3.33k
{
227
3.33k
  if (wrapper && FG(wrapper_errors)) {
228
670
    zend_hash_str_del(FG(wrapper_errors), (const char*)&wrapper, sizeof(wrapper));
229
670
  }
230
3.33k
}
231
232
static void wrapper_error_dtor(void *error)
233
670
{
234
670
  efree(*(char**)error);
235
670
}
236
237
670
static void wrapper_list_dtor(zval *item) {
238
670
  zend_llist *list = (zend_llist*)Z_PTR_P(item);
239
670
  zend_llist_destroy(list);
240
670
  efree(list);
241
670
}
242
243
PHPAPI void php_stream_wrapper_log_error(const php_stream_wrapper *wrapper, int options, const char *fmt, ...)
244
670
{
245
670
  va_list args;
246
670
  char *buffer = NULL;
247
248
670
  va_start(args, fmt);
249
670
  vspprintf(&buffer, 0, fmt, args);
250
670
  va_end(args);
251
252
670
  if ((options & REPORT_ERRORS) || wrapper == NULL) {
253
0
    php_error_docref(NULL, E_WARNING, "%s", buffer);
254
0
    efree(buffer);
255
670
  } else {
256
670
    zend_llist *list = NULL;
257
670
    if (!FG(wrapper_errors)) {
258
10
      ALLOC_HASHTABLE(FG(wrapper_errors));
259
10
      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
670
    if (!list) {
265
670
      zend_llist new_list;
266
670
      zend_llist_init(&new_list, sizeof(buffer), wrapper_error_dtor, 0);
267
670
      list = zend_hash_str_update_mem(FG(wrapper_errors), (const char*)&wrapper,
268
670
          sizeof(wrapper), &new_list, sizeof(new_list));
269
670
    }
270
271
    /* append to linked list */
272
670
    zend_llist_add_element(list, &buffer);
273
670
  }
274
670
}
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
6.95k
{
282
6.95k
  php_stream *ret;
283
284
6.95k
  ret = (php_stream*) pemalloc_rel_orig(sizeof(php_stream), persistent_id ? 1 : 0);
285
286
6.95k
  memset(ret, 0, sizeof(php_stream));
287
288
6.95k
  ret->readfilters.stream = ret;
289
6.95k
  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
6.95k
  ret->ops = ops;
296
6.95k
  ret->abstract = abstract;
297
6.95k
  ret->is_persistent = persistent_id ? 1 : 0;
298
6.95k
  ret->chunk_size = FG(def_chunk_size);
299
300
6.95k
#if ZEND_DEBUG
301
6.95k
  ret->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename;
302
6.95k
  ret->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno;
303
6.95k
#endif
304
305
6.95k
  if (FG(auto_detect_line_endings)) {
306
0
    ret->flags |= PHP_STREAM_FLAG_DETECT_EOL;
307
0
  }
308
309
6.95k
  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
6.95k
  ret->res = zend_register_resource(ret, persistent_id ? le_pstream : le_stream);
317
6.95k
  strlcpy(ret->mode, mode, sizeof(ret->mode));
318
319
6.95k
  ret->wrapper          = NULL;
320
6.95k
  ret->wrapperthis      = NULL;
321
6.95k
  ZVAL_UNDEF(&ret->wrapperdata);
322
6.95k
  ret->stdiocast        = NULL;
323
6.95k
  ret->orig_path        = NULL;
324
6.95k
  ret->ctx              = NULL;
325
6.95k
  ret->readbuf          = NULL;
326
6.95k
  ret->enclosing_stream = NULL;
327
328
6.95k
  return ret;
329
6.95k
}
330
/* }}} */
331
332
PHPAPI int _php_stream_free_enclosed(php_stream *stream_enclosed, int close_options) /* {{{ */
333
2
{
334
2
  return php_stream_free(stream_enclosed,
335
2
    close_options | PHP_STREAM_FREE_IGNORE_ENCLOSING);
336
2
}
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
7.06k
{
369
7.06k
  int ret = 1;
370
7.06k
  int preserve_handle = close_options & PHP_STREAM_FREE_PRESERVE_HANDLE ? 1 : 0;
371
7.06k
  int release_cast = 1;
372
7.06k
  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
7.06k
  if ((EG(flags) & EG_FLAGS_IN_RESOURCE_SHUTDOWN) &&
382
677
      !(close_options & (PHP_STREAM_FREE_RSRC_DTOR|PHP_STREAM_FREE_IGNORE_ENCLOSING))) {
383
0
    return 1;
384
0
  }
385
386
7.06k
  context = PHP_STREAM_CONTEXT(stream);
387
388
7.06k
  if ((stream->flags & PHP_STREAM_FLAG_NO_CLOSE) ||
389
7.06k
      ((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
7.06k
  if (stream->in_free) {
403
    /* hopefully called recursively from the enclosing stream; the pointer was NULLed below */
404
114
    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
114
    } else {
407
114
      return 1; /* recursion protection */
408
114
    }
409
114
  }
410
411
6.95k
  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
6.95k
  if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) &&
416
6.84k
      !(close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) &&
417
6.84k
      (close_options & (PHP_STREAM_FREE_CALL_DTOR | PHP_STREAM_FREE_RELEASE_STREAM)) && /* always? */
418
6.84k
      (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
6.95k
  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
6.95k
  if (stream->flags & PHP_STREAM_FLAG_WAS_WRITTEN || stream->writefilters.head) {
452
    /* make sure everything is saved */
453
6.02k
    _php_stream_flush(stream, 1);
454
6.02k
  }
455
456
  /* If not called from the resource dtor, remove the stream from the resource list. */
457
6.95k
  if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0 && stream->res) {
458
    /* Close resource, but keep it in resource list */
459
114
    zend_list_close(stream->res);
460
114
    if ((close_options & PHP_STREAM_FREE_KEEP_RSRC) == 0) {
461
      /* Completely delete zend_resource, if not referenced */
462
114
      zend_list_delete(stream->res);
463
114
      stream->res = NULL;
464
114
    }
465
114
  }
466
467
6.95k
  if (close_options & PHP_STREAM_FREE_CALL_DTOR) {
468
6.95k
    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
6.95k
    ret = stream->ops->close(stream, preserve_handle ? 0 : 1);
481
6.95k
    stream->abstract = NULL;
482
483
    /* tidy up any FILE* that might have been fdopened */
484
6.95k
    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
6.95k
  }
490
491
6.95k
  if (close_options & PHP_STREAM_FREE_RELEASE_STREAM) {
492
6.30k
    while (stream->readfilters.head) {
493
27
      if (stream->readfilters.head->res != NULL) {
494
0
        zend_list_close(stream->readfilters.head->res);
495
0
      }
496
27
      php_stream_filter_remove(stream->readfilters.head, 1);
497
27
    }
498
6.28k
    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
6.28k
    if (stream->wrapper && stream->wrapper->wops && stream->wrapper->wops->stream_closer) {
506
178
      stream->wrapper->wops->stream_closer(stream->wrapper, stream);
507
178
      stream->wrapper = NULL;
508
178
    }
509
510
6.28k
    if (Z_TYPE(stream->wrapperdata) != IS_UNDEF) {
511
178
      zval_ptr_dtor(&stream->wrapperdata);
512
178
      ZVAL_UNDEF(&stream->wrapperdata);
513
178
    }
514
515
6.28k
    if (stream->readbuf) {
516
47
      pefree(stream->readbuf, stream->is_persistent);
517
47
      stream->readbuf = NULL;
518
47
    }
519
520
6.28k
    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
6.28k
    if (stream->orig_path) {
526
107
      pefree(stream->orig_path, stream->is_persistent);
527
107
      stream->orig_path = NULL;
528
107
    }
529
530
6.28k
    pefree(stream, stream->is_persistent);
531
6.28k
  }
532
533
6.95k
  if (context) {
534
0
    zend_list_delete(context->res);
535
0
  }
536
537
6.95k
  return ret;
538
6.95k
}
539
/* }}} */
540
541
/* {{{ generic stream operations */
542
543
PHPAPI zend_result _php_stream_fill_read_buffer(php_stream *stream, size_t size)
544
91
{
545
  /* allocate/fill the buffer */
546
547
91
  zend_result retval;
548
91
  bool old_eof = stream->eof;
549
550
91
  if (stream->readfilters.head) {
551
27
    size_t to_read_now = MIN(size, stream->chunk_size);
552
27
    char *chunk_buf;
553
27
    php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL };
554
27
    php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap;
555
556
    /* allocate a buffer for reading chunks */
557
27
    chunk_buf = emalloc(stream->chunk_size);
558
559
27
    while (!stream->eof && (stream->writepos - stream->readpos < (zend_off_t)to_read_now)) {
560
27
      ssize_t justread = 0;
561
27
      int flags;
562
27
      php_stream_bucket *bucket;
563
27
      php_stream_filter_status_t status = PSFS_ERR_FATAL;
564
27
      php_stream_filter *filter;
565
566
      /* read a chunk into a bucket */
567
27
      justread = stream->ops->read(stream, chunk_buf, stream->chunk_size);
568
27
      if (justread < 0 && stream->writepos == stream->readpos) {
569
0
        efree(chunk_buf);
570
0
        retval = FAILURE;
571
0
        goto out_check_eof;
572
27
      } 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
27
      } else {
580
27
        flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC;
581
27
      }
582
583
      /* wind the handle... */
584
36
      for (filter = stream->readfilters.head; filter; filter = filter->next) {
585
27
        status = filter->fops->filter(stream, filter, brig_inp, brig_outp, NULL, flags);
586
587
27
        if (status != PSFS_PASS_ON) {
588
18
          break;
589
18
        }
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
9
        brig_swap = brig_inp;
595
9
        brig_inp = brig_outp;
596
9
        brig_outp = brig_swap;
597
9
        memset(brig_outp, 0, sizeof(*brig_outp));
598
9
      }
599
600
27
      switch (status) {
601
9
        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
18
          while (brig_inp->head) {
606
9
            bucket = brig_inp->head;
607
            /* reduce buffer memory consumption if possible, to avoid a realloc */
608
9
            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
9
            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
9
            if (bucket->buflen) {
622
0
              memcpy(stream->readbuf + stream->writepos, bucket->buf, bucket->buflen);
623
0
            }
624
9
            stream->writepos += bucket->buflen;
625
626
9
            php_stream_bucket_unlink(bucket);
627
9
            php_stream_bucket_delref(bucket);
628
9
          }
629
9
          break;
630
631
7
        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
11
          while ((bucket = brig_outp->head)) {
638
4
            php_stream_bucket_unlink(bucket);
639
4
            php_stream_bucket_delref(bucket);
640
4
          }
641
7
          break;
642
643
11
        case PSFS_ERR_FATAL:
644
          /* some fatal error. Theoretically, the stream is borked, so all
645
           * further reads should fail. */
646
11
          stream->eof = 1;
647
11
          stream->fatal_error = 1;
648
          /* free all data left in brigades */
649
11
          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
11
          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
11
          efree(chunk_buf);
660
11
          retval = FAILURE;
661
11
          goto out_is_eof;
662
27
      }
663
664
16
      if (justread <= 0) {
665
16
        break;
666
16
      }
667
16
    }
668
669
16
    efree(chunk_buf);
670
16
    return SUCCESS;
671
64
  } else {
672
    /* is there enough data in the buffer ? */
673
64
    if (stream->writepos - stream->readpos < (zend_off_t)size) {
674
64
      ssize_t justread = 0;
675
676
      /* reduce buffer memory consumption if possible, to avoid a realloc */
677
64
      if (stream->readbuf && stream->readbuflen - stream->writepos < stream->chunk_size) {
678
7
        if (stream->writepos > stream->readpos) {
679
0
          memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->writepos - stream->readpos);
680
0
        }
681
7
        stream->writepos -= stream->readpos;
682
7
        stream->readpos = 0;
683
7
      }
684
685
      /* grow the buffer if required
686
       * TODO: this can fail for persistent streams */
687
64
      if (stream->readbuflen - stream->writepos < stream->chunk_size) {
688
57
        stream->readbuflen += stream->chunk_size;
689
57
        stream->readbuf = perealloc(stream->readbuf, stream->readbuflen,
690
57
            stream->is_persistent);
691
57
      }
692
693
64
      justread = stream->ops->read(stream, (char*)stream->readbuf + stream->writepos,
694
64
          stream->readbuflen - stream->writepos
695
64
          );
696
64
      if (justread < 0) {
697
20
        retval = FAILURE;
698
20
        goto out_check_eof;
699
20
      }
700
44
      stream->writepos += justread;
701
44
      retval = SUCCESS;
702
44
      goto out_check_eof;
703
64
    }
704
0
    return SUCCESS;
705
64
  }
706
707
49
out_check_eof:
708
49
  if (old_eof != stream->eof) {
709
36
out_is_eof:
710
36
    php_stream_notify_completed(PHP_STREAM_CONTEXT(stream));
711
36
  }
712
60
  return retval;
713
49
}
714
715
PHPAPI ssize_t _php_stream_read(php_stream *stream, char *buf, size_t size)
716
1.89M
{
717
1.89M
  ssize_t toread = 0, didread = 0;
718
719
3.79M
  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.89M
    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.89M
    if (size == 0) {
742
0
      break;
743
0
    }
744
745
1.89M
    if (!stream->readfilters.head && ((stream->flags & PHP_STREAM_FLAG_NO_BUFFER) || stream->chunk_size == 1)) {
746
1.89M
      toread = stream->ops->read(stream, buf, size);
747
1.89M
      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.89M
    } else {
756
85
      if (php_stream_fill_read_buffer(stream, size) != SUCCESS) {
757
31
        if (didread == 0) {
758
31
          return -1;
759
31
        }
760
0
        break;
761
31
      }
762
763
54
      toread = stream->writepos - stream->readpos;
764
54
      if ((size_t) toread > size) {
765
0
        toread = size;
766
0
      }
767
768
54
      if (toread > 0) {
769
13
        memcpy(buf, stream->readbuf + stream->readpos, toread);
770
13
        stream->readpos += toread;
771
13
      }
772
54
    }
773
1.89M
    if (toread > 0) {
774
1.89M
      didread += toread;
775
1.89M
      buf += toread;
776
1.89M
      size -= toread;
777
1.89M
      stream->has_buffered_data = 1;
778
1.89M
    } else {
779
      /* EOF, or temporary end of data (for non-blocking mode). */
780
1.22k
      break;
781
1.22k
    }
782
783
    /* just break anyway, to avoid greedy read for file://, php://memory, and php://temp */
784
1.89M
    if ((stream->wrapper != &php_plain_files_wrapper) &&
785
1.89M
      (stream->ops != &php_stream_memory_ops) &&
786
13
      (stream->ops != &php_stream_temp_ops)) {
787
13
      break;
788
13
    }
789
1.89M
  }
790
791
1.89M
  if (didread > 0) {
792
1.89M
    stream->position += didread;
793
1.89M
    stream->has_buffered_data = 0;
794
1.89M
  }
795
796
1.89M
  return didread;
797
1.89M
}
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
142
{
821
  /* if there is data in the buffer, it's not EOF */
822
142
  if (stream->writepos - stream->readpos > 0) {
823
0
    return 0;
824
0
  }
825
826
  /* use the configured timeout when checking eof */
827
142
  if (!stream->eof && PHP_STREAM_OPTION_RETURN_ERR ==
828
140
        php_stream_set_option(stream, PHP_STREAM_OPTION_CHECK_LIVENESS,
829
142
        0, NULL)) {
830
0
    stream->eof = 1;
831
0
  }
832
833
142
  return stream->eof;
834
142
}
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.26M
{
848
1.26M
  char buf;
849
850
1.26M
  if (php_stream_read(stream, &buf, 1) > 0) {
851
1.26M
    return buf & 0xff;
852
1.26M
  }
853
543
  return EOF;
854
1.26M
}
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
88
{
870
88
  memset(ssb, 0, sizeof(*ssb));
871
872
  /* if the stream was wrapped, allow the wrapper to stat it */
873
88
  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
88
  if (stream->ops->stat == NULL) {
882
0
    return -1;
883
0
  }
884
885
88
  return (stream->ops->stat)(stream, ssb);
886
88
}
887
888
PHPAPI const char *php_stream_locate_eol(php_stream *stream, zend_string *buf)
889
11
{
890
11
  size_t avail;
891
11
  const char *eol = NULL;
892
11
  const char *readptr;
893
894
11
  if (!buf) {
895
11
    readptr = (char*)stream->readbuf + stream->readpos;
896
11
    avail = stream->writepos - stream->readpos;
897
11
  } else {
898
0
    readptr = ZSTR_VAL(buf);
899
0
    avail = ZSTR_LEN(buf);
900
0
  }
901
902
  /* Look for EOL */
903
11
  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
11
  } else if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) {
918
0
    eol = memchr(readptr, '\r', avail);
919
11
  } else {
920
    /* unix (and dos) line endings */
921
11
    eol = memchr(readptr, '\n', avail);
922
11
  }
923
924
11
  return eol;
925
11
}
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
14
{
933
14
  size_t avail = 0;
934
14
  size_t current_buf_size = 0;
935
14
  size_t total_copied = 0;
936
14
  int grow_mode = 0;
937
14
  char *bufstart = buf;
938
939
14
  if (buf == NULL) {
940
14
    grow_mode = 1;
941
14
  } 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
20
  for (;;) {
959
20
    avail = stream->writepos - stream->readpos;
960
961
20
    if (avail > 0) {
962
11
      size_t cpysz = 0;
963
11
      char *readptr;
964
11
      const char *eol;
965
11
      int done = 0;
966
967
11
      readptr = (char*)stream->readbuf + stream->readpos;
968
11
      eol = php_stream_locate_eol(stream, NULL);
969
970
11
      if (eol) {
971
8
        cpysz = eol - readptr + 1;
972
8
        done = 1;
973
8
      } else {
974
3
        cpysz = avail;
975
3
      }
976
977
11
      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
11
        bufstart = erealloc(bufstart, current_buf_size + cpysz + 1);
986
11
        current_buf_size += cpysz + 1;
987
11
        buf = bufstart + total_copied;
988
11
      } else {
989
0
        if (cpysz >= maxlen - 1) {
990
0
          cpysz = maxlen - 1;
991
0
          done = 1;
992
0
        }
993
0
      }
994
995
11
      memcpy(buf, readptr, cpysz);
996
997
11
      stream->position += cpysz;
998
11
      stream->readpos += cpysz;
999
11
      buf += cpysz;
1000
11
      maxlen -= cpysz;
1001
11
      total_copied += cpysz;
1002
1003
11
      if (done) {
1004
8
        break;
1005
8
      }
1006
11
    } else if (stream->eof) {
1007
3
      break;
1008
6
    } else {
1009
      /* XXX: Should be fine to always read chunk_size */
1010
6
      size_t toread;
1011
1012
6
      if (grow_mode) {
1013
6
        toread = stream->chunk_size;
1014
6
      } 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
6
      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
6
      if (stream->writepos - stream->readpos == 0) {
1029
3
        break;
1030
3
      }
1031
6
    }
1032
20
  }
1033
1034
14
  if (total_copied == 0) {
1035
3
    if (grow_mode) {
1036
3
      assert(bufstart == NULL);
1037
3
    }
1038
3
    return NULL;
1039
3
  }
1040
1041
11
  buf[0] = '\0';
1042
11
  if (returned_len) {
1043
0
    *returned_len = total_copied;
1044
0
  }
1045
1046
11
  return bufstart;
1047
14
}
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
6.02k
{
1170
6.02k
  ssize_t didwrite = 0;
1171
6.02k
  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
6.02k
  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
6.02k
  bool old_eof = stream->eof;
1183
1184
  /* See GH-13071: userspace stream is subject to the memory limit. */
1185
6.02k
  size_t chunk_size = count;
1186
6.02k
  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
12.0k
  while (count > 0) {
1192
6.02k
    ssize_t justwrote = stream->ops->write(stream, buf, MIN(chunk_size, count));
1193
6.02k
    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
6.02k
    buf += justwrote;
1205
6.02k
    count -= justwrote;
1206
6.02k
    didwrite += justwrote;
1207
6.02k
    stream->position += justwrote;
1208
6.02k
  }
1209
1210
6.02k
  retval = didwrite;
1211
1212
6.02k
out:
1213
6.02k
  if (old_eof != stream->eof) {
1214
0
    php_stream_notify_completed(PHP_STREAM_CONTEXT(stream));
1215
0
  }
1216
6.02k
  return retval;
1217
6.02k
}
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
6.02k
{
1297
6.02k
  int ret = 0;
1298
1299
6.02k
  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
6.02k
  stream->flags &= ~PHP_STREAM_FLAG_WAS_WRITTEN;
1304
1305
6.02k
  if (stream->ops->flush) {
1306
6.02k
    ret = stream->ops->flush(stream);
1307
6.02k
  }
1308
1309
6.02k
  return ret;
1310
6.02k
}
1311
1312
PHPAPI ssize_t _php_stream_write(php_stream *stream, const char *buf, size_t count)
1313
6.02k
{
1314
6.02k
  ssize_t bytes;
1315
1316
6.02k
  if (count == 0) {
1317
0
    return 0;
1318
0
  }
1319
1320
6.02k
  ZEND_ASSERT(buf != NULL);
1321
6.02k
  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
6.02k
  if (stream->writefilters.head) {
1327
0
    bytes = _php_stream_write_filtered(stream, buf, count, PSFS_FLAG_NORMAL);
1328
6.02k
  } else {
1329
6.02k
    bytes = _php_stream_write_buffer(stream, buf, count);
1330
6.02k
  }
1331
1332
6.02k
  if (bytes) {
1333
6.02k
    stream->flags |= PHP_STREAM_FLAG_WAS_WRITTEN;
1334
6.02k
  }
1335
1336
6.02k
  return bytes;
1337
6.02k
}
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
474k
{
1361
474k
  return stream->position;
1362
474k
}
1363
1364
PHPAPI int _php_stream_seek(php_stream *stream, zend_off_t offset, int whence)
1365
253k
{
1366
253k
  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
253k
  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
253k
  if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) {
1403
253k
    int ret;
1404
1405
253k
    if (stream->writefilters.head) {
1406
0
      _php_stream_flush(stream, 0);
1407
0
    }
1408
1409
253k
    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
247k
      case SEEK_SET:
1420
247k
        if (offset < 0) {
1421
0
          return -1;
1422
0
        }
1423
253k
    }
1424
253k
    ret = stream->ops->seek(stream, offset, whence, &stream->position);
1425
1426
253k
    if (((stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) || ret == 0) {
1427
253k
      if (ret == 0) {
1428
253k
        stream->eof = 0;
1429
253k
        stream->fatal_error = 0;
1430
253k
      }
1431
1432
      /* invalidate the buffer contents */
1433
253k
      stream->readpos = stream->writepos = 0;
1434
1435
253k
      return ret;
1436
253k
    }
1437
    /* else the stream has decided that it can't support seeking after all;
1438
     * fall through to attempt emulation */
1439
253k
  }
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
1.05k
{
1463
1.05k
  int ret = PHP_STREAM_OPTION_RETURN_NOTIMPL;
1464
1465
1.05k
  if (stream->ops->set_option) {
1466
771
    ret = stream->ops->set_option(stream, option, value, ptrparam);
1467
771
  }
1468
1469
1.05k
  if (ret == PHP_STREAM_OPTION_RETURN_NOTIMPL) {
1470
341
    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
61
      case PHP_STREAM_OPTION_READ_BUFFER:
1478
        /* try to match the buffer mode as best we can */
1479
61
        if (value == PHP_STREAM_BUFFER_NONE) {
1480
61
          stream->flags |= PHP_STREAM_FLAG_NO_BUFFER;
1481
61
        } else if (stream->flags & PHP_STREAM_FLAG_NO_BUFFER) {
1482
0
          stream->flags ^= PHP_STREAM_FLAG_NO_BUFFER;
1483
0
        }
1484
61
        ret = PHP_STREAM_OPTION_RETURN_OK;
1485
61
        break;
1486
1487
280
      default:
1488
280
        ;
1489
341
    }
1490
341
  }
1491
1492
1.05k
  return ret;
1493
1.05k
}
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
6
{
1550
6
  ssize_t ret = 0;
1551
6
  char *ptr;
1552
6
  size_t len = 0, buflen;
1553
6
  php_stream_statbuf ssbuf;
1554
6
  zend_string *result;
1555
1556
6
  if (maxlen == 0) {
1557
0
    return ZSTR_EMPTY_ALLOC();
1558
0
  }
1559
1560
6
  if (maxlen == PHP_STREAM_COPY_ALL) {
1561
6
    maxlen = 0;
1562
6
  }
1563
1564
6
  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
6
  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
6
  } else {
1603
6
    buflen = CHUNK_SIZE;
1604
6
  }
1605
1606
6
  result = zend_string_alloc(buflen, persistent);
1607
6
  ptr = ZSTR_VAL(result);
1608
1609
6
  const int min_room = CHUNK_SIZE / 4;
1610
  // TODO: Propagate error?
1611
6
  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
6
  if (len) {
1629
0
    result = zend_string_truncate(result, len, persistent);
1630
0
    ZSTR_VAL(result)[len] = '\0';
1631
6
  } else {
1632
6
    zend_string_free(result);
1633
6
    result = NULL;
1634
6
  }
1635
1636
6
  return result;
1637
6
}
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
6.95k
{
1854
6.95k
  php_stream *stream = (php_stream*)rsrc->ptr;
1855
  /* set the return value for pclose */
1856
6.95k
  FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR);
1857
6.95k
}
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
247k
{
1867
247k
  FG(user_stream_current_filename) = NULL;
1868
247k
  if (FG(stream_wrappers)) {
1869
108
    zend_hash_destroy(FG(stream_wrappers));
1870
108
    efree(FG(stream_wrappers));
1871
108
    FG(stream_wrappers) = NULL;
1872
108
  }
1873
1874
247k
  if (FG(stream_filters)) {
1875
82
    zend_hash_destroy(FG(stream_filters));
1876
82
    efree(FG(stream_filters));
1877
82
    FG(stream_filters) = NULL;
1878
82
  }
1879
1880
247k
  if (FG(wrapper_errors)) {
1881
10
    zend_hash_destroy(FG(wrapper_errors));
1882
10
    efree(FG(wrapper_errors));
1883
10
    FG(wrapper_errors) = NULL;
1884
10
  }
1885
247k
}
1886
1887
zend_result php_init_stream_wrappers(int module_number)
1888
16
{
1889
16
  le_stream = zend_register_list_destructors_ex(stream_resource_regular_dtor, NULL, "stream", module_number);
1890
16
  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
16
  le_stream_filter = zend_register_list_destructors_ex(NULL, NULL, "stream filter", module_number);
1894
1895
16
  zend_hash_init(&url_stream_wrappers_hash, 8, NULL, NULL, 1);
1896
16
  zend_hash_init(php_get_stream_filters_hash_global(), 8, NULL, NULL, 1);
1897
16
  zend_hash_init(php_stream_xport_get_hash(), 8, NULL, NULL, 1);
1898
1899
16
  return (php_stream_xport_register("tcp", php_stream_generic_socket_factory) == SUCCESS
1900
16
      &&
1901
16
      php_stream_xport_register("udp", php_stream_generic_socket_factory) == SUCCESS
1902
16
#if defined(AF_UNIX) && !(defined(PHP_WIN32) || defined(__riscos__))
1903
16
      &&
1904
16
      php_stream_xport_register("unix", php_stream_generic_socket_factory) == SUCCESS
1905
16
      &&
1906
16
      php_stream_xport_register("udg", php_stream_generic_socket_factory) == SUCCESS
1907
16
#endif
1908
16
    ) ? SUCCESS : FAILURE;
1909
16
}
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
348
{
1923
1.56k
  for (size_t i = 0; i < protocol_len; i++) {
1924
1.22k
    if (!isalnum((int)protocol[i]) &&
1925
4
      protocol[i] != '+' &&
1926
4
      protocol[i] != '-' &&
1927
4
      protocol[i] != '.') {
1928
4
      return FAILURE;
1929
4
    }
1930
1.22k
  }
1931
1932
344
  return SUCCESS;
1933
348
}
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
96
{
1938
96
  size_t protocol_len = strlen(protocol);
1939
96
  zend_result ret;
1940
96
  zend_string *str;
1941
1942
96
  if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) {
1943
0
    return FAILURE;
1944
0
  }
1945
1946
96
  str = zend_string_init_interned(protocol, protocol_len, 1);
1947
96
  ret = zend_hash_add_ptr(&url_stream_wrappers_hash, str, (void*)wrapper) ? SUCCESS : FAILURE;
1948
96
  zend_string_release_ex(str, 1);
1949
96
  return ret;
1950
96
}
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
108
{
1959
108
  ALLOC_HASHTABLE(FG(stream_wrappers));
1960
108
  zend_hash_init(FG(stream_wrappers), zend_hash_num_elements(&url_stream_wrappers_hash), NULL, NULL, 0);
1961
108
  zend_hash_copy(FG(stream_wrappers), &url_stream_wrappers_hash, NULL);
1962
108
}
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
252
{
1967
252
  if (php_stream_wrapper_scheme_validate(ZSTR_VAL(protocol), ZSTR_LEN(protocol)) == FAILURE) {
1968
4
    return FAILURE;
1969
4
  }
1970
1971
248
  if (!FG(stream_wrappers)) {
1972
108
    clone_wrapper_hash();
1973
108
  }
1974
1975
248
  return zend_hash_add_ptr(FG(stream_wrappers), protocol, wrapper) ? SUCCESS : FAILURE;
1976
252
}
1977
1978
PHPAPI zend_result php_unregister_url_stream_wrapper_volatile(zend_string *protocol)
1979
145
{
1980
145
  if (!FG(stream_wrappers)) {
1981
0
    clone_wrapper_hash();
1982
0
  }
1983
1984
145
  return zend_hash_del(FG(stream_wrappers), protocol);
1985
145
}
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
8.80k
{
1991
8.80k
  const HashTable *wrapper_hash = (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash);
1992
8.80k
  php_stream_wrapper *wrapper = NULL;
1993
8.80k
  const char *p, *protocol = NULL;
1994
8.80k
  size_t n = 0;
1995
1996
8.80k
  if (path_for_open) {
1997
8.80k
    *path_for_open = (char*)path;
1998
8.80k
  }
1999
2000
8.80k
  if (options & IGNORE_URL) {
2001
0
    return (php_stream_wrapper*)((options & STREAM_LOCATE_WRAPPERS_ONLY) ? NULL : &php_plain_files_wrapper);
2002
0
  }
2003
2004
44.7k
  for (p = path; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++) {
2005
35.9k
    n++;
2006
35.9k
  }
2007
2008
8.80k
  if ((*p == ':') && (n > 1) && (!strncmp("//", p+1, 2) || (n == 4 && !memcmp("data:", path, 5)))) {
2009
7.08k
    protocol = path;
2010
7.08k
  }
2011
2012
8.80k
  if (protocol) {
2013
7.08k
    if (NULL == (wrapper = zend_hash_str_find_ptr(wrapper_hash, protocol, n))) {
2014
19
      char *tmp = estrndup(protocol, n);
2015
2016
19
      zend_str_tolower(tmp, n);
2017
19
      if (NULL == (wrapper = zend_hash_str_find_ptr(wrapper_hash, tmp, n))) {
2018
19
        char wrapper_name[32];
2019
2020
19
        if (n >= sizeof(wrapper_name)) {
2021
0
          n = sizeof(wrapper_name) - 1;
2022
0
        }
2023
19
        PHP_STRLCPY(wrapper_name, protocol, sizeof(wrapper_name), n);
2024
2025
19
        php_error_docref(NULL, E_WARNING, "Unable to find the wrapper \"%s\" - did you forget to enable it when you configured PHP?", wrapper_name);
2026
2027
19
        wrapper = NULL;
2028
19
        protocol = NULL;
2029
19
      }
2030
19
      efree(tmp);
2031
19
    }
2032
7.08k
  }
2033
  /* TODO: curl based streams probably support file:// properly */
2034
8.80k
  if (!protocol || !strncasecmp(protocol, "file", n))  {
2035
    /* fall back on regular file access */
2036
1.76k
    php_stream_wrapper *plain_files_wrapper = (php_stream_wrapper*)&php_plain_files_wrapper;
2037
2038
1.76k
    if (protocol) {
2039
20
      bool localhost = false;
2040
2041
20
      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
20
      if (!localhost && path[n+3] != '\0' && path[n+3] != '/') {
2049
20
#endif
2050
20
        if (options & REPORT_ERRORS) {
2051
0
          php_error_docref(NULL, E_WARNING, "Remote host file access not supported, %s", path);
2052
0
        }
2053
20
        return NULL;
2054
20
      }
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
1.74k
    if (options & STREAM_LOCATE_WRAPPERS_ONLY) {
2073
0
      return NULL;
2074
0
    }
2075
2076
1.74k
    if (FG(stream_wrappers)) {
2077
    /* The file:// wrapper may have been disabled/overridden */
2078
2079
17
      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
17
      if ((wrapper = zend_hash_find_ex_ptr(wrapper_hash, ZSTR_KNOWN(ZEND_STR_FILE), 1)) != NULL) {
2086
17
        return wrapper;
2087
17
      }
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
17
    }
2094
2095
1.72k
    return plain_files_wrapper;
2096
1.74k
  }
2097
2098
7.04k
  if (wrapper && wrapper->is_url &&
2099
25
      (options & STREAM_DISABLE_URL_PROTECTION) == 0 &&
2100
25
      (!PG(allow_url_fopen) ||
2101
0
       (((options & STREAM_OPEN_FOR_INCLUDE) ||
2102
25
         PG(in_user_include)) && !PG(allow_url_include)))) {
2103
25
    if (options & REPORT_ERRORS) {
2104
      /* protocol[n] probably isn't '\0' */
2105
15
      if (!PG(allow_url_fopen)) {
2106
15
        php_error_docref(NULL, E_WARNING, "%.*s:// wrapper is disabled in the server configuration by allow_url_fopen=0", (int)n, protocol);
2107
15
      } 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
15
    }
2111
25
    return NULL;
2112
25
  }
2113
2114
7.01k
  return wrapper;
2115
7.04k
}
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
152
{
2166
152
  php_stream *stream = NULL;
2167
152
  php_stream_wrapper *wrapper = NULL;
2168
152
  const char *path_to_open;
2169
2170
152
  if (!path || !*path) {
2171
0
    return NULL;
2172
0
  }
2173
2174
152
  path_to_open = path;
2175
2176
152
  wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options);
2177
2178
152
  if (wrapper && wrapper->wops->dir_opener) {
2179
152
    stream = wrapper->wops->dir_opener(wrapper,
2180
152
        path_to_open, "r", options & ~REPORT_ERRORS, NULL,
2181
152
        context STREAMS_REL_CC);
2182
2183
152
    if (stream) {
2184
140
      stream->wrapper = wrapper;
2185
140
      stream->flags |= PHP_STREAM_FLAG_NO_BUFFER | PHP_STREAM_FLAG_IS_DIR;
2186
140
    }
2187
152
  } else if (wrapper) {
2188
0
    php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS, "not implemented");
2189
0
  }
2190
152
  if (stream == NULL && (options & REPORT_ERRORS)) {
2191
12
    php_stream_display_wrapper_errors(wrapper, path, "Failed to open directory");
2192
12
  }
2193
152
  php_stream_tidy_wrapper_error_log(wrapper);
2194
2195
152
  return stream;
2196
152
}
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
5.17k
{
2215
5.17k
  php_stream *stream = NULL;
2216
5.17k
  php_stream_wrapper *wrapper = NULL;
2217
5.17k
  const char *path_to_open;
2218
5.17k
  int persistent = options & STREAM_OPEN_PERSISTENT;
2219
5.17k
  zend_string *path_str = NULL;
2220
5.17k
  zend_string *resolved_path = NULL;
2221
2222
5.17k
  if (opened_path) {
2223
5.16k
    if (options & STREAM_OPEN_FOR_ZEND_STREAM) {
2224
5.16k
      path_str = *opened_path;
2225
5.16k
    }
2226
5.16k
    *opened_path = NULL;
2227
5.16k
  }
2228
2229
5.17k
  if (!path || !*path) {
2230
5
    zend_value_error("Path must not be empty");
2231
5
    return NULL;
2232
5
  }
2233
2234
5.17k
  if (options & USE_PATH) {
2235
5.15k
    if (path_str) {
2236
5.10k
      resolved_path = zend_resolve_path(path_str);
2237
5.10k
    } else {
2238
46
      resolved_path = php_resolve_path(path, strlen(path), PG(include_path));
2239
46
    }
2240
5.15k
    if (resolved_path) {
2241
63
      path = ZSTR_VAL(resolved_path);
2242
      /* we've found this file, don't re-check include_path or run realpath */
2243
63
      options |= STREAM_ASSUME_REALPATH;
2244
63
      options &= ~USE_PATH;
2245
63
    }
2246
5.15k
    if (EG(exception)) {
2247
10
      if (resolved_path) {
2248
0
        zend_string_release_ex(resolved_path, false);
2249
0
      }
2250
10
      return NULL;
2251
10
    }
2252
5.15k
  }
2253
2254
5.16k
  path_to_open = path;
2255
2256
5.16k
  wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options);
2257
5.16k
  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
5.16k
  if (wrapper) {
2266
3.16k
    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
3.16k
    } else {
2270
3.16k
      stream = wrapper->wops->stream_opener(wrapper,
2271
3.16k
        path_to_open, mode, options & ~REPORT_ERRORS,
2272
3.16k
        opened_path, context STREAMS_REL_CC);
2273
3.16k
    }
2274
2275
    /* if the caller asked for a persistent stream but the wrapper did not
2276
     * return one, force an error here */
2277
3.16k
    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
3.16k
    if (stream) {
2285
825
      stream->wrapper = wrapper;
2286
825
    }
2287
3.16k
  }
2288
2289
5.16k
  if (stream) {
2290
825
    if (opened_path && !*opened_path && resolved_path) {
2291
0
      *opened_path = resolved_path;
2292
0
      resolved_path = NULL;
2293
0
    }
2294
825
    if (stream->orig_path) {
2295
46
      pefree(stream->orig_path, persistent);
2296
46
    }
2297
825
    stream->orig_path = pestrdup(path, persistent);
2298
825
#if ZEND_DEBUG
2299
825
    stream->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename;
2300
825
    stream->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno;
2301
825
#endif
2302
825
  }
2303
2304
5.16k
  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
5.16k
  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
5.16k
  if (stream == NULL && (options & REPORT_ERRORS)) {
2349
2.35k
    php_stream_display_wrapper_errors(wrapper, path, "Failed to open stream");
2350
2.35k
    if (opened_path && *opened_path) {
2351
0
      zend_string_release_ex(*opened_path, 0);
2352
0
      *opened_path = NULL;
2353
0
    }
2354
2.35k
  }
2355
5.16k
  php_stream_tidy_wrapper_error_log(wrapper);
2356
5.16k
  if (resolved_path) {
2357
63
    zend_string_release_ex(resolved_path, 0);
2358
63
  }
2359
5.16k
  return stream;
2360
5.16k
}
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
30
{
2390
30
  if (Z_TYPE(context->options) != IS_UNDEF) {
2391
0
    zval_ptr_dtor(&context->options);
2392
0
    ZVAL_UNDEF(&context->options);
2393
0
  }
2394
30
  if (context->notifier) {
2395
0
    php_stream_notification_free(context->notifier);
2396
0
    context->notifier = NULL;
2397
0
  }
2398
30
  efree(context);
2399
30
}
2400
2401
PHPAPI php_stream_context *php_stream_context_alloc(void)
2402
30
{
2403
30
  php_stream_context *context;
2404
2405
30
  context = ecalloc(1, sizeof(php_stream_context));
2406
30
  array_init(&context->options);
2407
2408
30
  context->res = zend_register_resource(context, php_le_stream_context());
2409
30
  return context;
2410
30
}
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
/* }}} */