streams.c 63 KB

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