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