PageRenderTime 58ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/main/streams/streams.c

http://github.com/php/php-src
C | 2368 lines | 1742 code | 367 blank | 259 comment | 545 complexity | 70bdcabeb6650adf5f2632d35fef3af1 MD5 | raw file
Possible License(s): BSD-2-Clause, BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. +----------------------------------------------------------------------+
  3. | Copyright (c) The PHP Group |
  4. +----------------------------------------------------------------------+
  5. | This source file is subject to version 3.01 of the PHP license, |
  6. | that is bundled with this package in the file LICENSE, and is |
  7. | available through the world-wide-web at the following url: |
  8. | http://www.php.net/license/3_01.txt |
  9. | If you did not receive a copy of the PHP license and are unable to |
  10. | obtain it through the world-wide-web, please send a note to |
  11. | license@php.net so we can mail you a copy immediately. |
  12. +----------------------------------------------------------------------+
  13. | Authors: Wez Furlong <wez@thebrainroom.com> |
  14. | Borrowed code from: |
  15. | Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
  16. | Jim Winstead <jimw@php.net> |
  17. +----------------------------------------------------------------------+
  18. */
  19. #define _GNU_SOURCE
  20. #include "php.h"
  21. #include "php_globals.h"
  22. #include "php_memory_streams.h"
  23. #include "php_network.h"
  24. #include "php_open_temporary_file.h"
  25. #include "ext/standard/file.h"
  26. #include "ext/standard/basic_functions.h" /* for BG(CurrentStatFile) */
  27. #include "ext/standard/php_string.h" /* for php_memnstr, used by php_stream_get_record() */
  28. #include <stddef.h>
  29. #include <fcntl.h>
  30. #include "php_streams_int.h"
  31. /* {{{ resource and registration code */
  32. /* Global wrapper hash, copied to FG(stream_wrappers) on registration of volatile wrapper */
  33. static HashTable url_stream_wrappers_hash;
  34. static int le_stream = FAILURE; /* true global */
  35. static int le_pstream = FAILURE; /* true global */
  36. static int le_stream_filter = FAILURE; /* true global */
  37. PHPAPI int php_file_le_stream(void)
  38. {
  39. return le_stream;
  40. }
  41. PHPAPI int php_file_le_pstream(void)
  42. {
  43. return le_pstream;
  44. }
  45. PHPAPI int php_file_le_stream_filter(void)
  46. {
  47. return le_stream_filter;
  48. }
  49. PHPAPI HashTable *_php_stream_get_url_stream_wrappers_hash(void)
  50. {
  51. return (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash);
  52. }
  53. PHPAPI HashTable *php_stream_get_url_stream_wrappers_hash_global(void)
  54. {
  55. return &url_stream_wrappers_hash;
  56. }
  57. static int forget_persistent_resource_id_numbers(zval *el)
  58. {
  59. php_stream *stream;
  60. zend_resource *rsrc = Z_RES_P(el);
  61. if (rsrc->type != le_pstream) {
  62. return 0;
  63. }
  64. stream = (php_stream*)rsrc->ptr;
  65. #if STREAM_DEBUG
  66. fprintf(stderr, "forget_persistent: %s:%p\n", stream->ops->label, stream);
  67. #endif
  68. stream->res = NULL;
  69. if (stream->ctx) {
  70. zend_list_delete(stream->ctx);
  71. stream->ctx = NULL;
  72. }
  73. return 0;
  74. }
  75. PHP_RSHUTDOWN_FUNCTION(streams)
  76. {
  77. zval *el;
  78. ZEND_HASH_FOREACH_VAL(&EG(persistent_list), el) {
  79. forget_persistent_resource_id_numbers(el);
  80. } ZEND_HASH_FOREACH_END();
  81. return SUCCESS;
  82. }
  83. PHPAPI php_stream *php_stream_encloses(php_stream *enclosing, php_stream *enclosed)
  84. {
  85. php_stream *orig = enclosed->enclosing_stream;
  86. php_stream_auto_cleanup(enclosed);
  87. enclosed->enclosing_stream = enclosing;
  88. return orig;
  89. }
  90. PHPAPI int php_stream_from_persistent_id(const char *persistent_id, php_stream **stream)
  91. {
  92. zend_resource *le;
  93. if ((le = zend_hash_str_find_ptr(&EG(persistent_list), persistent_id, strlen(persistent_id))) != NULL) {
  94. if (le->type == le_pstream) {
  95. if (stream) {
  96. zend_resource *regentry = NULL;
  97. /* see if this persistent resource already has been loaded to the
  98. * regular list; allowing the same resource in several entries in the
  99. * regular list causes trouble (see bug #54623) */
  100. *stream = (php_stream*)le->ptr;
  101. ZEND_HASH_FOREACH_PTR(&EG(regular_list), regentry) {
  102. if (regentry->ptr == le->ptr) {
  103. GC_ADDREF(regentry);
  104. (*stream)->res = regentry;
  105. return PHP_STREAM_PERSISTENT_SUCCESS;
  106. }
  107. } ZEND_HASH_FOREACH_END();
  108. GC_ADDREF(le);
  109. (*stream)->res = zend_register_resource(*stream, le_pstream);
  110. }
  111. return PHP_STREAM_PERSISTENT_SUCCESS;
  112. }
  113. return PHP_STREAM_PERSISTENT_FAILURE;
  114. }
  115. return PHP_STREAM_PERSISTENT_NOT_EXIST;
  116. }
  117. /* }}} */
  118. static zend_llist *php_get_wrapper_errors_list(php_stream_wrapper *wrapper)
  119. {
  120. if (!FG(wrapper_errors)) {
  121. return NULL;
  122. } else {
  123. return (zend_llist*) zend_hash_str_find_ptr(FG(wrapper_errors), (const char*)&wrapper, sizeof(wrapper));
  124. }
  125. }
  126. /* {{{ wrapper error reporting */
  127. void php_stream_display_wrapper_errors(php_stream_wrapper *wrapper, const char *path, const char *caption)
  128. {
  129. char *tmp;
  130. char *msg;
  131. int free_msg = 0;
  132. if (EG(exception)) {
  133. /* Don't emit additional warnings if an exception has already been thrown. */
  134. return;
  135. }
  136. tmp = estrdup(path);
  137. if (wrapper) {
  138. zend_llist *err_list = php_get_wrapper_errors_list(wrapper);
  139. if (err_list) {
  140. size_t l = 0;
  141. int brlen;
  142. int i;
  143. int count = (int)zend_llist_count(err_list);
  144. const char *br;
  145. const char **err_buf_p;
  146. zend_llist_position pos;
  147. if (PG(html_errors)) {
  148. brlen = 7;
  149. br = "<br />\n";
  150. } else {
  151. brlen = 1;
  152. br = "\n";
  153. }
  154. for (err_buf_p = zend_llist_get_first_ex(err_list, &pos), i = 0;
  155. err_buf_p;
  156. err_buf_p = zend_llist_get_next_ex(err_list, &pos), i++) {
  157. l += strlen(*err_buf_p);
  158. if (i < count - 1) {
  159. l += brlen;
  160. }
  161. }
  162. msg = emalloc(l + 1);
  163. msg[0] = '\0';
  164. for (err_buf_p = zend_llist_get_first_ex(err_list, &pos), i = 0;
  165. err_buf_p;
  166. err_buf_p = zend_llist_get_next_ex(err_list, &pos), i++) {
  167. strcat(msg, *err_buf_p);
  168. if (i < count - 1) {
  169. strcat(msg, br);
  170. }
  171. }
  172. free_msg = 1;
  173. } else {
  174. if (wrapper == &php_plain_files_wrapper) {
  175. msg = strerror(errno); /* TODO: not ts on linux */
  176. } else {
  177. msg = "operation failed";
  178. }
  179. }
  180. } else {
  181. msg = "no suitable wrapper could be found";
  182. }
  183. php_strip_url_passwd(tmp);
  184. php_error_docref1(NULL, tmp, E_WARNING, "%s: %s", caption, msg);
  185. efree(tmp);
  186. if (free_msg) {
  187. efree(msg);
  188. }
  189. }
  190. void php_stream_tidy_wrapper_error_log(php_stream_wrapper *wrapper)
  191. {
  192. if (wrapper && FG(wrapper_errors)) {
  193. zend_hash_str_del(FG(wrapper_errors), (const char*)&wrapper, sizeof(wrapper));
  194. }
  195. }
  196. static void wrapper_error_dtor(void *error)
  197. {
  198. efree(*(char**)error);
  199. }
  200. static void wrapper_list_dtor(zval *item) {
  201. zend_llist *list = (zend_llist*)Z_PTR_P(item);
  202. zend_llist_destroy(list);
  203. efree(list);
  204. }
  205. PHPAPI void php_stream_wrapper_log_error(const php_stream_wrapper *wrapper, int options, const char *fmt, ...)
  206. {
  207. va_list args;
  208. char *buffer = NULL;
  209. va_start(args, fmt);
  210. vspprintf(&buffer, 0, fmt, args);
  211. va_end(args);
  212. if (options & REPORT_ERRORS || wrapper == NULL) {
  213. php_error_docref(NULL, E_WARNING, "%s", buffer);
  214. efree(buffer);
  215. } else {
  216. zend_llist *list = NULL;
  217. if (!FG(wrapper_errors)) {
  218. ALLOC_HASHTABLE(FG(wrapper_errors));
  219. zend_hash_init(FG(wrapper_errors), 8, NULL, wrapper_list_dtor, 0);
  220. } else {
  221. list = zend_hash_str_find_ptr(FG(wrapper_errors), (const char*)&wrapper, sizeof(wrapper));
  222. }
  223. if (!list) {
  224. zend_llist new_list;
  225. zend_llist_init(&new_list, sizeof(buffer), wrapper_error_dtor, 0);
  226. list = zend_hash_str_update_mem(FG(wrapper_errors), (const char*)&wrapper,
  227. sizeof(wrapper), &new_list, sizeof(new_list));
  228. }
  229. /* append to linked list */
  230. zend_llist_add_element(list, &buffer);
  231. }
  232. }
  233. /* }}} */
  234. /* allocate a new stream for a particular ops */
  235. PHPAPI php_stream *_php_stream_alloc(const php_stream_ops *ops, void *abstract, const char *persistent_id, const char *mode STREAMS_DC) /* {{{ */
  236. {
  237. php_stream *ret;
  238. ret = (php_stream*) pemalloc_rel_orig(sizeof(php_stream), persistent_id ? 1 : 0);
  239. memset(ret, 0, sizeof(php_stream));
  240. ret->readfilters.stream = ret;
  241. ret->writefilters.stream = ret;
  242. #if STREAM_DEBUG
  243. fprintf(stderr, "stream_alloc: %s:%p persistent=%s\n", ops->label, ret, persistent_id);
  244. #endif
  245. ret->ops = ops;
  246. ret->abstract = abstract;
  247. ret->is_persistent = persistent_id ? 1 : 0;
  248. ret->chunk_size = FG(def_chunk_size);
  249. #if ZEND_DEBUG
  250. ret->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename;
  251. ret->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno;
  252. #endif
  253. if (FG(auto_detect_line_endings)) {
  254. ret->flags |= PHP_STREAM_FLAG_DETECT_EOL;
  255. }
  256. if (persistent_id) {
  257. if (NULL == zend_register_persistent_resource(persistent_id, strlen(persistent_id), ret, le_pstream)) {
  258. pefree(ret, 1);
  259. return NULL;
  260. }
  261. }
  262. ret->res = zend_register_resource(ret, persistent_id ? le_pstream : le_stream);
  263. strlcpy(ret->mode, mode, sizeof(ret->mode));
  264. ret->wrapper = NULL;
  265. ret->wrapperthis = NULL;
  266. ZVAL_UNDEF(&ret->wrapperdata);
  267. ret->stdiocast = NULL;
  268. ret->orig_path = NULL;
  269. ret->ctx = NULL;
  270. ret->readbuf = NULL;
  271. ret->enclosing_stream = NULL;
  272. return ret;
  273. }
  274. /* }}} */
  275. PHPAPI int _php_stream_free_enclosed(php_stream *stream_enclosed, int close_options) /* {{{ */
  276. {
  277. return php_stream_free(stream_enclosed,
  278. close_options | PHP_STREAM_FREE_IGNORE_ENCLOSING);
  279. }
  280. /* }}} */
  281. #if STREAM_DEBUG
  282. static const char *_php_stream_pretty_free_options(int close_options, char *out)
  283. {
  284. if (close_options & PHP_STREAM_FREE_CALL_DTOR)
  285. strcat(out, "CALL_DTOR, ");
  286. if (close_options & PHP_STREAM_FREE_RELEASE_STREAM)
  287. strcat(out, "RELEASE_STREAM, ");
  288. if (close_options & PHP_STREAM_FREE_PRESERVE_HANDLE)
  289. strcat(out, "PREVERSE_HANDLE, ");
  290. if (close_options & PHP_STREAM_FREE_RSRC_DTOR)
  291. strcat(out, "RSRC_DTOR, ");
  292. if (close_options & PHP_STREAM_FREE_PERSISTENT)
  293. strcat(out, "PERSISTENT, ");
  294. if (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING)
  295. strcat(out, "IGNORE_ENCLOSING, ");
  296. if (out[0] != '\0')
  297. out[strlen(out) - 2] = '\0';
  298. return out;
  299. }
  300. #endif
  301. static int _php_stream_free_persistent(zval *zv, void *pStream)
  302. {
  303. zend_resource *le = Z_RES_P(zv);
  304. return le->ptr == pStream;
  305. }
  306. PHPAPI int _php_stream_free(php_stream *stream, int close_options) /* {{{ */
  307. {
  308. int ret = 1;
  309. int preserve_handle = close_options & PHP_STREAM_FREE_PRESERVE_HANDLE ? 1 : 0;
  310. int release_cast = 1;
  311. php_stream_context *context;
  312. /* During shutdown resources may be released before other resources still holding them.
  313. * When only resoruces are referenced this is not a problem, because they are refcounted
  314. * and will only be fully freed once the refcount drops to zero. However, if php_stream*
  315. * is held directly, we don't have this guarantee. To avoid use-after-free we ignore all
  316. * stream free operations in shutdown unless they come from the resource list destruction,
  317. * or by freeing an enclosed stream (in which case resource list destruction will not have
  318. * freed it). */
  319. if ((EG(flags) & EG_FLAGS_IN_RESOURCE_SHUTDOWN) &&
  320. !(close_options & (PHP_STREAM_FREE_RSRC_DTOR|PHP_STREAM_FREE_IGNORE_ENCLOSING))) {
  321. return 1;
  322. }
  323. context = PHP_STREAM_CONTEXT(stream);
  324. if (stream->flags & PHP_STREAM_FLAG_NO_CLOSE) {
  325. preserve_handle = 1;
  326. }
  327. #if STREAM_DEBUG
  328. {
  329. char out[200] = "";
  330. fprintf(stderr, "stream_free: %s:%p[%s] in_free=%d opts=%s\n",
  331. stream->ops->label, stream, stream->orig_path, stream->in_free, _php_stream_pretty_free_options(close_options, out));
  332. }
  333. #endif
  334. if (stream->in_free) {
  335. /* hopefully called recursively from the enclosing stream; the pointer was NULLed below */
  336. if ((stream->in_free == 1) && (close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) && (stream->enclosing_stream == NULL)) {
  337. close_options |= PHP_STREAM_FREE_RSRC_DTOR; /* restore flag */
  338. } else {
  339. return 1; /* recursion protection */
  340. }
  341. }
  342. stream->in_free++;
  343. /* force correct order on enclosing/enclosed stream destruction (only from resource
  344. * destructor as in when reverse destroying the resource list) */
  345. if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) &&
  346. !(close_options & PHP_STREAM_FREE_IGNORE_ENCLOSING) &&
  347. (close_options & (PHP_STREAM_FREE_CALL_DTOR | PHP_STREAM_FREE_RELEASE_STREAM)) && /* always? */
  348. (stream->enclosing_stream != NULL)) {
  349. php_stream *enclosing_stream = stream->enclosing_stream;
  350. stream->enclosing_stream = NULL;
  351. /* we force PHP_STREAM_CALL_DTOR because that's from where the
  352. * enclosing stream can free this stream. */
  353. return php_stream_free(enclosing_stream,
  354. (close_options | PHP_STREAM_FREE_CALL_DTOR | PHP_STREAM_FREE_KEEP_RSRC) & ~PHP_STREAM_FREE_RSRC_DTOR);
  355. }
  356. /* if we are releasing the stream only (and preserving the underlying handle),
  357. * we need to do things a little differently.
  358. * We are only ever called like this when the stream is cast to a FILE*
  359. * for include (or other similar) purposes.
  360. * */
  361. if (preserve_handle) {
  362. if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) {
  363. /* If the stream was fopencookied, we must NOT touch anything
  364. * here, as the cookied stream relies on it all.
  365. * Instead, mark the stream as OK to auto-clean */
  366. php_stream_auto_cleanup(stream);
  367. stream->in_free--;
  368. return 0;
  369. }
  370. /* otherwise, make sure that we don't close the FILE* from a cast */
  371. release_cast = 0;
  372. }
  373. #if STREAM_DEBUG
  374. fprintf(stderr, "stream_free: %s:%p[%s] preserve_handle=%d release_cast=%d remove_rsrc=%d\n",
  375. stream->ops->label, stream, stream->orig_path, preserve_handle, release_cast,
  376. (close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0);
  377. #endif
  378. if (stream->flags & PHP_STREAM_FLAG_WAS_WRITTEN) {
  379. /* make sure everything is saved */
  380. _php_stream_flush(stream, 1);
  381. }
  382. /* If not called from the resource dtor, remove the stream from the resource list. */
  383. if ((close_options & PHP_STREAM_FREE_RSRC_DTOR) == 0 && stream->res) {
  384. /* Close resource, but keep it in resource list */
  385. zend_list_close(stream->res);
  386. if ((close_options & PHP_STREAM_FREE_KEEP_RSRC) == 0) {
  387. /* Completely delete zend_resource, if not referenced */
  388. zend_list_delete(stream->res);
  389. stream->res = NULL;
  390. }
  391. }
  392. if (close_options & PHP_STREAM_FREE_CALL_DTOR) {
  393. if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) {
  394. /* calling fclose on an fopencookied stream will ultimately
  395. call this very same function. If we were called via fclose,
  396. the cookie_closer unsets the fclose_stdiocast flags, so
  397. we can be sure that we only reach here when PHP code calls
  398. php_stream_free.
  399. Lets let the cookie code clean it all up.
  400. */
  401. stream->in_free = 0;
  402. return fclose(stream->stdiocast);
  403. }
  404. ret = stream->ops->close(stream, preserve_handle ? 0 : 1);
  405. stream->abstract = NULL;
  406. /* tidy up any FILE* that might have been fdopened */
  407. if (release_cast && stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FDOPEN && stream->stdiocast) {
  408. fclose(stream->stdiocast);
  409. stream->stdiocast = NULL;
  410. stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE;
  411. }
  412. }
  413. if (close_options & PHP_STREAM_FREE_RELEASE_STREAM) {
  414. while (stream->readfilters.head) {
  415. if (stream->readfilters.head->res != NULL) {
  416. zend_list_close(stream->readfilters.head->res);
  417. }
  418. php_stream_filter_remove(stream->readfilters.head, 1);
  419. }
  420. while (stream->writefilters.head) {
  421. if (stream->writefilters.head->res != NULL) {
  422. zend_list_close(stream->writefilters.head->res);
  423. }
  424. php_stream_filter_remove(stream->writefilters.head, 1);
  425. }
  426. if (stream->wrapper && stream->wrapper->wops && stream->wrapper->wops->stream_closer) {
  427. stream->wrapper->wops->stream_closer(stream->wrapper, stream);
  428. stream->wrapper = NULL;
  429. }
  430. if (Z_TYPE(stream->wrapperdata) != IS_UNDEF) {
  431. zval_ptr_dtor(&stream->wrapperdata);
  432. ZVAL_UNDEF(&stream->wrapperdata);
  433. }
  434. if (stream->readbuf) {
  435. pefree(stream->readbuf, stream->is_persistent);
  436. stream->readbuf = NULL;
  437. }
  438. if (stream->is_persistent && (close_options & PHP_STREAM_FREE_PERSISTENT)) {
  439. /* we don't work with *stream but need its value for comparison */
  440. zend_hash_apply_with_argument(&EG(persistent_list), _php_stream_free_persistent, stream);
  441. }
  442. if (stream->orig_path) {
  443. pefree(stream->orig_path, stream->is_persistent);
  444. stream->orig_path = NULL;
  445. }
  446. pefree(stream, stream->is_persistent);
  447. }
  448. if (context) {
  449. zend_list_delete(context->res);
  450. }
  451. return ret;
  452. }
  453. /* }}} */
  454. /* {{{ generic stream operations */
  455. PHPAPI int _php_stream_fill_read_buffer(php_stream *stream, size_t size)
  456. {
  457. /* allocate/fill the buffer */
  458. if (stream->readfilters.head) {
  459. char *chunk_buf;
  460. php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL };
  461. php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap;
  462. /* allocate a buffer for reading chunks */
  463. chunk_buf = emalloc(stream->chunk_size);
  464. while (!stream->eof && (stream->writepos - stream->readpos < (zend_off_t)size)) {
  465. ssize_t justread = 0;
  466. int flags;
  467. php_stream_bucket *bucket;
  468. php_stream_filter_status_t status = PSFS_ERR_FATAL;
  469. php_stream_filter *filter;
  470. /* read a chunk into a bucket */
  471. justread = stream->ops->read(stream, chunk_buf, stream->chunk_size);
  472. if (justread < 0 && stream->writepos == stream->readpos) {
  473. efree(chunk_buf);
  474. return FAILURE;
  475. } else if (justread > 0) {
  476. bucket = php_stream_bucket_new(stream, chunk_buf, justread, 0, 0);
  477. /* after this call, bucket is owned by the brigade */
  478. php_stream_bucket_append(brig_inp, bucket);
  479. flags = PSFS_FLAG_NORMAL;
  480. } else {
  481. flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC;
  482. }
  483. /* wind the handle... */
  484. for (filter = stream->readfilters.head; filter; filter = filter->next) {
  485. status = filter->fops->filter(stream, filter, brig_inp, brig_outp, NULL, flags);
  486. if (status != PSFS_PASS_ON) {
  487. break;
  488. }
  489. /* brig_out becomes brig_in.
  490. * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets
  491. * to its own brigade */
  492. brig_swap = brig_inp;
  493. brig_inp = brig_outp;
  494. brig_outp = brig_swap;
  495. memset(brig_outp, 0, sizeof(*brig_outp));
  496. }
  497. switch (status) {
  498. case PSFS_PASS_ON:
  499. /* we get here when the last filter in the chain has data to pass on.
  500. * in this situation, we are passing the brig_in brigade into the
  501. * stream read buffer */
  502. while (brig_inp->head) {
  503. bucket = brig_inp->head;
  504. /* reduce buffer memory consumption if possible, to avoid a realloc */
  505. if (stream->readbuf && stream->readbuflen - stream->writepos < bucket->buflen) {
  506. if (stream->writepos > stream->readpos) {
  507. memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->writepos - stream->readpos);
  508. }
  509. stream->writepos -= stream->readpos;
  510. stream->readpos = 0;
  511. }
  512. /* grow buffer to hold this bucket */
  513. if (stream->readbuflen - stream->writepos < bucket->buflen) {
  514. stream->readbuflen += bucket->buflen;
  515. stream->readbuf = perealloc(stream->readbuf, stream->readbuflen,
  516. stream->is_persistent);
  517. }
  518. if (bucket->buflen) {
  519. memcpy(stream->readbuf + stream->writepos, bucket->buf, bucket->buflen);
  520. }
  521. stream->writepos += bucket->buflen;
  522. php_stream_bucket_unlink(bucket);
  523. php_stream_bucket_delref(bucket);
  524. }
  525. break;
  526. case PSFS_FEED_ME:
  527. /* when a filter needs feeding, there is no brig_out to deal with.
  528. * we simply continue the loop; if the caller needs more data,
  529. * we will read again, otherwise out job is done here */
  530. break;
  531. case PSFS_ERR_FATAL:
  532. /* some fatal error. Theoretically, the stream is borked, so all
  533. * further reads should fail. */
  534. stream->eof = 1;
  535. efree(chunk_buf);
  536. return FAILURE;
  537. }
  538. if (justread <= 0) {
  539. break;
  540. }
  541. }
  542. efree(chunk_buf);
  543. return SUCCESS;
  544. } else {
  545. /* is there enough data in the buffer ? */
  546. if (stream->writepos - stream->readpos < (zend_off_t)size) {
  547. ssize_t justread = 0;
  548. /* reduce buffer memory consumption if possible, to avoid a realloc */
  549. if (stream->readbuf && stream->readbuflen - stream->writepos < stream->chunk_size) {
  550. if (stream->writepos > stream->readpos) {
  551. memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->writepos - stream->readpos);
  552. }
  553. stream->writepos -= stream->readpos;
  554. stream->readpos = 0;
  555. }
  556. /* grow the buffer if required
  557. * TODO: this can fail for persistent streams */
  558. if (stream->readbuflen - stream->writepos < stream->chunk_size) {
  559. stream->readbuflen += stream->chunk_size;
  560. stream->readbuf = perealloc(stream->readbuf, stream->readbuflen,
  561. stream->is_persistent);
  562. }
  563. justread = stream->ops->read(stream, (char*)stream->readbuf + stream->writepos,
  564. stream->readbuflen - stream->writepos
  565. );
  566. if (justread < 0) {
  567. return FAILURE;
  568. }
  569. stream->writepos += justread;
  570. }
  571. return SUCCESS;
  572. }
  573. }
  574. PHPAPI ssize_t _php_stream_read(php_stream *stream, char *buf, size_t size)
  575. {
  576. ssize_t toread = 0, didread = 0;
  577. while (size > 0) {
  578. /* take from the read buffer first.
  579. * It is possible that a buffered stream was switched to non-buffered, so we
  580. * drain the remainder of the buffer before using the "raw" read mode for
  581. * the excess */
  582. if (stream->writepos > stream->readpos) {
  583. toread = stream->writepos - stream->readpos;
  584. if (toread > size) {
  585. toread = size;
  586. }
  587. memcpy(buf, stream->readbuf + stream->readpos, toread);
  588. stream->readpos += toread;
  589. size -= toread;
  590. buf += toread;
  591. didread += toread;
  592. }
  593. /* ignore eof here; the underlying state might have changed */
  594. if (size == 0) {
  595. break;
  596. }
  597. if (!stream->readfilters.head && (stream->flags & PHP_STREAM_FLAG_NO_BUFFER || stream->chunk_size == 1)) {
  598. toread = stream->ops->read(stream, buf, size);
  599. if (toread < 0) {
  600. /* Report an error if the read failed and we did not read any data
  601. * before that. Otherwise return the data we did read. */
  602. if (didread == 0) {
  603. return toread;
  604. }
  605. break;
  606. }
  607. } else {
  608. if (php_stream_fill_read_buffer(stream, size) != SUCCESS) {
  609. if (didread == 0) {
  610. return -1;
  611. }
  612. break;
  613. }
  614. toread = stream->writepos - stream->readpos;
  615. if ((size_t) toread > size) {
  616. toread = size;
  617. }
  618. if (toread > 0) {
  619. memcpy(buf, stream->readbuf + stream->readpos, toread);
  620. stream->readpos += toread;
  621. }
  622. }
  623. if (toread > 0) {
  624. didread += toread;
  625. buf += toread;
  626. size -= toread;
  627. } else {
  628. /* EOF, or temporary end of data (for non-blocking mode). */
  629. break;
  630. }
  631. /* just break anyway, to avoid greedy read for file://, php://memory, and php://temp */
  632. if ((stream->wrapper != &php_plain_files_wrapper) &&
  633. (stream->ops != &php_stream_memory_ops) &&
  634. (stream->ops != &php_stream_temp_ops)) {
  635. break;
  636. }
  637. }
  638. if (didread > 0) {
  639. stream->position += didread;
  640. }
  641. return didread;
  642. }
  643. /* Like php_stream_read(), but reading into a zend_string buffer. This has some similarity
  644. * to the copy_to_mem() operation, but only performs a single direct read. */
  645. PHPAPI zend_string *php_stream_read_to_str(php_stream *stream, size_t len)
  646. {
  647. zend_string *str = zend_string_alloc(len, 0);
  648. ssize_t read = php_stream_read(stream, ZSTR_VAL(str), len);
  649. if (read < 0) {
  650. zend_string_efree(str);
  651. return NULL;
  652. }
  653. ZSTR_LEN(str) = read;
  654. ZSTR_VAL(str)[read] = 0;
  655. if ((size_t) read < len / 2) {
  656. return zend_string_truncate(str, read, 0);
  657. }
  658. return str;
  659. }
  660. PHPAPI int _php_stream_eof(php_stream *stream)
  661. {
  662. /* if there is data in the buffer, it's not EOF */
  663. if (stream->writepos - stream->readpos > 0) {
  664. return 0;
  665. }
  666. /* use the configured timeout when checking eof */
  667. if (!stream->eof && PHP_STREAM_OPTION_RETURN_ERR ==
  668. php_stream_set_option(stream, PHP_STREAM_OPTION_CHECK_LIVENESS,
  669. 0, NULL)) {
  670. stream->eof = 1;
  671. }
  672. return stream->eof;
  673. }
  674. PHPAPI int _php_stream_putc(php_stream *stream, int c)
  675. {
  676. unsigned char buf = c;
  677. if (php_stream_write(stream, (char*)&buf, 1) > 0) {
  678. return 1;
  679. }
  680. return EOF;
  681. }
  682. PHPAPI int _php_stream_getc(php_stream *stream)
  683. {
  684. char buf;
  685. if (php_stream_read(stream, &buf, 1) > 0) {
  686. return buf & 0xff;
  687. }
  688. return EOF;
  689. }
  690. PHPAPI int _php_stream_puts(php_stream *stream, const char *buf)
  691. {
  692. size_t len;
  693. char newline[2] = "\n"; /* is this OK for Win? */
  694. len = strlen(buf);
  695. if (len > 0 && php_stream_write(stream, buf, len) > 0 && php_stream_write(stream, newline, 1) > 0) {
  696. return 1;
  697. }
  698. return 0;
  699. }
  700. PHPAPI int _php_stream_stat(php_stream *stream, php_stream_statbuf *ssb)
  701. {
  702. memset(ssb, 0, sizeof(*ssb));
  703. /* if the stream was wrapped, allow the wrapper to stat it */
  704. if (stream->wrapper && stream->wrapper->wops->stream_stat != NULL) {
  705. return stream->wrapper->wops->stream_stat(stream->wrapper, stream, ssb);
  706. }
  707. /* if the stream doesn't directly support stat-ing, return with failure.
  708. * We could try and emulate this by casting to a FD and fstat-ing it,
  709. * but since the fd might not represent the actual underlying content
  710. * this would give bogus results. */
  711. if (stream->ops->stat == NULL) {
  712. return -1;
  713. }
  714. return (stream->ops->stat)(stream, ssb);
  715. }
  716. PHPAPI const char *php_stream_locate_eol(php_stream *stream, zend_string *buf)
  717. {
  718. size_t avail;
  719. const char *cr, *lf, *eol = NULL;
  720. const char *readptr;
  721. if (!buf) {
  722. readptr = (char*)stream->readbuf + stream->readpos;
  723. avail = stream->writepos - stream->readpos;
  724. } else {
  725. readptr = ZSTR_VAL(buf);
  726. avail = ZSTR_LEN(buf);
  727. }
  728. /* Look for EOL */
  729. if (stream->flags & PHP_STREAM_FLAG_DETECT_EOL) {
  730. cr = memchr(readptr, '\r', avail);
  731. lf = memchr(readptr, '\n', avail);
  732. if (cr && lf != cr + 1 && !(lf && lf < cr)) {
  733. /* mac */
  734. stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL;
  735. stream->flags |= PHP_STREAM_FLAG_EOL_MAC;
  736. eol = cr;
  737. } else if ((cr && lf && cr == lf - 1) || (lf)) {
  738. /* dos or unix endings */
  739. stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL;
  740. eol = lf;
  741. }
  742. } else if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) {
  743. eol = memchr(readptr, '\r', avail);
  744. } else {
  745. /* unix (and dos) line endings */
  746. eol = memchr(readptr, '\n', avail);
  747. }
  748. return eol;
  749. }
  750. /* If buf == NULL, the buffer will be allocated automatically and will be of an
  751. * appropriate length to hold the line, regardless of the line length, memory
  752. * permitting */
  753. PHPAPI char *_php_stream_get_line(php_stream *stream, char *buf, size_t maxlen,
  754. size_t *returned_len)
  755. {
  756. size_t avail = 0;
  757. size_t current_buf_size = 0;
  758. size_t total_copied = 0;
  759. int grow_mode = 0;
  760. char *bufstart = buf;
  761. if (buf == NULL) {
  762. grow_mode = 1;
  763. } else if (maxlen == 0) {
  764. return NULL;
  765. }
  766. /*
  767. * If the underlying stream operations block when no new data is readable,
  768. * we need to take extra precautions.
  769. *
  770. * If there is buffered data available, we check for a EOL. If it exists,
  771. * we pass the data immediately back to the caller. This saves a call
  772. * to the read implementation and will not block where blocking
  773. * is not necessary at all.
  774. *
  775. * If the stream buffer contains more data than the caller requested,
  776. * we can also avoid that costly step and simply return that data.
  777. */
  778. for (;;) {
  779. avail = stream->writepos - stream->readpos;
  780. if (avail > 0) {
  781. size_t cpysz = 0;
  782. char *readptr;
  783. const char *eol;
  784. int done = 0;
  785. readptr = (char*)stream->readbuf + stream->readpos;
  786. eol = php_stream_locate_eol(stream, NULL);
  787. if (eol) {
  788. cpysz = eol - readptr + 1;
  789. done = 1;
  790. } else {
  791. cpysz = avail;
  792. }
  793. if (grow_mode) {
  794. /* allow room for a NUL. If this realloc is really a realloc
  795. * (ie: second time around), we get an extra byte. In most
  796. * cases, with the default chunk size of 8K, we will only
  797. * incur that overhead once. When people have lines longer
  798. * than 8K, we waste 1 byte per additional 8K or so.
  799. * That seems acceptable to me, to avoid making this code
  800. * hard to follow */
  801. bufstart = erealloc(bufstart, current_buf_size + cpysz + 1);
  802. current_buf_size += cpysz + 1;
  803. buf = bufstart + total_copied;
  804. } else {
  805. if (cpysz >= maxlen - 1) {
  806. cpysz = maxlen - 1;
  807. done = 1;
  808. }
  809. }
  810. memcpy(buf, readptr, cpysz);
  811. stream->position += cpysz;
  812. stream->readpos += cpysz;
  813. buf += cpysz;
  814. maxlen -= cpysz;
  815. total_copied += cpysz;
  816. if (done) {
  817. break;
  818. }
  819. } else if (stream->eof) {
  820. break;
  821. } else {
  822. /* XXX: Should be fine to always read chunk_size */
  823. size_t toread;
  824. if (grow_mode) {
  825. toread = stream->chunk_size;
  826. } else {
  827. toread = maxlen - 1;
  828. if (toread > stream->chunk_size) {
  829. toread = stream->chunk_size;
  830. }
  831. }
  832. php_stream_fill_read_buffer(stream, toread);
  833. if (stream->writepos - stream->readpos == 0) {
  834. break;
  835. }
  836. }
  837. }
  838. if (total_copied == 0) {
  839. if (grow_mode) {
  840. assert(bufstart == NULL);
  841. }
  842. return NULL;
  843. }
  844. buf[0] = '\0';
  845. if (returned_len) {
  846. *returned_len = total_copied;
  847. }
  848. return bufstart;
  849. }
  850. #define STREAM_BUFFERED_AMOUNT(stream) \
  851. ((size_t)(((stream)->writepos) - (stream)->readpos))
  852. static const char *_php_stream_search_delim(php_stream *stream,
  853. size_t maxlen,
  854. size_t skiplen,
  855. const char *delim, /* non-empty! */
  856. size_t delim_len)
  857. {
  858. size_t seek_len;
  859. /* set the maximum number of bytes we're allowed to read from buffer */
  860. seek_len = MIN(STREAM_BUFFERED_AMOUNT(stream), maxlen);
  861. if (seek_len <= skiplen) {
  862. return NULL;
  863. }
  864. if (delim_len == 1) {
  865. return memchr(&stream->readbuf[stream->readpos + skiplen],
  866. delim[0], seek_len - skiplen);
  867. } else {
  868. return php_memnstr((char*)&stream->readbuf[stream->readpos + skiplen],
  869. delim, delim_len,
  870. (char*)&stream->readbuf[stream->readpos + seek_len]);
  871. }
  872. }
  873. PHPAPI zend_string *php_stream_get_record(php_stream *stream, size_t maxlen, const char *delim, size_t delim_len)
  874. {
  875. zend_string *ret_buf; /* returned buffer */
  876. const char *found_delim = NULL;
  877. size_t buffered_len,
  878. tent_ret_len; /* tentative returned length */
  879. int has_delim = delim_len > 0;
  880. if (maxlen == 0) {
  881. return NULL;
  882. }
  883. if (has_delim) {
  884. found_delim = _php_stream_search_delim(
  885. stream, maxlen, 0, delim, delim_len);
  886. }
  887. buffered_len = STREAM_BUFFERED_AMOUNT(stream);
  888. /* try to read up to maxlen length bytes while we don't find the delim */
  889. while (!found_delim && buffered_len < maxlen) {
  890. size_t just_read,
  891. to_read_now;
  892. to_read_now = MIN(maxlen - buffered_len, stream->chunk_size);
  893. php_stream_fill_read_buffer(stream, buffered_len + to_read_now);
  894. just_read = STREAM_BUFFERED_AMOUNT(stream) - buffered_len;
  895. /* Assume the stream is temporarily or permanently out of data */
  896. if (just_read == 0) {
  897. break;
  898. }
  899. if (has_delim) {
  900. /* search for delimiter, but skip buffered_len (the number of bytes
  901. * buffered before this loop iteration), as they have already been
  902. * searched for the delimiter.
  903. * The left part of the delimiter may still remain in the buffer,
  904. * so subtract up to <delim_len - 1> from buffered_len, which is
  905. * the amount of data we skip on this search as an optimization
  906. */
  907. found_delim = _php_stream_search_delim(
  908. stream, maxlen,
  909. buffered_len >= (delim_len - 1)
  910. ? buffered_len - (delim_len - 1)
  911. : 0,
  912. delim, delim_len);
  913. if (found_delim) {
  914. break;
  915. }
  916. }
  917. buffered_len += just_read;
  918. }
  919. if (has_delim && found_delim) {
  920. tent_ret_len = found_delim - (char*)&stream->readbuf[stream->readpos];
  921. } else if (!has_delim && STREAM_BUFFERED_AMOUNT(stream) >= maxlen) {
  922. tent_ret_len = maxlen;
  923. } else {
  924. /* return with error if the delimiter string (if any) was not found, we
  925. * could not completely fill the read buffer with maxlen bytes and we
  926. * don't know we've reached end of file. Added with non-blocking streams
  927. * in mind, where this situation is frequent */
  928. if (STREAM_BUFFERED_AMOUNT(stream) < maxlen && !stream->eof) {
  929. return NULL;
  930. } else if (STREAM_BUFFERED_AMOUNT(stream) == 0 && stream->eof) {
  931. /* refuse to return an empty string just because by accident
  932. * we knew of EOF in a read that returned no data */
  933. return NULL;
  934. } else {
  935. tent_ret_len = MIN(STREAM_BUFFERED_AMOUNT(stream), maxlen);
  936. }
  937. }
  938. ret_buf = zend_string_alloc(tent_ret_len, 0);
  939. /* php_stream_read will not call ops->read here because the necessary
  940. * data is guaranteedly buffered */
  941. ZSTR_LEN(ret_buf) = php_stream_read(stream, ZSTR_VAL(ret_buf), tent_ret_len);
  942. if (found_delim) {
  943. stream->readpos += delim_len;
  944. stream->position += delim_len;
  945. }
  946. ZSTR_VAL(ret_buf)[ZSTR_LEN(ret_buf)] = '\0';
  947. return ret_buf;
  948. }
  949. /* Writes a buffer directly to a stream, using multiple of the chunk size */
  950. static ssize_t _php_stream_write_buffer(php_stream *stream, const char *buf, size_t count)
  951. {
  952. ssize_t didwrite = 0;
  953. /* if we have a seekable stream we need to ensure that data is written at the
  954. * current stream->position. This means invalidating the read buffer and then
  955. * performing a low-level seek */
  956. if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && stream->readpos != stream->writepos) {
  957. stream->readpos = stream->writepos = 0;
  958. stream->ops->seek(stream, stream->position, SEEK_SET, &stream->position);
  959. }
  960. while (count > 0) {
  961. ssize_t justwrote = stream->ops->write(stream, buf, count);
  962. if (justwrote <= 0) {
  963. /* If we already successfully wrote some bytes and a write error occurred
  964. * later, report the successfully written bytes. */
  965. if (didwrite == 0) {
  966. return justwrote;
  967. }
  968. return didwrite;
  969. }
  970. buf += justwrote;
  971. count -= justwrote;
  972. didwrite += justwrote;
  973. /* Only screw with the buffer if we can seek, otherwise we lose data
  974. * buffered from fifos and sockets */
  975. if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) {
  976. stream->position += justwrote;
  977. }
  978. }
  979. return didwrite;
  980. }
  981. /* push some data through the write filter chain.
  982. * buf may be NULL, if flags are set to indicate a flush.
  983. * This may trigger a real write to the stream.
  984. * Returns the number of bytes consumed from buf by the first filter in the chain.
  985. * */
  986. static ssize_t _php_stream_write_filtered(php_stream *stream, const char *buf, size_t count, int flags)
  987. {
  988. size_t consumed = 0;
  989. php_stream_bucket *bucket;
  990. php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL };
  991. php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap;
  992. php_stream_filter_status_t status = PSFS_ERR_FATAL;
  993. php_stream_filter *filter;
  994. if (buf) {
  995. bucket = php_stream_bucket_new(stream, (char *)buf, count, 0, 0);
  996. php_stream_bucket_append(&brig_in, bucket);
  997. }
  998. for (filter = stream->writefilters.head; filter; filter = filter->next) {
  999. /* for our return value, we are interested in the number of bytes consumed from
  1000. * the first filter in the chain */
  1001. status = filter->fops->filter(stream, filter, brig_inp, brig_outp,
  1002. filter == stream->writefilters.head ? &consumed : NULL, flags);
  1003. if (status != PSFS_PASS_ON) {
  1004. break;
  1005. }
  1006. /* brig_out becomes brig_in.
  1007. * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets
  1008. * to its own brigade */
  1009. brig_swap = brig_inp;
  1010. brig_inp = brig_outp;
  1011. brig_outp = brig_swap;
  1012. memset(brig_outp, 0, sizeof(*brig_outp));
  1013. }
  1014. switch (status) {
  1015. case PSFS_PASS_ON:
  1016. /* filter chain generated some output; push it through to the
  1017. * underlying stream */
  1018. while (brig_inp->head) {
  1019. bucket = brig_inp->head;
  1020. if (_php_stream_write_buffer(stream, bucket->buf, bucket->buflen) < 0) {
  1021. consumed = (ssize_t) -1;
  1022. }
  1023. /* Potential error situation - eg: no space on device. Perhaps we should keep this brigade
  1024. * hanging around and try to write it later.
  1025. * At the moment, we just drop it on the floor
  1026. * */
  1027. php_stream_bucket_unlink(bucket);
  1028. php_stream_bucket_delref(bucket);
  1029. }
  1030. break;
  1031. case PSFS_FEED_ME:
  1032. /* need more data before we can push data through to the stream */
  1033. break;
  1034. case PSFS_ERR_FATAL:
  1035. /* some fatal error. Theoretically, the stream is borked, so all
  1036. * further writes should fail. */
  1037. return (ssize_t) -1;
  1038. }
  1039. return consumed;
  1040. }
  1041. PHPAPI int _php_stream_flush(php_stream *stream, int closing)
  1042. {
  1043. int ret = 0;
  1044. if (stream->writefilters.head) {
  1045. _php_stream_write_filtered(stream, NULL, 0, closing ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC );
  1046. }
  1047. stream->flags &= ~PHP_STREAM_FLAG_WAS_WRITTEN;
  1048. if (stream->ops->flush) {
  1049. ret = stream->ops->flush(stream);
  1050. }
  1051. return ret;
  1052. }
  1053. PHPAPI ssize_t _php_stream_write(php_stream *stream, const char *buf, size_t count)
  1054. {
  1055. ssize_t bytes;
  1056. if (count == 0) {
  1057. return 0;
  1058. }
  1059. ZEND_ASSERT(buf != NULL);
  1060. if (stream->ops->write == NULL) {
  1061. php_error_docref(NULL, E_NOTICE, "Stream is not writable");
  1062. return (ssize_t) -1;
  1063. }
  1064. if (stream->writefilters.head) {
  1065. bytes = _php_stream_write_filtered(stream, buf, count, PSFS_FLAG_NORMAL);
  1066. } else {
  1067. bytes = _php_stream_write_buffer(stream, buf, count);
  1068. }
  1069. if (bytes) {
  1070. stream->flags |= PHP_STREAM_FLAG_WAS_WRITTEN;
  1071. }
  1072. return bytes;
  1073. }
  1074. PHPAPI ssize_t _php_stream_printf(php_stream *stream, const char *fmt, ...)
  1075. {
  1076. ssize_t count;
  1077. char *buf;
  1078. va_list ap;
  1079. va_start(ap, fmt);
  1080. count = vspprintf(&buf, 0, fmt, ap);
  1081. va_end(ap);
  1082. if (!buf) {
  1083. return -1; /* error condition */
  1084. }
  1085. count = php_stream_write(stream, buf, count);
  1086. efree(buf);
  1087. return count;
  1088. }
  1089. PHPAPI zend_off_t _php_stream_tell(php_stream *stream)
  1090. {
  1091. return stream->position;
  1092. }
  1093. PHPAPI int _php_stream_seek(php_stream *stream, zend_off_t offset, int whence)
  1094. {
  1095. if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) {
  1096. /* flush to commit data written to the fopencookie FILE* */
  1097. fflush(stream->stdiocast);
  1098. }
  1099. /* handle the case where we are in the buffer */
  1100. if ((stream->flags & PHP_STREAM_FLAG_NO_BUFFER) == 0) {
  1101. switch(whence) {
  1102. case SEEK_CUR:
  1103. if (offset > 0 && offset <= stream->writepos - stream->readpos) {
  1104. stream->readpos += offset; /* if offset = ..., then readpos = writepos */
  1105. stream->position += offset;
  1106. stream->eof = 0;
  1107. return 0;
  1108. }
  1109. break;
  1110. case SEEK_SET:
  1111. if (offset > stream->position &&
  1112. offset <= stream->position + stream->writepos - stream->readpos) {
  1113. stream->readpos += offset - stream->position;
  1114. stream->position = offset;
  1115. stream->eof = 0;
  1116. return 0;
  1117. }
  1118. break;
  1119. }
  1120. }
  1121. if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) {
  1122. int ret;
  1123. if (stream->writefilters.head) {
  1124. _php_stream_flush(stream, 0);
  1125. }
  1126. switch(whence) {
  1127. case SEEK_CUR:
  1128. offset = stream->position + offset;
  1129. whence = SEEK_SET;
  1130. break;
  1131. }
  1132. ret = stream->ops->seek(stream, offset, whence, &stream->position);
  1133. if (((stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) || ret == 0) {
  1134. if (ret == 0) {
  1135. stream->eof = 0;
  1136. }
  1137. /* invalidate the buffer contents */
  1138. stream->readpos = stream->writepos = 0;
  1139. return ret;
  1140. }
  1141. /* else the stream has decided that it can't support seeking after all;
  1142. * fall through to attempt emulation */
  1143. }
  1144. /* emulate forward moving seeks with reads */
  1145. if (whence == SEEK_CUR && offset >= 0) {
  1146. char tmp[1024];
  1147. ssize_t didread;
  1148. while (offset > 0) {
  1149. if ((didread = php_stream_read(stream, tmp, MIN(offset, sizeof(tmp)))) <= 0) {
  1150. return -1;
  1151. }
  1152. offset -= didread;
  1153. }
  1154. stream->eof = 0;
  1155. return 0;
  1156. }
  1157. php_error_docref(NULL, E_WARNING, "Stream does not support seeking");
  1158. return -1;
  1159. }
  1160. PHPAPI int _php_stream_set_option(php_stream *stream, int option, int value, void *ptrparam)
  1161. {
  1162. int ret = PHP_STREAM_OPTION_RETURN_NOTIMPL;
  1163. if (stream->ops->set_option) {
  1164. ret = stream->ops->set_option(stream, option, value, ptrparam);
  1165. }
  1166. if (ret == PHP_STREAM_OPTION_RETURN_NOTIMPL) {
  1167. switch(option) {
  1168. case PHP_STREAM_OPTION_SET_CHUNK_SIZE:
  1169. /* XXX chunk size itself is of size_t, that might be ok or not for a particular case*/
  1170. ret = stream->chunk_size > INT_MAX ? INT_MAX : (int)stream->chunk_size;
  1171. stream->chunk_size = value;
  1172. return ret;
  1173. case PHP_STREAM_OPTION_READ_BUFFER:
  1174. /* try to match the buffer mode as best we can */
  1175. if (value == PHP_STREAM_BUFFER_NONE) {
  1176. stream->flags |= PHP_STREAM_FLAG_NO_BUFFER;
  1177. } else if (stream->flags & PHP_STREAM_FLAG_NO_BUFFER) {
  1178. stream->flags ^= PHP_STREAM_FLAG_NO_BUFFER;
  1179. }
  1180. ret = PHP_STREAM_OPTION_RETURN_OK;
  1181. break;
  1182. default:
  1183. ;
  1184. }
  1185. }
  1186. return ret;
  1187. }
  1188. PHPAPI int _php_stream_truncate_set_size(php_stream *stream, size_t newsize)
  1189. {
  1190. return php_stream_set_option(stream, PHP_STREAM_OPTION_TRUNCATE_API, PHP_STREAM_TRUNCATE_SET_SIZE, &newsize);
  1191. }
  1192. PHPAPI ssize_t _php_stream_passthru(php_stream * stream STREAMS_DC)
  1193. {
  1194. size_t bcount = 0;
  1195. char buf[8192];
  1196. ssize_t b;
  1197. if (php_stream_mmap_possible(stream)) {
  1198. char *p;
  1199. size_t mapped;
  1200. p = php_stream_mmap_range(stream, php_stream_tell(stream), PHP_STREAM_MMAP_ALL, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped);
  1201. if (p) {
  1202. do {
  1203. /* output functions return int, so pass in int max */
  1204. if (0 < (b = PHPWRITE(p + bcount, MIN(mapped - bcount, INT_MAX)))) {
  1205. bcount += b;
  1206. }
  1207. } while (b > 0 && mapped > bcount);
  1208. php_stream_mmap_unmap_ex(stream, mapped);
  1209. return bcount;
  1210. }
  1211. }
  1212. while ((b = php_stream_read(stream, buf, sizeof(buf))) > 0) {
  1213. PHPWRITE(buf, b);
  1214. bcount += b;
  1215. }
  1216. if (b < 0 && bcount == 0) {
  1217. return b;
  1218. }
  1219. return bcount;
  1220. }
  1221. PHPAPI zend_string *_php_stream_copy_to_mem(php_stream *src, size_t maxlen, int persistent STREAMS_DC)
  1222. {
  1223. ssize_t ret = 0;
  1224. char *ptr;
  1225. size_t len = 0, max_len;
  1226. int step = CHUNK_SIZE;
  1227. int min_room = CHUNK_SIZE / 4;
  1228. php_stream_statbuf ssbuf;
  1229. zend_string *result;
  1230. if (maxlen == 0) {
  1231. return ZSTR_EMPTY_ALLOC();
  1232. }
  1233. if (maxlen == PHP_STREAM_COPY_ALL) {
  1234. maxlen = 0;
  1235. }
  1236. if (maxlen > 0) {
  1237. result = zend_string_alloc(maxlen, persistent);
  1238. ptr = ZSTR_VAL(result);
  1239. while ((len < maxlen) && !php_stream_eof(src)) {
  1240. ret = php_stream_read(src, ptr, maxlen - len);
  1241. if (ret <= 0) {
  1242. // TODO: Propagate error?
  1243. break;
  1244. }
  1245. len += ret;
  1246. ptr += ret;
  1247. }
  1248. if (len) {
  1249. ZSTR_LEN(result) = len;
  1250. ZSTR_VAL(result)[len] = '\0';
  1251. /* Only truncate if the savings are large enough */
  1252. if (len < maxlen / 2) {
  1253. result = zend_string_truncate(result, len, persistent);
  1254. }
  1255. } else {
  1256. zend_string_free(result);
  1257. result = NULL;
  1258. }
  1259. return result;
  1260. }
  1261. /* avoid many reallocs by allocating a good sized chunk to begin with, if
  1262. * we can. Note that the stream may be filtered, in which case the stat
  1263. * result may be inaccurate, as the filter may inflate or deflate the
  1264. * number of bytes that we can read. In order to avoid an upsize followed
  1265. * by a downsize of the buffer, overestimate by the step size (which is
  1266. * 2K). */
  1267. if (php_stream_stat(src, &ssbuf) == 0 && ssbuf.sb.st_size > 0) {
  1268. max_len = ssbuf.sb.st_size + step;
  1269. } else {
  1270. max_len = step;
  1271. }
  1272. result = zend_string_alloc(max_len, persistent);
  1273. ptr = ZSTR_VAL(result);
  1274. // TODO: Propagate error?
  1275. while ((ret = php_stream_read(src, ptr, max_len - len)) > 0){
  1276. len += ret;
  1277. if (len + min_room >= max_len) {
  1278. result = zend_string_extend(result, max_len + step, persistent);
  1279. max_len += step;
  1280. ptr = ZSTR_VAL(result) + len;
  1281. } else {
  1282. ptr += ret;
  1283. }
  1284. }
  1285. if (len) {
  1286. result = zend_string_truncate(result, len, persistent);
  1287. ZSTR_VAL(result)[len] = '\0';
  1288. } else {
  1289. zend_string_free(result);
  1290. result = NULL;
  1291. }
  1292. return result;
  1293. }
  1294. /* Returns SUCCESS/FAILURE and sets *len to the number of bytes moved */
  1295. PHPAPI int _php_stream_copy_to_stream_ex(php_stream *src, php_stream *dest, size_t maxlen, size_t *len STREAMS_DC)
  1296. {
  1297. char buf[CHUNK_SIZE];
  1298. size_t haveread = 0;
  1299. size_t towrite;
  1300. size_t dummy;
  1301. php_stream_statbuf ssbuf;
  1302. if (!len) {
  1303. len = &dummy;
  1304. }
  1305. if (maxlen == 0) {
  1306. *len = 0;
  1307. return SUCCESS;
  1308. }
  1309. if (maxlen == PHP_STREAM_COPY_ALL) {
  1310. maxlen = 0;
  1311. }
  1312. if (php_stream_stat(src, &ssbuf) == 0) {
  1313. if (ssbuf.sb.st_size == 0
  1314. #ifdef S_ISREG
  1315. && S_ISREG(ssbuf.sb.st_mode)
  1316. #endif
  1317. ) {
  1318. *len = 0;
  1319. return SUCCESS;
  1320. }
  1321. }
  1322. if (php_stream_mmap_possible(src)) {
  1323. char *p;
  1324. size_t mapped;
  1325. p = php_stream_mmap_range(src, php_stream_tell(src), maxlen, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped);
  1326. if (p) {
  1327. ssize_t didwrite = php_stream_write(dest, p, mapped);
  1328. if (didwrite < 0) {
  1329. *len = 0;
  1330. return FAILURE;
  1331. }
  1332. php_stream_mmap_unmap_ex(src, mapped);
  1333. *len = didwrite;
  1334. /* we've got at least 1 byte to read
  1335. * less than 1 is an error
  1336. * AND read bytes match written */
  1337. if (mapped > 0 && mapped == didwrite) {
  1338. return SUCCESS;
  1339. }
  1340. return FAILURE;
  1341. }
  1342. }
  1343. while(1) {
  1344. size_t readchunk = sizeof(buf);
  1345. ssize_t didread;
  1346. char *writeptr;
  1347. if (maxlen && (maxlen - haveread) < readchunk) {
  1348. readchunk = maxlen - haveread;
  1349. }
  1350. didread = php_stream_read(src, buf, readchunk);
  1351. if (didread <= 0) {
  1352. *len = haveread;
  1353. return didread < 0 ? FAILURE : SUCCESS;
  1354. }
  1355. towrite = didread;
  1356. writeptr = buf;
  1357. haveread += didread;
  1358. while (towrite) {
  1359. ssize_t didwrite = php_stream_write(dest, writeptr, towrite);
  1360. if (didwrite <= 0) {
  1361. *len = haveread - (didread - towrite);
  1362. return FAILURE;
  1363. }
  1364. towrite -= didwrite;
  1365. writeptr += didwrite;
  1366. }
  1367. if (maxlen - haveread == 0) {
  1368. break;
  1369. }
  1370. }
  1371. *len = haveread;
  1372. /* we've got at least 1 byte to read.
  1373. * less than 1 is an error */
  1374. if (haveread > 0 || src->eof) {
  1375. return SUCCESS;
  1376. }
  1377. return FAILURE;
  1378. }
  1379. /* Returns the number of bytes moved.
  1380. * Returns 1 when source len is 0.
  1381. * Deprecated in favor of php_stream_copy_to_stream_ex() */
  1382. ZEND_ATTRIBUTE_DEPRECATED
  1383. PHPAPI size_t _php_stream_copy_to_stream(php_stream *src, php_stream *dest, size_t maxlen STREAMS_DC)
  1384. {
  1385. size_t len;
  1386. int ret = _php_stream_copy_to_stream_ex(src, dest, maxlen, &len STREAMS_REL_CC);
  1387. if (ret == SUCCESS && len == 0 && maxlen != 0) {
  1388. return 1;
  1389. }
  1390. return len;
  1391. }
  1392. /* }}} */
  1393. /* {{{ wrapper init and registration */
  1394. static void stream_resource_regular_dtor(zend_resource *rsrc)
  1395. {
  1396. php_stream *stream = (php_stream*)rsrc->ptr;
  1397. /* set the return value for pclose */
  1398. FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR);
  1399. }
  1400. static void stream_resource_persistent_dtor(zend_resource *rsrc)
  1401. {
  1402. php_stream *stream = (php_stream*)rsrc->ptr;
  1403. FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR);
  1404. }
  1405. void php_shutdown_stream_hashes(void)
  1406. {
  1407. if (FG(stream_wrappers)) {
  1408. zend_hash_destroy(FG(stream_wrappers));
  1409. efree(FG(stream_wrappers));
  1410. FG(stream_wrappers) = NULL;
  1411. }
  1412. if (FG(stream_filters)) {
  1413. zend_hash_destroy(FG(stream_filters));
  1414. efree(FG(stream_filters));
  1415. FG(stream_filters) = NULL;
  1416. }
  1417. if (FG(wrapper_errors)) {
  1418. zend_hash_destroy(FG(wrapper_errors));
  1419. efree(FG(wrapper_errors));
  1420. FG(wrapper_errors) = NULL;
  1421. }
  1422. }
  1423. int php_init_stream_wrappers(int module_number)
  1424. {
  1425. le_stream = zend_register_list_destructors_ex(stream_resource_regular_dtor, NULL, "stream", module_number);
  1426. le_pstream = zend_register_list_destructors_ex(NULL, stream_resource_persistent_dtor, "persistent stream", module_number);
  1427. /* Filters are cleaned up by the streams they're attached to */
  1428. le_stream_filter = zend_register_list_destructors_ex(NULL, NULL, "stream filter", module_number);
  1429. zend_hash_init(&url_stream_wrappers_hash, 8, NULL, NULL, 1);
  1430. zend_hash_init(php_get_stream_filters_hash_global(), 8, NULL, NULL, 1);
  1431. zend_hash_init(php_stream_xport_get_hash(), 8, NULL, NULL, 1);
  1432. return (php_stream_xport_register("tcp", php_stream_generic_socket_factory) == SUCCESS
  1433. &&
  1434. php_stream_xport_register("udp", php_stream_generic_socket_factory) == SUCCESS
  1435. #if defined(AF_UNIX) && !(defined(PHP_WIN32) || defined(__riscos__))
  1436. &&
  1437. php_stream_xport_register("unix", php_stream_generic_socket_factory) == SUCCESS
  1438. &&
  1439. php_stream_xport_register("udg", php_stream_generic_socket_factory) == SUCCESS
  1440. #endif
  1441. ) ? SUCCESS : FAILURE;
  1442. }
  1443. int php_shutdown_stream_wrappers(int module_number)
  1444. {
  1445. zend_hash_destroy(&url_stream_wrappers_hash);
  1446. zend_hash_destroy(php_get_stream_filters_hash_global());
  1447. zend_hash_destroy(php_stream_xport_get_hash());
  1448. return SUCCESS;
  1449. }
  1450. /* Validate protocol scheme names during registration
  1451. * Must conform to /^[a-zA-Z0-9+.-]+$/
  1452. */
  1453. static inline int php_stream_wrapper_scheme_validate(const char *protocol, unsigned int protocol_len)
  1454. {
  1455. unsigned int i;
  1456. for(i = 0; i < protocol_len; i++) {
  1457. if (!isalnum((int)protocol[i]) &&
  1458. protocol[i] != '+' &&
  1459. protocol[i] != '-' &&
  1460. protocol[i] != '.') {
  1461. return FAILURE;
  1462. }
  1463. }
  1464. return SUCCESS;
  1465. }
  1466. /* API for registering GLOBAL wrappers */
  1467. PHPAPI int php_register_url_stream_wrapper(const char *protocol, const php_stream_wrapper *wrapper)
  1468. {
  1469. unsigned int protocol_len = (unsigned int)strlen(protocol);
  1470. int ret;
  1471. zend_string *str;
  1472. if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) {
  1473. return FAILURE;
  1474. }
  1475. str = zend_string_init_interned(protocol, protocol_len, 1);
  1476. ret = zend_hash_add_ptr(&url_stream_wrappers_hash, str, (void*)wrapper) ? SUCCESS : FAILURE;
  1477. zend_string_release_ex(str, 1);
  1478. return ret;
  1479. }
  1480. PHPAPI int php_unregister_url_stream_wrapper(const char *protocol)
  1481. {
  1482. return zend_hash_str_del(&url_stream_wrappers_hash, protocol, strlen(protocol));
  1483. }
  1484. static void clone_wrapper_hash(void)
  1485. {
  1486. ALLOC_HASHTABLE(FG(stream_wrappers));
  1487. zend_hash_init(FG(stream_wrappers), zend_hash_num_elements(&url_stream_wrappers_hash), NULL, NULL, 0);
  1488. zend_hash_copy(FG(stream_wrappers), &url_stream_wrappers_hash, NULL);
  1489. }
  1490. /* API for registering VOLATILE wrappers */
  1491. PHPAPI int php_register_url_stream_wrapper_volatile(zend_string *protocol, php_stream_wrapper *wrapper)
  1492. {
  1493. if (php_stream_wrapper_scheme_validate(ZSTR_VAL(protocol), ZSTR_LEN(protocol)) == FAILURE) {
  1494. return FAILURE;
  1495. }
  1496. if (!FG(stream_wrappers)) {
  1497. clone_wrapper_hash();
  1498. }
  1499. return zend_hash_add_ptr(FG(stream_wrappers), protocol, wrapper) ? SUCCESS : FAILURE;
  1500. }
  1501. PHPAPI int php_unregister_url_stream_wrapper_volatile(zend_string *protocol)
  1502. {
  1503. if (!FG(stream_wrappers)) {
  1504. clone_wrapper_hash();
  1505. }
  1506. return zend_hash_del(FG(stream_wrappers), protocol);
  1507. }
  1508. /* }}} */
  1509. /* {{{ php_stream_locate_url_wrapper */
  1510. PHP

Large files files are truncated, but you can click here to view the full file