forked from php/php-src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreams.c
2341 lines (1974 loc) · 64.7 KB
/
streams.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2014 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Wez Furlong <[email protected]> |
| Borrowed code from: |
| Rasmus Lerdorf <[email protected]> |
| Jim Winstead <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#define _GNU_SOURCE
#include "php.h"
#include "php_globals.h"
#include "php_network.h"
#include "php_open_temporary_file.h"
#include "ext/standard/file.h"
#include "ext/standard/basic_functions.h" /* for BG(mmap_file) (not strictly required) */
#include "ext/standard/php_string.h" /* for php_memnstr, used by php_stream_get_record() */
#include <stddef.h>
#include <fcntl.h>
#include "php_streams_int.h"
/* {{{ resource and registration code */
/* Global wrapper hash, copied to FG(stream_wrappers) on registration of volatile wrapper */
static HashTable url_stream_wrappers_hash;
static int le_stream = FAILURE; /* true global */
static int le_pstream = FAILURE; /* true global */
static int le_stream_filter = FAILURE; /* true global */
PHPAPI int php_file_le_stream(void)
{
return le_stream;
}
PHPAPI int php_file_le_pstream(void)
{
return le_pstream;
}
PHPAPI int php_file_le_stream_filter(void)
{
return le_stream_filter;
}
PHPAPI HashTable *_php_stream_get_url_stream_wrappers_hash(TSRMLS_D)
{
return (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash);
}
PHPAPI HashTable *php_stream_get_url_stream_wrappers_hash_global(void)
{
return &url_stream_wrappers_hash;
}
static int _php_stream_release_context(zend_rsrc_list_entry *le, void *pContext TSRMLS_DC)
{
if (le->ptr == pContext) {
return --le->refcount == 0;
}
return 0;
}
static int forget_persistent_resource_id_numbers(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
php_stream *stream;
if (Z_TYPE_P(rsrc) != le_pstream) {
return 0;
}
stream = (php_stream*)rsrc->ptr;
#if STREAM_DEBUG
fprintf(stderr, "forget_persistent: %s:%p\n", stream->ops->label, stream);
#endif
stream->rsrc_id = FAILURE;
if (stream->context) {
zend_hash_apply_with_argument(&EG(regular_list),
(apply_func_arg_t) _php_stream_release_context,
stream->context TSRMLS_CC);
stream->context = NULL;
}
return 0;
}
PHP_RSHUTDOWN_FUNCTION(streams)
{
zend_hash_apply(&EG(persistent_list), (apply_func_t)forget_persistent_resource_id_numbers TSRMLS_CC);
return SUCCESS;
}
PHPAPI php_stream *php_stream_encloses(php_stream *enclosing, php_stream *enclosed)
{
php_stream *orig = enclosed->enclosing_stream;
php_stream_auto_cleanup(enclosed);
enclosed->enclosing_stream = enclosing;
return orig;
}
PHPAPI int php_stream_from_persistent_id(const char *persistent_id, php_stream **stream TSRMLS_DC)
{
zend_rsrc_list_entry *le;
if (zend_hash_find(&EG(persistent_list), (char*)persistent_id, strlen(persistent_id)+1, (void*) &le) == SUCCESS) {
if (Z_TYPE_P(le) == le_pstream) {
if (stream) {
HashPosition pos;
zend_rsrc_list_entry *regentry;
zend_uint_t index = -1; /* intentional */
/* see if this persistent resource already has been loaded to the
* regular list; allowing the same resource in several entries in the
* regular list causes trouble (see bug #54623) */
zend_hash_internal_pointer_reset_ex(&EG(regular_list), &pos);
while (zend_hash_get_current_data_ex(&EG(regular_list),
(void **)®entry, &pos) == SUCCESS) {
if (regentry->ptr == le->ptr) {
zend_hash_get_current_key_ex(&EG(regular_list), NULL, NULL,
&index, 0, &pos);
break;
}
zend_hash_move_forward_ex(&EG(regular_list), &pos);
}
*stream = (php_stream*)le->ptr;
if (index == -1) { /* not found in regular list */
le->refcount++;
(*stream)->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, *stream, le_pstream);
} else {
regentry->refcount++;
(*stream)->rsrc_id = index;
}
}
return PHP_STREAM_PERSISTENT_SUCCESS;
}
return PHP_STREAM_PERSISTENT_FAILURE;
}
return PHP_STREAM_PERSISTENT_NOT_EXIST;
}
/* }}} */
static zend_llist *php_get_wrapper_errors_list(php_stream_wrapper *wrapper TSRMLS_DC)
{
zend_llist *list = NULL;
if (!FG(wrapper_errors)) {
return NULL;
} else {
zend_hash_find(FG(wrapper_errors), (const char*)&wrapper,
sizeof wrapper, (void**)&list);
return list;
}
}
/* {{{ wrapper error reporting */
void php_stream_display_wrapper_errors(php_stream_wrapper *wrapper, const char *path, const char *caption TSRMLS_DC)
{
char *tmp = estrdup(path);
char *msg;
int free_msg = 0;
if (wrapper) {
zend_llist *err_list = php_get_wrapper_errors_list(wrapper TSRMLS_CC);
if (err_list) {
size_t l = 0;
int brlen;
int i;
int count = zend_llist_count(err_list);
const char *br;
const char **err_buf_p;
zend_llist_position pos;
if (PG(html_errors)) {
brlen = 7;
br = "<br />\n";
} else {
brlen = 1;
br = "\n";
}
for (err_buf_p = zend_llist_get_first_ex(err_list, &pos), i = 0;
err_buf_p;
err_buf_p = zend_llist_get_next_ex(err_list, &pos), i++) {
l += strlen(*err_buf_p);
if (i < count - 1) {
l += brlen;
}
}
msg = emalloc(l + 1);
msg[0] = '\0';
for (err_buf_p = zend_llist_get_first_ex(err_list, &pos), i = 0;
err_buf_p;
err_buf_p = zend_llist_get_next_ex(err_list, &pos), i++) {
strcat(msg, *err_buf_p);
if (i < count - 1) {
strcat(msg, br);
}
}
free_msg = 1;
} else {
if (wrapper == &php_plain_files_wrapper) {
msg = strerror(errno); /* TODO: not ts on linux */
} else {
msg = "operation failed";
}
}
} else {
msg = "no suitable wrapper could be found";
}
php_strip_url_passwd(tmp);
php_error_docref1(NULL TSRMLS_CC, tmp, E_WARNING, "%s: %s", caption, msg);
efree(tmp);
if (free_msg) {
efree(msg);
}
}
void php_stream_tidy_wrapper_error_log(php_stream_wrapper *wrapper TSRMLS_DC)
{
if (wrapper && FG(wrapper_errors)) {
zend_hash_del(FG(wrapper_errors), (const char*)&wrapper, sizeof wrapper);
}
}
static void wrapper_error_dtor(void *error)
{
efree(*(char**)error);
}
PHPAPI void php_stream_wrapper_log_error(php_stream_wrapper *wrapper, int options TSRMLS_DC, const char *fmt, ...)
{
va_list args;
char *buffer = NULL;
va_start(args, fmt);
vspprintf(&buffer, 0, fmt, args);
va_end(args);
if (options & REPORT_ERRORS || wrapper == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", buffer);
efree(buffer);
} else {
zend_llist *list = NULL;
if (!FG(wrapper_errors)) {
ALLOC_HASHTABLE(FG(wrapper_errors));
zend_hash_init(FG(wrapper_errors), 8, NULL,
(dtor_func_t)zend_llist_destroy, 0);
} else {
zend_hash_find(FG(wrapper_errors), (const char*)&wrapper,
sizeof wrapper, (void**)&list);
}
if (!list) {
zend_llist new_list;
zend_llist_init(&new_list, sizeof buffer, wrapper_error_dtor, 0);
zend_hash_update(FG(wrapper_errors), (const char*)&wrapper,
sizeof wrapper, &new_list, sizeof new_list, (void**)&list);
}
/* append to linked list */
zend_llist_add_element(list, &buffer);
}
}
/* }}} */
/* allocate a new stream for a particular ops */
PHPAPI php_stream *_php_stream_alloc(php_stream_ops *ops, void *abstract, const char *persistent_id, const char *mode STREAMS_DC TSRMLS_DC) /* {{{ */
{
php_stream *ret;
ret = (php_stream*) pemalloc_rel_orig(sizeof(php_stream), persistent_id ? 1 : 0);
memset(ret, 0, sizeof(php_stream));
ret->readfilters.stream = ret;
ret->writefilters.stream = ret;
#if STREAM_DEBUG
fprintf(stderr, "stream_alloc: %s:%p persistent=%s\n", ops->label, ret, persistent_id);
#endif
ret->ops = ops;
ret->abstract = abstract;
ret->is_persistent = persistent_id ? 1 : 0;
ret->chunk_size = FG(def_chunk_size);
#if ZEND_DEBUG
ret->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename;
ret->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno;
#endif
if (FG(auto_detect_line_endings)) {
ret->flags |= PHP_STREAM_FLAG_DETECT_EOL;
}
if (persistent_id) {
zend_rsrc_list_entry le;
Z_TYPE(le) = le_pstream;
le.ptr = ret;
le.refcount = 0;
if (FAILURE == zend_hash_update(&EG(persistent_list), (char *)persistent_id,
strlen(persistent_id) + 1,
(void *)&le, sizeof(le), NULL)) {
pefree(ret, 1);
return NULL;
}
}
ret->rsrc_id = ZEND_REGISTER_RESOURCE(NULL, ret, persistent_id ? le_pstream : le_stream);
strlcpy(ret->mode, mode, sizeof(ret->mode));
ret->wrapper = NULL;
ret->wrapperthis = NULL;
ret->wrapperdata = NULL;
ret->stdiocast = NULL;
ret->orig_path = NULL;
ret->context = NULL;
ret->readbuf = NULL;
ret->enclosing_stream = NULL;
return ret;
}
/* }}} */
PHPAPI int _php_stream_free_enclosed(php_stream *stream_enclosed, int close_options TSRMLS_DC) /* {{{ */
{
return _php_stream_free(stream_enclosed,
close_options | PHP_STREAM_FREE_IGNORE_ENCLOSING TSRMLS_CC);
}
/* }}} */
#if STREAM_DEBUG
static const char *_php_stream_pretty_free_options(int close_options, char *out)
{
if (close_options & PHP_STREAM_FREE_CALL_DTOR)
strcat(out, "CALL_DTOR, ");
if (close_options & PHP_STREAM_FREE_RELEASE_STREAM)
strcat(out, "RELEASE_STREAM, ");
if (close_options & PHP_STREAM_FREE_PRESERVE_HANDLE)
strcat(out, "PREVERSE_HANDLE, ");
if (close_options & PHP_STREAM_FREE_RSRC_DTOR)
strcat(out, "RSRC_DTOR, ");
if (close_options & PHP_STREAM_FREE_PERSISTENT)
strcat(out, "PERSISTENT, ");
if (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING)
strcat(out, "IGNORE_ENCLOSING, ");
if (out[0] != '\0')
out[strlen(out) - 2] = '\0';
return out;
}
#endif
static int _php_stream_free_persistent(zend_rsrc_list_entry *le, void *pStream TSRMLS_DC)
{
return le->ptr == pStream;
}
PHPAPI int _php_stream_free(php_stream *stream, int close_options TSRMLS_DC) /* {{{ */
{
int ret = 1;
int preserve_handle = close_options & PHP_STREAM_FREE_PRESERVE_HANDLE ? 1 : 0;
int release_cast = 1;
php_stream_context *context = NULL;
/* on an resource list destruction, the context, another resource, may have
* already been freed (if it was created after the stream resource), so
* don't reference it */
if (EG(active)) {
context = stream->context;
}
if (stream->flags & PHP_STREAM_FLAG_NO_CLOSE) {
preserve_handle = 1;
}
#if STREAM_DEBUG
{
char out[200] = "";
fprintf(stderr, "stream_free: %s:%p[%s] in_free=%d opts=%s\n",
stream->ops->label, stream, stream->orig_path, stream->in_free, _php_stream_pretty_free_options(close_options, out));
}
#endif
if (stream->in_free) {
/* hopefully called recursively from the enclosing stream; the pointer was NULLed below */
if ((stream->in_free == 1) && (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) && (stream->enclosing_stream == NULL)) {
close_options |= PHP_STREAM_FREE_RSRC_DTOR; /* restore flag */
} else {
return 1; /* recursion protection */
}
}
stream->in_free++;
/* force correct order on enclosing/enclosed stream destruction (only from resource
* destructor as in when reverse destroying the resource list) */
if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) &&
!(close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) &&
(close_options & (PHP_STREAM_FREE_CALL_DTOR | PHP_STREAM_FREE_RELEASE_STREAM)) && /* always? */
(stream->enclosing_stream != NULL)) {
php_stream *enclosing_stream = stream->enclosing_stream;
stream->enclosing_stream = NULL;
/* we force PHP_STREAM_CALL_DTOR because that's from where the
* enclosing stream can free this stream. We remove rsrc_dtor because
* we want the enclosing stream to be deleted from the resource list */
return _php_stream_free(enclosing_stream,
(close_options | PHP_STREAM_FREE_CALL_DTOR) & ~PHP_STREAM_FREE_RSRC_DTOR TSRMLS_CC);
}
/* if we are releasing the stream only (and preserving the underlying handle),
* we need to do things a little differently.
* We are only ever called like this when the stream is cast to a FILE*
* for include (or other similar) purposes.
* */
if (preserve_handle) {
if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) {
/* If the stream was fopencookied, we must NOT touch anything
* here, as the cookied stream relies on it all.
* Instead, mark the stream as OK to auto-clean */
php_stream_auto_cleanup(stream);
stream->in_free--;
return 0;
}
/* otherwise, make sure that we don't close the FILE* from a cast */
release_cast = 0;
}
#if STREAM_DEBUG
fprintf(stderr, "stream_free: %s:%p[%s] preserve_handle=%d release_cast=%d remove_rsrc=%d\n",
stream->ops->label, stream, stream->orig_path, preserve_handle, release_cast,
(close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0);
#endif
/* make sure everything is saved */
_php_stream_flush(stream, 1 TSRMLS_CC);
/* If not called from the resource dtor, remove the stream from the resource list. */
if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0) {
/* zend_list_delete actually only decreases the refcount; if we're
* releasing the stream, we want to actually delete the resource from
* the resource list, otherwise the resource will point to invalid memory.
* In any case, let's always completely delete it from the resource list,
* not only when PHP_STREAM_FREE_RELEASE_STREAM is set */
while (zend_list_delete(stream->rsrc_id) == SUCCESS) {}
}
if (close_options & PHP_STREAM_FREE_CALL_DTOR) {
if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) {
/* calling fclose on an fopencookied stream will ultimately
call this very same function. If we were called via fclose,
the cookie_closer unsets the fclose_stdiocast flags, so
we can be sure that we only reach here when PHP code calls
php_stream_free.
Lets let the cookie code clean it all up.
*/
stream->in_free = 0;
return fclose(stream->stdiocast);
}
ret = stream->ops->close(stream, preserve_handle ? 0 : 1 TSRMLS_CC);
stream->abstract = NULL;
/* tidy up any FILE* that might have been fdopened */
if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FDOPEN && stream->stdiocast) {
fclose(stream->stdiocast);
stream->stdiocast = NULL;
stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE;
}
}
if (close_options & PHP_STREAM_FREE_RELEASE_STREAM) {
while (stream->readfilters.head) {
php_stream_filter_remove(stream->readfilters.head, 1 TSRMLS_CC);
}
while (stream->writefilters.head) {
php_stream_filter_remove(stream->writefilters.head, 1 TSRMLS_CC);
}
if (stream->wrapper && stream->wrapper->wops && stream->wrapper->wops->stream_closer) {
stream->wrapper->wops->stream_closer(stream->wrapper, stream TSRMLS_CC);
stream->wrapper = NULL;
}
if (stream->wrapperdata) {
zval_ptr_dtor(&stream->wrapperdata);
stream->wrapperdata = NULL;
}
if (stream->readbuf) {
pefree(stream->readbuf, stream->is_persistent);
stream->readbuf = NULL;
}
if (stream->is_persistent && (close_options & PHP_STREAM_FREE_PERSISTENT)) {
/* we don't work with *stream but need its value for comparison */
zend_hash_apply_with_argument(&EG(persistent_list), (apply_func_arg_t) _php_stream_free_persistent, stream TSRMLS_CC);
}
#if ZEND_DEBUG
if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) && (stream->__exposed == 0) && (EG(error_reporting) & E_WARNING)) {
/* it leaked: Lets deliberately NOT pefree it so that the memory manager shows it
* as leaked; it will log a warning, but lets help it out and display what kind
* of stream it was. */
char *leakinfo;
spprintf(&leakinfo, 0, __FILE__ "(%d) : Stream of type '%s' %p (path:%s) was not closed\n", __LINE__, stream->ops->label, stream, stream->orig_path);
if (stream->orig_path) {
pefree(stream->orig_path, stream->is_persistent);
stream->orig_path = NULL;
}
# if defined(PHP_WIN32)
OutputDebugString(leakinfo);
# else
fprintf(stderr, "%s", leakinfo);
# endif
efree(leakinfo);
} else {
if (stream->orig_path) {
pefree(stream->orig_path, stream->is_persistent);
stream->orig_path = NULL;
}
pefree(stream, stream->is_persistent);
}
#else
if (stream->orig_path) {
pefree(stream->orig_path, stream->is_persistent);
stream->orig_path = NULL;
}
pefree(stream, stream->is_persistent);
#endif
}
if (context) {
zend_list_delete(context->rsrc_id);
}
return ret;
}
/* }}} */
/* {{{ generic stream operations */
static void php_stream_fill_read_buffer(php_stream *stream, size_t size TSRMLS_DC)
{
/* allocate/fill the buffer */
if (stream->readfilters.head) {
char *chunk_buf;
int err_flag = 0;
php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL };
php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap;
/* Invalidate the existing cache, otherwise reads can fail, see note in
main/streams/filter.c::_php_stream_filter_append */
stream->writepos = stream->readpos = 0;
/* allocate a buffer for reading chunks */
chunk_buf = emalloc(stream->chunk_size);
while (!stream->eof && !err_flag && (stream->writepos - stream->readpos < (zend_off_t)size)) {
size_t justread = 0;
int flags;
php_stream_bucket *bucket;
php_stream_filter_status_t status = PSFS_ERR_FATAL;
php_stream_filter *filter;
/* read a chunk into a bucket */
justread = stream->ops->read(stream, chunk_buf, stream->chunk_size TSRMLS_CC);
if (justread && justread != (size_t)-1) {
bucket = php_stream_bucket_new(stream, chunk_buf, justread, 0, 0 TSRMLS_CC);
/* after this call, bucket is owned by the brigade */
php_stream_bucket_append(brig_inp, bucket TSRMLS_CC);
flags = PSFS_FLAG_NORMAL;
} else {
flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC;
}
/* wind the handle... */
for (filter = stream->readfilters.head; filter; filter = filter->next) {
status = filter->fops->filter(stream, filter, brig_inp, brig_outp, NULL, flags TSRMLS_CC);
if (status != PSFS_PASS_ON) {
break;
}
/* brig_out becomes brig_in.
* brig_in will always be empty here, as the filter MUST attach any un-consumed buckets
* to its own brigade */
brig_swap = brig_inp;
brig_inp = brig_outp;
brig_outp = brig_swap;
memset(brig_outp, 0, sizeof(*brig_outp));
}
switch (status) {
case PSFS_PASS_ON:
/* we get here when the last filter in the chain has data to pass on.
* in this situation, we are passing the brig_in brigade into the
* stream read buffer */
while (brig_inp->head) {
bucket = brig_inp->head;
/* grow buffer to hold this bucket
* TODO: this can fail for persistent streams */
if (stream->readbuflen - stream->writepos < bucket->buflen) {
stream->readbuflen += bucket->buflen;
stream->readbuf = perealloc(stream->readbuf, stream->readbuflen,
stream->is_persistent);
}
memcpy(stream->readbuf + stream->writepos, bucket->buf, bucket->buflen);
stream->writepos += bucket->buflen;
php_stream_bucket_unlink(bucket TSRMLS_CC);
php_stream_bucket_delref(bucket TSRMLS_CC);
}
break;
case PSFS_FEED_ME:
/* when a filter needs feeding, there is no brig_out to deal with.
* we simply continue the loop; if the caller needs more data,
* we will read again, otherwise out job is done here */
if (justread == 0) {
/* there is no data */
err_flag = 1;
break;
}
continue;
case PSFS_ERR_FATAL:
/* some fatal error. Theoretically, the stream is borked, so all
* further reads should fail. */
err_flag = 1;
break;
}
if (justread == 0 || justread == (size_t)-1) {
break;
}
}
efree(chunk_buf);
} else {
/* is there enough data in the buffer ? */
if (stream->writepos - stream->readpos < (zend_off_t)size) {
size_t justread = 0;
/* reduce buffer memory consumption if possible, to avoid a realloc */
if (stream->readbuf && stream->readbuflen - stream->writepos < stream->chunk_size) {
memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->readbuflen - stream->readpos);
stream->writepos -= stream->readpos;
stream->readpos = 0;
}
/* grow the buffer if required
* TODO: this can fail for persistent streams */
if (stream->readbuflen - stream->writepos < stream->chunk_size) {
stream->readbuflen += stream->chunk_size;
stream->readbuf = perealloc(stream->readbuf, stream->readbuflen,
stream->is_persistent);
}
justread = stream->ops->read(stream, stream->readbuf + stream->writepos,
stream->readbuflen - stream->writepos
TSRMLS_CC);
if (justread != (size_t)-1) {
stream->writepos += justread;
}
}
}
}
PHPAPI size_t _php_stream_read(php_stream *stream, char *buf, size_t size TSRMLS_DC)
{
size_t toread = 0, didread = 0;
while (size > 0) {
/* take from the read buffer first.
* It is possible that a buffered stream was switched to non-buffered, so we
* drain the remainder of the buffer before using the "raw" read mode for
* the excess */
if (stream->writepos > stream->readpos) {
toread = stream->writepos - stream->readpos;
if (toread > size) {
toread = size;
}
memcpy(buf, stream->readbuf + stream->readpos, toread);
stream->readpos += toread;
size -= toread;
buf += toread;
didread += toread;
}
/* ignore eof here; the underlying state might have changed */
if (size == 0) {
break;
}
if (!stream->readfilters.head && (stream->flags & PHP_STREAM_FLAG_NO_BUFFER || stream->chunk_size == 1)) {
toread = stream->ops->read(stream, buf, size TSRMLS_CC);
if (toread == (size_t) -1) {
/* e.g. underlying read(2) returned -1 */
break;
}
} else {
php_stream_fill_read_buffer(stream, size TSRMLS_CC);
toread = stream->writepos - stream->readpos;
if (toread > size) {
toread = size;
}
if (toread > 0) {
memcpy(buf, stream->readbuf + stream->readpos, toread);
stream->readpos += toread;
}
}
if (toread > 0) {
didread += toread;
buf += toread;
size -= toread;
} else {
/* EOF, or temporary end of data (for non-blocking mode). */
break;
}
/* just break anyway, to avoid greedy read */
if (stream->wrapper != &php_plain_files_wrapper) {
break;
}
}
if (didread > 0) {
stream->position += didread;
}
return didread;
}
PHPAPI int _php_stream_eof(php_stream *stream TSRMLS_DC)
{
/* if there is data in the buffer, it's not EOF */
if (stream->writepos - stream->readpos > 0) {
return 0;
}
/* use the configured timeout when checking eof */
if (!stream->eof && PHP_STREAM_OPTION_RETURN_ERR ==
php_stream_set_option(stream, PHP_STREAM_OPTION_CHECK_LIVENESS,
0, NULL)) {
stream->eof = 1;
}
return stream->eof;
}
PHPAPI int _php_stream_putc(php_stream *stream, int c TSRMLS_DC)
{
unsigned char buf = c;
if (php_stream_write(stream, &buf, 1) > 0) {
return 1;
}
return EOF;
}
PHPAPI int _php_stream_getc(php_stream *stream TSRMLS_DC)
{
char buf;
if (php_stream_read(stream, &buf, 1) > 0) {
return buf & 0xff;
}
return EOF;
}
PHPAPI int _php_stream_puts(php_stream *stream, const char *buf TSRMLS_DC)
{
php_size_t len;
char newline[2] = "\n"; /* is this OK for Win? */
len = strlen(buf);
if (len > 0 && php_stream_write(stream, buf, len) && php_stream_write(stream, newline, 1)) {
return 1;
}
return 0;
}
PHPAPI int _php_stream_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC)
{
memset(ssb, 0, sizeof(*ssb));
/* if the stream was wrapped, allow the wrapper to stat it */
if (stream->wrapper && stream->wrapper->wops->stream_stat != NULL) {
return stream->wrapper->wops->stream_stat(stream->wrapper, stream, ssb TSRMLS_CC);
}
/* if the stream doesn't directly support stat-ing, return with failure.
* We could try and emulate this by casting to a FD and fstat-ing it,
* but since the fd might not represent the actual underlying content
* this would give bogus results. */
if (stream->ops->stat == NULL) {
return -1;
}
return (stream->ops->stat)(stream, ssb TSRMLS_CC);
}
PHPAPI const char *php_stream_locate_eol(php_stream *stream, const char *buf, size_t buf_len TSRMLS_DC)
{
size_t avail;
const char *cr, *lf, *eol = NULL;
const char *readptr;
if (!buf) {
readptr = stream->readbuf + stream->readpos;
avail = stream->writepos - stream->readpos;
} else {
readptr = buf;
avail = buf_len;
}
/* Look for EOL */
if (stream->flags & PHP_STREAM_FLAG_DETECT_EOL) {
cr = memchr(readptr, '\r', avail);
lf = memchr(readptr, '\n', avail);
if (cr && lf != cr + 1 && !(lf && lf < cr)) {
/* mac */
stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL;
stream->flags |= PHP_STREAM_FLAG_EOL_MAC;
eol = cr;
} else if ((cr && lf && cr == lf - 1) || (lf)) {
/* dos or unix endings */
stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL;
eol = lf;
}
} else if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) {
eol = memchr(readptr, '\r', avail);
} else {
/* unix (and dos) line endings */
eol = memchr(readptr, '\n', avail);
}
return eol;
}
/* If buf == NULL, the buffer will be allocated automatically and will be of an
* appropriate length to hold the line, regardless of the line length, memory
* permitting */
PHPAPI char *_php_stream_get_line(php_stream *stream, char *buf, size_t maxlen,
size_t *returned_len TSRMLS_DC)
{
size_t avail = 0;
size_t current_buf_size = 0;
size_t total_copied = 0;
int grow_mode = 0;
char *bufstart = buf;
if (buf == NULL) {
grow_mode = 1;
} else if (maxlen == 0) {
return NULL;
}
/*
* If the underlying stream operations block when no new data is readable,
* we need to take extra precautions.
*
* If there is buffered data available, we check for a EOL. If it exists,
* we pass the data immediately back to the caller. This saves a call
* to the read implementation and will not block where blocking
* is not necessary at all.
*
* If the stream buffer contains more data than the caller requested,
* we can also avoid that costly step and simply return that data.
*/
for (;;) {
avail = stream->writepos - stream->readpos;
if (avail > 0) {
size_t cpysz = 0;
char *readptr;
const char *eol;
int done = 0;
readptr = stream->readbuf + stream->readpos;
eol = php_stream_locate_eol(stream, NULL, 0 TSRMLS_CC);
if (eol) {
cpysz = eol - readptr + 1;
done = 1;
} else {
cpysz = avail;
}
if (grow_mode) {
/* allow room for a NUL. If this realloc is really a realloc
* (ie: second time around), we get an extra byte. In most
* cases, with the default chunk size of 8K, we will only
* incur that overhead once. When people have lines longer
* than 8K, we waste 1 byte per additional 8K or so.
* That seems acceptable to me, to avoid making this code
* hard to follow */
bufstart = erealloc(bufstart, current_buf_size + cpysz + 1);
current_buf_size += cpysz + 1;
buf = bufstart + total_copied;
} else {
if (cpysz >= maxlen - 1) {
cpysz = maxlen - 1;
done = 1;
}
}
memcpy(buf, readptr, cpysz);
stream->position += cpysz;
stream->readpos += cpysz;
buf += cpysz;
maxlen -= cpysz;
total_copied += cpysz;
if (done) {
break;
}
} else if (stream->eof) {
break;
} else {
/* XXX: Should be fine to always read chunk_size */
size_t toread;
if (grow_mode) {
toread = stream->chunk_size;
} else {
toread = maxlen - 1;
if (toread > stream->chunk_size) {
toread = stream->chunk_size;
}
}
php_stream_fill_read_buffer(stream, toread TSRMLS_CC);
if (stream->writepos - stream->readpos == 0) {
break;
}
}
}
if (total_copied == 0) {
if (grow_mode) {
assert(bufstart == NULL);
}
return NULL;
}
buf[0] = '\0';
if (returned_len) {
*returned_len = total_copied;
}
return bufstart;
}
#define STREAM_BUFFERED_AMOUNT(stream) \
((size_t)(((stream)->writepos) - (stream)->readpos))