streams.c 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342
  1. /*
  2. +----------------------------------------------------------------------+
  3. | Copyright (c) The PHP Group |
  4. +----------------------------------------------------------------------+
  5. | This source file is subject to version 3.01 of the PHP license, |
  6. | that is bundled with this package in the file LICENSE, and is |
  7. | available through the world-wide-web at the following url: |
  8. | https://www.php.net/license/3_01.txt |
  9. | If you did not receive a copy of the PHP license and are unable to |
  10. | obtain it through the world-wide-web, please send a note to |
  11. | license@php.net so we can mail you a copy immediately. |
  12. +----------------------------------------------------------------------+
  13. | Authors: Wez Furlong <wez@thebrainroom.com> |
  14. | Borrowed code from: |
  15. | Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
  16. | Jim Winstead <jimw@php.net> |
  17. +----------------------------------------------------------------------+
  18. */
  19. #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, "PRESERVE_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 resources 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 || stream->writefilters.head) {
  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. size_t to_read_now = MIN(size, stream->chunk_size);
  460. char *chunk_buf;
  461. php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL };
  462. php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap;
  463. /* allocate a buffer for reading chunks */
  464. chunk_buf = emalloc(stream->chunk_size);
  465. while (!stream->eof && (stream->writepos - stream->readpos < (zend_off_t)to_read_now)) {
  466. ssize_t justread = 0;
  467. int flags;
  468. php_stream_bucket *bucket;
  469. php_stream_filter_status_t status = PSFS_ERR_FATAL;
  470. php_stream_filter *filter;
  471. /* read a chunk into a bucket */
  472. justread = stream->ops->read(stream, chunk_buf, stream->chunk_size);
  473. if (justread < 0 && stream->writepos == stream->readpos) {
  474. efree(chunk_buf);
  475. return FAILURE;
  476. } else if (justread > 0) {
  477. bucket = php_stream_bucket_new(stream, chunk_buf, justread, 0, 0);
  478. /* after this call, bucket is owned by the brigade */
  479. php_stream_bucket_append(brig_inp, bucket);
  480. flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_NORMAL;
  481. } else {
  482. flags = stream->eof ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC;
  483. }
  484. /* wind the handle... */
  485. for (filter = stream->readfilters.head; filter; filter = filter->next) {
  486. status = filter->fops->filter(stream, filter, brig_inp, brig_outp, NULL, flags);
  487. if (status != PSFS_PASS_ON) {
  488. break;
  489. }
  490. /* brig_out becomes brig_in.
  491. * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets
  492. * to its own brigade */
  493. brig_swap = brig_inp;
  494. brig_inp = brig_outp;
  495. brig_outp = brig_swap;
  496. memset(brig_outp, 0, sizeof(*brig_outp));
  497. }
  498. switch (status) {
  499. case PSFS_PASS_ON:
  500. /* we get here when the last filter in the chain has data to pass on.
  501. * in this situation, we are passing the brig_in brigade into the
  502. * stream read buffer */
  503. while (brig_inp->head) {
  504. bucket = brig_inp->head;
  505. /* reduce buffer memory consumption if possible, to avoid a realloc */
  506. if (stream->readbuf && stream->readbuflen - stream->writepos < bucket->buflen) {
  507. if (stream->writepos > stream->readpos) {
  508. memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->writepos - stream->readpos);
  509. }
  510. stream->writepos -= stream->readpos;
  511. stream->readpos = 0;
  512. }
  513. /* grow buffer to hold this bucket */
  514. if (stream->readbuflen - stream->writepos < bucket->buflen) {
  515. stream->readbuflen += bucket->buflen;
  516. stream->readbuf = perealloc(stream->readbuf, stream->readbuflen,
  517. stream->is_persistent);
  518. }
  519. if (bucket->buflen) {
  520. memcpy(stream->readbuf + stream->writepos, bucket->buf, bucket->buflen);
  521. }
  522. stream->writepos += bucket->buflen;
  523. php_stream_bucket_unlink(bucket);
  524. php_stream_bucket_delref(bucket);
  525. }
  526. break;
  527. case PSFS_FEED_ME:
  528. /* when a filter needs feeding, there is no brig_out to deal with.
  529. * we simply continue the loop; if the caller needs more data,
  530. * we will read again, otherwise out job is done here */
  531. break;
  532. case PSFS_ERR_FATAL:
  533. /* some fatal error. Theoretically, the stream is borked, so all
  534. * further reads should fail. */
  535. stream->eof = 1;
  536. efree(chunk_buf);
  537. return FAILURE;
  538. }
  539. if (justread <= 0) {
  540. break;
  541. }
  542. }
  543. efree(chunk_buf);
  544. return SUCCESS;
  545. } else {
  546. /* is there enough data in the buffer ? */
  547. if (stream->writepos - stream->readpos < (zend_off_t)size) {
  548. ssize_t justread = 0;
  549. /* reduce buffer memory consumption if possible, to avoid a realloc */
  550. if (stream->readbuf && stream->readbuflen - stream->writepos < stream->chunk_size) {
  551. if (stream->writepos > stream->readpos) {
  552. memmove(stream->readbuf, stream->readbuf + stream->readpos, stream->writepos - stream->readpos);
  553. }
  554. stream->writepos -= stream->readpos;
  555. stream->readpos = 0;
  556. }
  557. /* grow the buffer if required
  558. * TODO: this can fail for persistent streams */
  559. if (stream->readbuflen - stream->writepos < stream->chunk_size) {
  560. stream->readbuflen += stream->chunk_size;
  561. stream->readbuf = perealloc(stream->readbuf, stream->readbuflen,
  562. stream->is_persistent);
  563. }
  564. justread = stream->ops->read(stream, (char*)stream->readbuf + stream->writepos,
  565. stream->readbuflen - stream->writepos
  566. );
  567. if (justread < 0) {
  568. return FAILURE;
  569. }
  570. stream->writepos += justread;
  571. }
  572. return SUCCESS;
  573. }
  574. }
  575. PHPAPI ssize_t _php_stream_read(php_stream *stream, char *buf, size_t size)
  576. {
  577. ssize_t toread = 0, didread = 0;
  578. while (size > 0) {
  579. /* take from the read buffer first.
  580. * It is possible that a buffered stream was switched to non-buffered, so we
  581. * drain the remainder of the buffer before using the "raw" read mode for
  582. * the excess */
  583. if (stream->writepos > stream->readpos) {
  584. toread = stream->writepos - stream->readpos;
  585. if (toread > size) {
  586. toread = size;
  587. }
  588. memcpy(buf, stream->readbuf + stream->readpos, toread);
  589. stream->readpos += toread;
  590. size -= toread;
  591. buf += toread;
  592. didread += toread;
  593. }
  594. /* ignore eof here; the underlying state might have changed */
  595. if (size == 0) {
  596. break;
  597. }
  598. if (!stream->readfilters.head && ((stream->flags & PHP_STREAM_FLAG_NO_BUFFER) || stream->chunk_size == 1)) {
  599. toread = stream->ops->read(stream, buf, size);
  600. if (toread < 0) {
  601. /* Report an error if the read failed and we did not read any data
  602. * before that. Otherwise return the data we did read. */
  603. if (didread == 0) {
  604. return toread;
  605. }
  606. break;
  607. }
  608. } else {
  609. if (php_stream_fill_read_buffer(stream, size) != SUCCESS) {
  610. if (didread == 0) {
  611. return -1;
  612. }
  613. break;
  614. }
  615. toread = stream->writepos - stream->readpos;
  616. if ((size_t) toread > size) {
  617. toread = size;
  618. }
  619. if (toread > 0) {
  620. memcpy(buf, stream->readbuf + stream->readpos, toread);
  621. stream->readpos += toread;
  622. }
  623. }
  624. if (toread > 0) {
  625. didread += toread;
  626. buf += toread;
  627. size -= toread;
  628. } else {
  629. /* EOF, or temporary end of data (for non-blocking mode). */
  630. break;
  631. }
  632. /* just break anyway, to avoid greedy read for file://, php://memory, and php://temp */
  633. if ((stream->wrapper != &php_plain_files_wrapper) &&
  634. (stream->ops != &php_stream_memory_ops) &&
  635. (stream->ops != &php_stream_temp_ops)) {
  636. break;
  637. }
  638. }
  639. if (didread > 0) {
  640. stream->position += didread;
  641. }
  642. return didread;
  643. }
  644. /* Like php_stream_read(), but reading into a zend_string buffer. This has some similarity
  645. * to the copy_to_mem() operation, but only performs a single direct read. */
  646. PHPAPI zend_string *php_stream_read_to_str(php_stream *stream, size_t len)
  647. {
  648. zend_string *str = zend_string_alloc(len, 0);
  649. ssize_t read = php_stream_read(stream, ZSTR_VAL(str), len);
  650. if (read < 0) {
  651. zend_string_efree(str);
  652. return NULL;
  653. }
  654. ZSTR_LEN(str) = read;
  655. ZSTR_VAL(str)[read] = 0;
  656. if ((size_t) read < len / 2) {
  657. return zend_string_truncate(str, read, 0);
  658. }
  659. return str;
  660. }
  661. PHPAPI int _php_stream_eof(php_stream *stream)
  662. {
  663. /* if there is data in the buffer, it's not EOF */
  664. if (stream->writepos - stream->readpos > 0) {
  665. return 0;
  666. }
  667. /* use the configured timeout when checking eof */
  668. if (!stream->eof && PHP_STREAM_OPTION_RETURN_ERR ==
  669. php_stream_set_option(stream, PHP_STREAM_OPTION_CHECK_LIVENESS,
  670. 0, NULL)) {
  671. stream->eof = 1;
  672. }
  673. return stream->eof;
  674. }
  675. PHPAPI int _php_stream_putc(php_stream *stream, int c)
  676. {
  677. unsigned char buf = c;
  678. if (php_stream_write(stream, (char*)&buf, 1) > 0) {
  679. return 1;
  680. }
  681. return EOF;
  682. }
  683. PHPAPI int _php_stream_getc(php_stream *stream)
  684. {
  685. char buf;
  686. if (php_stream_read(stream, &buf, 1) > 0) {
  687. return buf & 0xff;
  688. }
  689. return EOF;
  690. }
  691. PHPAPI int _php_stream_puts(php_stream *stream, const char *buf)
  692. {
  693. size_t len;
  694. char newline[2] = "\n"; /* is this OK for Win? */
  695. len = strlen(buf);
  696. if (len > 0 && php_stream_write(stream, buf, len) > 0 && php_stream_write(stream, newline, 1) > 0) {
  697. return 1;
  698. }
  699. return 0;
  700. }
  701. PHPAPI int _php_stream_stat(php_stream *stream, php_stream_statbuf *ssb)
  702. {
  703. memset(ssb, 0, sizeof(*ssb));
  704. /* if the stream was wrapped, allow the wrapper to stat it */
  705. if (stream->wrapper && stream->wrapper->wops->stream_stat != NULL) {
  706. return stream->wrapper->wops->stream_stat(stream->wrapper, stream, ssb);
  707. }
  708. /* if the stream doesn't directly support stat-ing, return with failure.
  709. * We could try and emulate this by casting to a FD and fstat-ing it,
  710. * but since the fd might not represent the actual underlying content
  711. * this would give bogus results. */
  712. if (stream->ops->stat == NULL) {
  713. return -1;
  714. }
  715. return (stream->ops->stat)(stream, ssb);
  716. }
  717. PHPAPI const char *php_stream_locate_eol(php_stream *stream, zend_string *buf)
  718. {
  719. size_t avail;
  720. const char *cr, *lf, *eol = NULL;
  721. const char *readptr;
  722. if (!buf) {
  723. readptr = (char*)stream->readbuf + stream->readpos;
  724. avail = stream->writepos - stream->readpos;
  725. } else {
  726. readptr = ZSTR_VAL(buf);
  727. avail = ZSTR_LEN(buf);
  728. }
  729. /* Look for EOL */
  730. if (stream->flags & PHP_STREAM_FLAG_DETECT_EOL) {
  731. cr = memchr(readptr, '\r', avail);
  732. lf = memchr(readptr, '\n', avail);
  733. if (cr && lf != cr + 1 && !(lf && lf < cr)) {
  734. /* mac */
  735. stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL;
  736. stream->flags |= PHP_STREAM_FLAG_EOL_MAC;
  737. eol = cr;
  738. } else if ((cr && lf && cr == lf - 1) || (lf)) {
  739. /* dos or unix endings */
  740. stream->flags ^= PHP_STREAM_FLAG_DETECT_EOL;
  741. eol = lf;
  742. }
  743. } else if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) {
  744. eol = memchr(readptr, '\r', avail);
  745. } else {
  746. /* unix (and dos) line endings */
  747. eol = memchr(readptr, '\n', avail);
  748. }
  749. return eol;
  750. }
  751. /* If buf == NULL, the buffer will be allocated automatically and will be of an
  752. * appropriate length to hold the line, regardless of the line length, memory
  753. * permitting */
  754. PHPAPI char *_php_stream_get_line(php_stream *stream, char *buf, size_t maxlen,
  755. size_t *returned_len)
  756. {
  757. size_t avail = 0;
  758. size_t current_buf_size = 0;
  759. size_t total_copied = 0;
  760. int grow_mode = 0;
  761. char *bufstart = buf;
  762. if (buf == NULL) {
  763. grow_mode = 1;
  764. } else if (maxlen == 0) {
  765. return NULL;
  766. }
  767. /*
  768. * If the underlying stream operations block when no new data is readable,
  769. * we need to take extra precautions.
  770. *
  771. * If there is buffered data available, we check for a EOL. If it exists,
  772. * we pass the data immediately back to the caller. This saves a call
  773. * to the read implementation and will not block where blocking
  774. * is not necessary at all.
  775. *
  776. * If the stream buffer contains more data than the caller requested,
  777. * we can also avoid that costly step and simply return that data.
  778. */
  779. for (;;) {
  780. avail = stream->writepos - stream->readpos;
  781. if (avail > 0) {
  782. size_t cpysz = 0;
  783. char *readptr;
  784. const char *eol;
  785. int done = 0;
  786. readptr = (char*)stream->readbuf + stream->readpos;
  787. eol = php_stream_locate_eol(stream, NULL);
  788. if (eol) {
  789. cpysz = eol - readptr + 1;
  790. done = 1;
  791. } else {
  792. cpysz = avail;
  793. }
  794. if (grow_mode) {
  795. /* allow room for a NUL. If this realloc is really a realloc
  796. * (ie: second time around), we get an extra byte. In most
  797. * cases, with the default chunk size of 8K, we will only
  798. * incur that overhead once. When people have lines longer
  799. * than 8K, we waste 1 byte per additional 8K or so.
  800. * That seems acceptable to me, to avoid making this code
  801. * hard to follow */
  802. bufstart = erealloc(bufstart, current_buf_size + cpysz + 1);
  803. current_buf_size += cpysz + 1;
  804. buf = bufstart + total_copied;
  805. } else {
  806. if (cpysz >= maxlen - 1) {
  807. cpysz = maxlen - 1;
  808. done = 1;
  809. }
  810. }
  811. memcpy(buf, readptr, cpysz);
  812. stream->position += cpysz;
  813. stream->readpos += cpysz;
  814. buf += cpysz;
  815. maxlen -= cpysz;
  816. total_copied += cpysz;
  817. if (done) {
  818. break;
  819. }
  820. } else if (stream->eof) {
  821. break;
  822. } else {
  823. /* XXX: Should be fine to always read chunk_size */
  824. size_t toread;
  825. if (grow_mode) {
  826. toread = stream->chunk_size;
  827. } else {
  828. toread = maxlen - 1;
  829. if (toread > stream->chunk_size) {
  830. toread = stream->chunk_size;
  831. }
  832. }
  833. php_stream_fill_read_buffer(stream, toread);
  834. if (stream->writepos - stream->readpos == 0) {
  835. break;
  836. }
  837. }
  838. }
  839. if (total_copied == 0) {
  840. if (grow_mode) {
  841. assert(bufstart == NULL);
  842. }
  843. return NULL;
  844. }
  845. buf[0] = '\0';
  846. if (returned_len) {
  847. *returned_len = total_copied;
  848. }
  849. return bufstart;
  850. }
  851. #define STREAM_BUFFERED_AMOUNT(stream) \
  852. ((size_t)(((stream)->writepos) - (stream)->readpos))
  853. static const char *_php_stream_search_delim(php_stream *stream,
  854. size_t maxlen,
  855. size_t skiplen,
  856. const char *delim, /* non-empty! */
  857. size_t delim_len)
  858. {
  859. size_t seek_len;
  860. /* set the maximum number of bytes we're allowed to read from buffer */
  861. seek_len = MIN(STREAM_BUFFERED_AMOUNT(stream), maxlen);
  862. if (seek_len <= skiplen) {
  863. return NULL;
  864. }
  865. if (delim_len == 1) {
  866. return memchr(&stream->readbuf[stream->readpos + skiplen],
  867. delim[0], seek_len - skiplen);
  868. } else {
  869. return php_memnstr((char*)&stream->readbuf[stream->readpos + skiplen],
  870. delim, delim_len,
  871. (char*)&stream->readbuf[stream->readpos + seek_len]);
  872. }
  873. }
  874. PHPAPI zend_string *php_stream_get_record(php_stream *stream, size_t maxlen, const char *delim, size_t delim_len)
  875. {
  876. zend_string *ret_buf; /* returned buffer */
  877. const char *found_delim = NULL;
  878. size_t buffered_len,
  879. tent_ret_len; /* tentative returned length */
  880. int has_delim = delim_len > 0;
  881. if (maxlen == 0) {
  882. return NULL;
  883. }
  884. if (has_delim) {
  885. found_delim = _php_stream_search_delim(
  886. stream, maxlen, 0, delim, delim_len);
  887. }
  888. buffered_len = STREAM_BUFFERED_AMOUNT(stream);
  889. /* try to read up to maxlen length bytes while we don't find the delim */
  890. while (!found_delim && buffered_len < maxlen) {
  891. size_t just_read,
  892. to_read_now;
  893. to_read_now = MIN(maxlen - buffered_len, stream->chunk_size);
  894. php_stream_fill_read_buffer(stream, buffered_len + to_read_now);
  895. just_read = STREAM_BUFFERED_AMOUNT(stream) - buffered_len;
  896. /* Assume the stream is temporarily or permanently out of data */
  897. if (just_read == 0) {
  898. break;
  899. }
  900. if (has_delim) {
  901. /* search for delimiter, but skip buffered_len (the number of bytes
  902. * buffered before this loop iteration), as they have already been
  903. * searched for the delimiter.
  904. * The left part of the delimiter may still remain in the buffer,
  905. * so subtract up to <delim_len - 1> from buffered_len, which is
  906. * the amount of data we skip on this search as an optimization
  907. */
  908. found_delim = _php_stream_search_delim(
  909. stream, maxlen,
  910. buffered_len >= (delim_len - 1)
  911. ? buffered_len - (delim_len - 1)
  912. : 0,
  913. delim, delim_len);
  914. if (found_delim) {
  915. break;
  916. }
  917. }
  918. buffered_len += just_read;
  919. }
  920. if (has_delim && found_delim) {
  921. tent_ret_len = found_delim - (char*)&stream->readbuf[stream->readpos];
  922. } else if (!has_delim && STREAM_BUFFERED_AMOUNT(stream) >= maxlen) {
  923. tent_ret_len = maxlen;
  924. } else {
  925. /* return with error if the delimiter string (if any) was not found, we
  926. * could not completely fill the read buffer with maxlen bytes and we
  927. * don't know we've reached end of file. Added with non-blocking streams
  928. * in mind, where this situation is frequent */
  929. if (STREAM_BUFFERED_AMOUNT(stream) < maxlen && !stream->eof) {
  930. return NULL;
  931. } else if (STREAM_BUFFERED_AMOUNT(stream) == 0 && stream->eof) {
  932. /* refuse to return an empty string just because by accident
  933. * we knew of EOF in a read that returned no data */
  934. return NULL;
  935. } else {
  936. tent_ret_len = MIN(STREAM_BUFFERED_AMOUNT(stream), maxlen);
  937. }
  938. }
  939. ret_buf = zend_string_alloc(tent_ret_len, 0);
  940. /* php_stream_read will not call ops->read here because the necessary
  941. * data is guaranteed to be buffered */
  942. ZSTR_LEN(ret_buf) = php_stream_read(stream, ZSTR_VAL(ret_buf), tent_ret_len);
  943. if (found_delim) {
  944. stream->readpos += delim_len;
  945. stream->position += delim_len;
  946. }
  947. ZSTR_VAL(ret_buf)[ZSTR_LEN(ret_buf)] = '\0';
  948. return ret_buf;
  949. }
  950. /* Writes a buffer directly to a stream, using multiple of the chunk size */
  951. static ssize_t _php_stream_write_buffer(php_stream *stream, const char *buf, size_t count)
  952. {
  953. ssize_t didwrite = 0;
  954. /* if we have a seekable stream we need to ensure that data is written at the
  955. * current stream->position. This means invalidating the read buffer and then
  956. * performing a low-level seek */
  957. if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && stream->readpos != stream->writepos) {
  958. stream->readpos = stream->writepos = 0;
  959. stream->ops->seek(stream, stream->position, SEEK_SET, &stream->position);
  960. }
  961. while (count > 0) {
  962. ssize_t justwrote = stream->ops->write(stream, buf, count);
  963. if (justwrote <= 0) {
  964. /* If we already successfully wrote some bytes and a write error occurred
  965. * later, report the successfully written bytes. */
  966. if (didwrite == 0) {
  967. return justwrote;
  968. }
  969. return didwrite;
  970. }
  971. buf += justwrote;
  972. count -= justwrote;
  973. didwrite += justwrote;
  974. stream->position += justwrote;
  975. }
  976. return didwrite;
  977. }
  978. /* push some data through the write filter chain.
  979. * buf may be NULL, if flags are set to indicate a flush.
  980. * This may trigger a real write to the stream.
  981. * Returns the number of bytes consumed from buf by the first filter in the chain.
  982. * */
  983. static ssize_t _php_stream_write_filtered(php_stream *stream, const char *buf, size_t count, int flags)
  984. {
  985. size_t consumed = 0;
  986. php_stream_bucket *bucket;
  987. php_stream_bucket_brigade brig_in = { NULL, NULL }, brig_out = { NULL, NULL };
  988. php_stream_bucket_brigade *brig_inp = &brig_in, *brig_outp = &brig_out, *brig_swap;
  989. php_stream_filter_status_t status = PSFS_ERR_FATAL;
  990. php_stream_filter *filter;
  991. if (buf) {
  992. bucket = php_stream_bucket_new(stream, (char *)buf, count, 0, 0);
  993. php_stream_bucket_append(&brig_in, bucket);
  994. }
  995. for (filter = stream->writefilters.head; filter; filter = filter->next) {
  996. /* for our return value, we are interested in the number of bytes consumed from
  997. * the first filter in the chain */
  998. status = filter->fops->filter(stream, filter, brig_inp, brig_outp,
  999. filter == stream->writefilters.head ? &consumed : NULL, flags);
  1000. if (status != PSFS_PASS_ON) {
  1001. break;
  1002. }
  1003. /* brig_out becomes brig_in.
  1004. * brig_in will always be empty here, as the filter MUST attach any un-consumed buckets
  1005. * to its own brigade */
  1006. brig_swap = brig_inp;
  1007. brig_inp = brig_outp;
  1008. brig_outp = brig_swap;
  1009. memset(brig_outp, 0, sizeof(*brig_outp));
  1010. }
  1011. switch (status) {
  1012. case PSFS_PASS_ON:
  1013. /* filter chain generated some output; push it through to the
  1014. * underlying stream */
  1015. while (brig_inp->head) {
  1016. bucket = brig_inp->head;
  1017. if (_php_stream_write_buffer(stream, bucket->buf, bucket->buflen) < 0) {
  1018. consumed = (ssize_t) -1;
  1019. }
  1020. /* Potential error situation - eg: no space on device. Perhaps we should keep this brigade
  1021. * hanging around and try to write it later.
  1022. * At the moment, we just drop it on the floor
  1023. * */
  1024. php_stream_bucket_unlink(bucket);
  1025. php_stream_bucket_delref(bucket);
  1026. }
  1027. break;
  1028. case PSFS_FEED_ME:
  1029. /* need more data before we can push data through to the stream */
  1030. break;
  1031. case PSFS_ERR_FATAL:
  1032. /* some fatal error. Theoretically, the stream is borked, so all
  1033. * further writes should fail. */
  1034. return (ssize_t) -1;
  1035. }
  1036. return consumed;
  1037. }
  1038. PHPAPI int _php_stream_flush(php_stream *stream, int closing)
  1039. {
  1040. int ret = 0;
  1041. if (stream->writefilters.head) {
  1042. _php_stream_write_filtered(stream, NULL, 0, closing ? PSFS_FLAG_FLUSH_CLOSE : PSFS_FLAG_FLUSH_INC );
  1043. }
  1044. stream->flags &= ~PHP_STREAM_FLAG_WAS_WRITTEN;
  1045. if (stream->ops->flush) {
  1046. ret = stream->ops->flush(stream);
  1047. }
  1048. return ret;
  1049. }
  1050. PHPAPI ssize_t _php_stream_write(php_stream *stream, const char *buf, size_t count)
  1051. {
  1052. ssize_t bytes;
  1053. if (count == 0) {
  1054. return 0;
  1055. }
  1056. ZEND_ASSERT(buf != NULL);
  1057. if (stream->ops->write == NULL) {
  1058. php_error_docref(NULL, E_NOTICE, "Stream is not writable");
  1059. return (ssize_t) -1;
  1060. }
  1061. if (stream->writefilters.head) {
  1062. bytes = _php_stream_write_filtered(stream, buf, count, PSFS_FLAG_NORMAL);
  1063. } else {
  1064. bytes = _php_stream_write_buffer(stream, buf, count);
  1065. }
  1066. if (bytes) {
  1067. stream->flags |= PHP_STREAM_FLAG_WAS_WRITTEN;
  1068. }
  1069. return bytes;
  1070. }
  1071. PHPAPI ssize_t _php_stream_printf(php_stream *stream, const char *fmt, ...)
  1072. {
  1073. ssize_t count;
  1074. char *buf;
  1075. va_list ap;
  1076. va_start(ap, fmt);
  1077. count = vspprintf(&buf, 0, fmt, ap);
  1078. va_end(ap);
  1079. if (!buf) {
  1080. return -1; /* error condition */
  1081. }
  1082. count = php_stream_write(stream, buf, count);
  1083. efree(buf);
  1084. return count;
  1085. }
  1086. PHPAPI zend_off_t _php_stream_tell(php_stream *stream)
  1087. {
  1088. return stream->position;
  1089. }
  1090. PHPAPI int _php_stream_seek(php_stream *stream, zend_off_t offset, int whence)
  1091. {
  1092. if (stream->fclose_stdiocast == PHP_STREAM_FCLOSE_FOPENCOOKIE) {
  1093. /* flush to commit data written to the fopencookie FILE* */
  1094. fflush(stream->stdiocast);
  1095. }
  1096. /* handle the case where we are in the buffer */
  1097. if ((stream->flags & PHP_STREAM_FLAG_NO_BUFFER) == 0) {
  1098. switch(whence) {
  1099. case SEEK_CUR:
  1100. if (offset > 0 && offset <= stream->writepos - stream->readpos) {
  1101. stream->readpos += offset; /* if offset = ..., then readpos = writepos */
  1102. stream->position += offset;
  1103. stream->eof = 0;
  1104. return 0;
  1105. }
  1106. break;
  1107. case SEEK_SET:
  1108. if (offset > stream->position &&
  1109. offset <= stream->position + stream->writepos - stream->readpos) {
  1110. stream->readpos += offset - stream->position;
  1111. stream->position = offset;
  1112. stream->eof = 0;
  1113. return 0;
  1114. }
  1115. break;
  1116. }
  1117. }
  1118. if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) {
  1119. int ret;
  1120. if (stream->writefilters.head) {
  1121. _php_stream_flush(stream, 0);
  1122. }
  1123. switch(whence) {
  1124. case SEEK_CUR:
  1125. offset = stream->position + offset;
  1126. whence = SEEK_SET;
  1127. break;
  1128. }
  1129. ret = stream->ops->seek(stream, offset, whence, &stream->position);
  1130. if (((stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) || ret == 0) {
  1131. if (ret == 0) {
  1132. stream->eof = 0;
  1133. }
  1134. /* invalidate the buffer contents */
  1135. stream->readpos = stream->writepos = 0;
  1136. return ret;
  1137. }
  1138. /* else the stream has decided that it can't support seeking after all;
  1139. * fall through to attempt emulation */
  1140. }
  1141. /* emulate forward moving seeks with reads */
  1142. if (whence == SEEK_CUR && offset >= 0) {
  1143. char tmp[1024];
  1144. ssize_t didread;
  1145. while (offset > 0) {
  1146. if ((didread = php_stream_read(stream, tmp, MIN(offset, sizeof(tmp)))) <= 0) {
  1147. return -1;
  1148. }
  1149. offset -= didread;
  1150. }
  1151. stream->eof = 0;
  1152. return 0;
  1153. }
  1154. php_error_docref(NULL, E_WARNING, "Stream does not support seeking");
  1155. return -1;
  1156. }
  1157. PHPAPI int _php_stream_set_option(php_stream *stream, int option, int value, void *ptrparam)
  1158. {
  1159. int ret = PHP_STREAM_OPTION_RETURN_NOTIMPL;
  1160. if (stream->ops->set_option) {
  1161. ret = stream->ops->set_option(stream, option, value, ptrparam);
  1162. }
  1163. if (ret == PHP_STREAM_OPTION_RETURN_NOTIMPL) {
  1164. switch(option) {
  1165. case PHP_STREAM_OPTION_SET_CHUNK_SIZE:
  1166. /* XXX chunk size itself is of size_t, that might be ok or not for a particular case*/
  1167. ret = stream->chunk_size > INT_MAX ? INT_MAX : (int)stream->chunk_size;
  1168. stream->chunk_size = value;
  1169. return ret;
  1170. case PHP_STREAM_OPTION_READ_BUFFER:
  1171. /* try to match the buffer mode as best we can */
  1172. if (value == PHP_STREAM_BUFFER_NONE) {
  1173. stream->flags |= PHP_STREAM_FLAG_NO_BUFFER;
  1174. } else if (stream->flags & PHP_STREAM_FLAG_NO_BUFFER) {
  1175. stream->flags ^= PHP_STREAM_FLAG_NO_BUFFER;
  1176. }
  1177. ret = PHP_STREAM_OPTION_RETURN_OK;
  1178. break;
  1179. default:
  1180. ;
  1181. }
  1182. }
  1183. return ret;
  1184. }
  1185. PHPAPI int _php_stream_sync(php_stream *stream, bool data_only)
  1186. {
  1187. int op = PHP_STREAM_SYNC_FSYNC;
  1188. if (data_only) {
  1189. op = PHP_STREAM_SYNC_FDSYNC;
  1190. }
  1191. return php_stream_set_option(stream, PHP_STREAM_OPTION_SYNC_API, op, NULL);
  1192. }
  1193. PHPAPI int _php_stream_truncate_set_size(php_stream *stream, size_t newsize)
  1194. {
  1195. return php_stream_set_option(stream, PHP_STREAM_OPTION_TRUNCATE_API, PHP_STREAM_TRUNCATE_SET_SIZE, &newsize);
  1196. }
  1197. PHPAPI ssize_t _php_stream_passthru(php_stream * stream STREAMS_DC)
  1198. {
  1199. size_t bcount = 0;
  1200. char buf[8192];
  1201. ssize_t b;
  1202. if (php_stream_mmap_possible(stream)) {
  1203. char *p;
  1204. size_t mapped;
  1205. p = php_stream_mmap_range(stream, php_stream_tell(stream), PHP_STREAM_MMAP_ALL, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped);
  1206. if (p) {
  1207. do {
  1208. /* output functions return int, so pass in int max */
  1209. if (0 < (b = PHPWRITE(p + bcount, MIN(mapped - bcount, INT_MAX)))) {
  1210. bcount += b;
  1211. }
  1212. } while (b > 0 && mapped > bcount);
  1213. php_stream_mmap_unmap_ex(stream, mapped);
  1214. return bcount;
  1215. }
  1216. }
  1217. while ((b = php_stream_read(stream, buf, sizeof(buf))) > 0) {
  1218. PHPWRITE(buf, b);
  1219. bcount += b;
  1220. }
  1221. if (b < 0 && bcount == 0) {
  1222. return b;
  1223. }
  1224. return bcount;
  1225. }
  1226. PHPAPI zend_string *_php_stream_copy_to_mem(php_stream *src, size_t maxlen, int persistent STREAMS_DC)
  1227. {
  1228. ssize_t ret = 0;
  1229. char *ptr;
  1230. size_t len = 0, max_len;
  1231. int step = CHUNK_SIZE;
  1232. int min_room = CHUNK_SIZE / 4;
  1233. php_stream_statbuf ssbuf;
  1234. zend_string *result;
  1235. if (maxlen == 0) {
  1236. return ZSTR_EMPTY_ALLOC();
  1237. }
  1238. if (maxlen == PHP_STREAM_COPY_ALL) {
  1239. maxlen = 0;
  1240. }
  1241. if (maxlen > 0) {
  1242. result = zend_string_alloc(maxlen, persistent);
  1243. ptr = ZSTR_VAL(result);
  1244. while ((len < maxlen) && !php_stream_eof(src)) {
  1245. ret = php_stream_read(src, ptr, maxlen - len);
  1246. if (ret <= 0) {
  1247. // TODO: Propagate error?
  1248. break;
  1249. }
  1250. len += ret;
  1251. ptr += ret;
  1252. }
  1253. if (len) {
  1254. ZSTR_LEN(result) = len;
  1255. ZSTR_VAL(result)[len] = '\0';
  1256. /* Only truncate if the savings are large enough */
  1257. if (len < maxlen / 2) {
  1258. result = zend_string_truncate(result, len, persistent);
  1259. }
  1260. } else {
  1261. zend_string_free(result);
  1262. result = NULL;
  1263. }
  1264. return result;
  1265. }
  1266. /* avoid many reallocs by allocating a good sized chunk to begin with, if
  1267. * we can. Note that the stream may be filtered, in which case the stat
  1268. * result may be inaccurate, as the filter may inflate or deflate the
  1269. * number of bytes that we can read. In order to avoid an upsize followed
  1270. * by a downsize of the buffer, overestimate by the step size (which is
  1271. * 8K). */
  1272. if (php_stream_stat(src, &ssbuf) == 0 && ssbuf.sb.st_size > 0) {
  1273. max_len = MAX(ssbuf.sb.st_size - src->position, 0) + step;
  1274. } else {
  1275. max_len = step;
  1276. }
  1277. result = zend_string_alloc(max_len, persistent);
  1278. ptr = ZSTR_VAL(result);
  1279. // TODO: Propagate error?
  1280. while ((ret = php_stream_read(src, ptr, max_len - len)) > 0){
  1281. len += ret;
  1282. if (len + min_room >= max_len) {
  1283. result = zend_string_extend(result, max_len + step, persistent);
  1284. max_len += step;
  1285. ptr = ZSTR_VAL(result) + len;
  1286. } else {
  1287. ptr += ret;
  1288. }
  1289. }
  1290. if (len) {
  1291. result = zend_string_truncate(result, len, persistent);
  1292. ZSTR_VAL(result)[len] = '\0';
  1293. } else {
  1294. zend_string_free(result);
  1295. result = NULL;
  1296. }
  1297. return result;
  1298. }
  1299. /* Returns SUCCESS/FAILURE and sets *len to the number of bytes moved */
  1300. PHPAPI int _php_stream_copy_to_stream_ex(php_stream *src, php_stream *dest, size_t maxlen, size_t *len STREAMS_DC)
  1301. {
  1302. char buf[CHUNK_SIZE];
  1303. size_t haveread = 0;
  1304. size_t towrite;
  1305. size_t dummy;
  1306. if (!len) {
  1307. len = &dummy;
  1308. }
  1309. if (maxlen == 0) {
  1310. *len = 0;
  1311. return SUCCESS;
  1312. }
  1313. if (maxlen == PHP_STREAM_COPY_ALL) {
  1314. maxlen = 0;
  1315. }
  1316. if (php_stream_mmap_possible(src)) {
  1317. char *p;
  1318. do {
  1319. size_t chunk_size = (maxlen == 0 || maxlen > PHP_STREAM_MMAP_MAX) ? PHP_STREAM_MMAP_MAX : maxlen;
  1320. size_t mapped;
  1321. p = php_stream_mmap_range(src, php_stream_tell(src), chunk_size, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped);
  1322. if (p) {
  1323. ssize_t didwrite;
  1324. if (php_stream_seek(src, mapped, SEEK_CUR) != 0) {
  1325. php_stream_mmap_unmap(src);
  1326. break;
  1327. }
  1328. didwrite = php_stream_write(dest, p, mapped);
  1329. if (didwrite < 0) {
  1330. *len = haveread;
  1331. return FAILURE;
  1332. }
  1333. php_stream_mmap_unmap(src);
  1334. *len = haveread += didwrite;
  1335. /* we've got at least 1 byte to read
  1336. * less than 1 is an error
  1337. * AND read bytes match written */
  1338. if (mapped == 0 || mapped != didwrite) {
  1339. return FAILURE;
  1340. }
  1341. if (mapped < chunk_size) {
  1342. return SUCCESS;
  1343. }
  1344. if (maxlen != 0) {
  1345. maxlen -= mapped;
  1346. if (maxlen == 0) {
  1347. return SUCCESS;
  1348. }
  1349. }
  1350. }
  1351. } while (p);
  1352. }
  1353. while(1) {
  1354. size_t readchunk = sizeof(buf);
  1355. ssize_t didread;
  1356. char *writeptr;
  1357. if (maxlen && (maxlen - haveread) < readchunk) {
  1358. readchunk = maxlen - haveread;
  1359. }
  1360. didread = php_stream_read(src, buf, readchunk);
  1361. if (didread <= 0) {
  1362. *len = haveread;
  1363. return didread < 0 ? FAILURE : SUCCESS;
  1364. }
  1365. towrite = didread;
  1366. writeptr = buf;
  1367. haveread += didread;
  1368. while (towrite) {
  1369. ssize_t didwrite = php_stream_write(dest, writeptr, towrite);
  1370. if (didwrite <= 0) {
  1371. *len = haveread - (didread - towrite);
  1372. return FAILURE;
  1373. }
  1374. towrite -= didwrite;
  1375. writeptr += didwrite;
  1376. }
  1377. if (maxlen && maxlen == haveread) {
  1378. break;
  1379. }
  1380. }
  1381. *len = haveread;
  1382. return SUCCESS;
  1383. }
  1384. /* Returns the number of bytes moved.
  1385. * Returns 1 when source len is 0.
  1386. * Deprecated in favor of php_stream_copy_to_stream_ex() */
  1387. ZEND_ATTRIBUTE_DEPRECATED
  1388. PHPAPI size_t _php_stream_copy_to_stream(php_stream *src, php_stream *dest, size_t maxlen STREAMS_DC)
  1389. {
  1390. size_t len;
  1391. int ret = _php_stream_copy_to_stream_ex(src, dest, maxlen, &len STREAMS_REL_CC);
  1392. if (ret == SUCCESS && len == 0 && maxlen != 0) {
  1393. return 1;
  1394. }
  1395. return len;
  1396. }
  1397. /* }}} */
  1398. /* {{{ wrapper init and registration */
  1399. static void stream_resource_regular_dtor(zend_resource *rsrc)
  1400. {
  1401. php_stream *stream = (php_stream*)rsrc->ptr;
  1402. /* set the return value for pclose */
  1403. FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR);
  1404. }
  1405. static void stream_resource_persistent_dtor(zend_resource *rsrc)
  1406. {
  1407. php_stream *stream = (php_stream*)rsrc->ptr;
  1408. FG(pclose_ret) = php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_RSRC_DTOR);
  1409. }
  1410. void php_shutdown_stream_hashes(void)
  1411. {
  1412. FG(user_stream_current_filename) = NULL;
  1413. if (FG(stream_wrappers)) {
  1414. zend_hash_destroy(FG(stream_wrappers));
  1415. efree(FG(stream_wrappers));
  1416. FG(stream_wrappers) = NULL;
  1417. }
  1418. if (FG(stream_filters)) {
  1419. zend_hash_destroy(FG(stream_filters));
  1420. efree(FG(stream_filters));
  1421. FG(stream_filters) = NULL;
  1422. }
  1423. if (FG(wrapper_errors)) {
  1424. zend_hash_destroy(FG(wrapper_errors));
  1425. efree(FG(wrapper_errors));
  1426. FG(wrapper_errors) = NULL;
  1427. }
  1428. }
  1429. int php_init_stream_wrappers(int module_number)
  1430. {
  1431. le_stream = zend_register_list_destructors_ex(stream_resource_regular_dtor, NULL, "stream", module_number);
  1432. le_pstream = zend_register_list_destructors_ex(NULL, stream_resource_persistent_dtor, "persistent stream", module_number);
  1433. /* Filters are cleaned up by the streams they're attached to */
  1434. le_stream_filter = zend_register_list_destructors_ex(NULL, NULL, "stream filter", module_number);
  1435. zend_hash_init(&url_stream_wrappers_hash, 8, NULL, NULL, 1);
  1436. zend_hash_init(php_get_stream_filters_hash_global(), 8, NULL, NULL, 1);
  1437. zend_hash_init(php_stream_xport_get_hash(), 8, NULL, NULL, 1);
  1438. return (php_stream_xport_register("tcp", php_stream_generic_socket_factory) == SUCCESS
  1439. &&
  1440. php_stream_xport_register("udp", php_stream_generic_socket_factory) == SUCCESS
  1441. #if defined(AF_UNIX) && !(defined(PHP_WIN32) || defined(__riscos__))
  1442. &&
  1443. php_stream_xport_register("unix", php_stream_generic_socket_factory) == SUCCESS
  1444. &&
  1445. php_stream_xport_register("udg", php_stream_generic_socket_factory) == SUCCESS
  1446. #endif
  1447. ) ? SUCCESS : FAILURE;
  1448. }
  1449. int php_shutdown_stream_wrappers(int module_number)
  1450. {
  1451. zend_hash_destroy(&url_stream_wrappers_hash);
  1452. zend_hash_destroy(php_get_stream_filters_hash_global());
  1453. zend_hash_destroy(php_stream_xport_get_hash());
  1454. return SUCCESS;
  1455. }
  1456. /* Validate protocol scheme names during registration
  1457. * Must conform to /^[a-zA-Z0-9+.-]+$/
  1458. */
  1459. static inline int php_stream_wrapper_scheme_validate(const char *protocol, unsigned int protocol_len)
  1460. {
  1461. unsigned int i;
  1462. for(i = 0; i < protocol_len; i++) {
  1463. if (!isalnum((int)protocol[i]) &&
  1464. protocol[i] != '+' &&
  1465. protocol[i] != '-' &&
  1466. protocol[i] != '.') {
  1467. return FAILURE;
  1468. }
  1469. }
  1470. return SUCCESS;
  1471. }
  1472. /* API for registering GLOBAL wrappers */
  1473. PHPAPI int php_register_url_stream_wrapper(const char *protocol, const php_stream_wrapper *wrapper)
  1474. {
  1475. unsigned int protocol_len = (unsigned int)strlen(protocol);
  1476. int ret;
  1477. zend_string *str;
  1478. if (php_stream_wrapper_scheme_validate(protocol, protocol_len) == FAILURE) {
  1479. return FAILURE;
  1480. }
  1481. str = zend_string_init_interned(protocol, protocol_len, 1);
  1482. ret = zend_hash_add_ptr(&url_stream_wrappers_hash, str, (void*)wrapper) ? SUCCESS : FAILURE;
  1483. zend_string_release_ex(str, 1);
  1484. return ret;
  1485. }
  1486. PHPAPI int php_unregister_url_stream_wrapper(const char *protocol)
  1487. {
  1488. return zend_hash_str_del(&url_stream_wrappers_hash, protocol, strlen(protocol));
  1489. }
  1490. static void clone_wrapper_hash(void)
  1491. {
  1492. ALLOC_HASHTABLE(FG(stream_wrappers));
  1493. zend_hash_init(FG(stream_wrappers), zend_hash_num_elements(&url_stream_wrappers_hash), NULL, NULL, 0);
  1494. zend_hash_copy(FG(stream_wrappers), &url_stream_wrappers_hash, NULL);
  1495. }
  1496. /* API for registering VOLATILE wrappers */
  1497. PHPAPI int php_register_url_stream_wrapper_volatile(zend_string *protocol, php_stream_wrapper *wrapper)
  1498. {
  1499. if (php_stream_wrapper_scheme_validate(ZSTR_VAL(protocol), ZSTR_LEN(protocol)) == FAILURE) {
  1500. return FAILURE;
  1501. }
  1502. if (!FG(stream_wrappers)) {
  1503. clone_wrapper_hash();
  1504. }
  1505. return zend_hash_add_ptr(FG(stream_wrappers), protocol, wrapper) ? SUCCESS : FAILURE;
  1506. }
  1507. PHPAPI int php_unregister_url_stream_wrapper_volatile(zend_string *protocol)
  1508. {
  1509. if (!FG(stream_wrappers)) {
  1510. clone_wrapper_hash();
  1511. }
  1512. return zend_hash_del(FG(stream_wrappers), protocol);
  1513. }
  1514. /* }}} */
  1515. /* {{{ php_stream_locate_url_wrapper */
  1516. PHPAPI php_stream_wrapper *php_stream_locate_url_wrapper(const char *path, const char **path_for_open, int options)
  1517. {
  1518. HashTable *wrapper_hash = (FG(stream_wrappers) ? FG(stream_wrappers) : &url_stream_wrappers_hash);
  1519. php_stream_wrapper *wrapper = NULL;
  1520. const char *p, *protocol = NULL;
  1521. size_t n = 0;
  1522. if (path_for_open) {
  1523. *path_for_open = (char*)path;
  1524. }
  1525. if (options & IGNORE_URL) {
  1526. return (php_stream_wrapper*)((options & STREAM_LOCATE_WRAPPERS_ONLY) ? NULL : &php_plain_files_wrapper);
  1527. }
  1528. for (p = path; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++) {
  1529. n++;
  1530. }
  1531. if ((*p == ':') && (n > 1) && (!strncmp("//", p+1, 2) || (n == 4 && !memcmp("data:", path, 5)))) {
  1532. protocol = path;
  1533. }
  1534. if (protocol) {
  1535. if (NULL == (wrapper = zend_hash_str_find_ptr(wrapper_hash, protocol, n))) {
  1536. char *tmp = estrndup(protocol, n);
  1537. zend_str_tolower(tmp, n);
  1538. if (NULL == (wrapper = zend_hash_str_find_ptr(wrapper_hash, tmp, n))) {
  1539. char wrapper_name[32];
  1540. if (n >= sizeof(wrapper_name)) {
  1541. n = sizeof(wrapper_name) - 1;
  1542. }
  1543. PHP_STRLCPY(wrapper_name, protocol, sizeof(wrapper_name), n);
  1544. php_error_docref(NULL, E_WARNING, "Unable to find the wrapper \"%s\" - did you forget to enable it when you configured PHP?", wrapper_name);
  1545. wrapper = NULL;
  1546. protocol = NULL;
  1547. }
  1548. efree(tmp);
  1549. }
  1550. }
  1551. /* TODO: curl based streams probably support file:// properly */
  1552. if (!protocol || !strncasecmp(protocol, "file", n)) {
  1553. /* fall back on regular file access */
  1554. php_stream_wrapper *plain_files_wrapper = (php_stream_wrapper*)&php_plain_files_wrapper;
  1555. if (protocol) {
  1556. int localhost = 0;
  1557. if (!strncasecmp(path, "file://localhost/", 17)) {
  1558. localhost = 1;
  1559. }
  1560. #ifdef PHP_WIN32
  1561. if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/' && path[n+4] != ':') {
  1562. #else
  1563. if (localhost == 0 && path[n+3] != '\0' && path[n+3] != '/') {
  1564. #endif
  1565. if (options & REPORT_ERRORS) {
  1566. php_error_docref(NULL, E_WARNING, "Remote host file access not supported, %s", path);
  1567. }
  1568. return NULL;
  1569. }
  1570. if (path_for_open) {
  1571. /* skip past protocol and :/, but handle windows correctly */
  1572. *path_for_open = (char*)path + n + 1;
  1573. if (localhost == 1) {
  1574. (*path_for_open) += 11;
  1575. }
  1576. while (*(++*path_for_open)=='/') {
  1577. /* intentionally empty */
  1578. }
  1579. #ifdef PHP_WIN32
  1580. if (*(*path_for_open + 1) != ':')
  1581. #endif
  1582. (*path_for_open)--;
  1583. }
  1584. }
  1585. if (options & STREAM_LOCATE_WRAPPERS_ONLY) {
  1586. return NULL;
  1587. }
  1588. if (FG(stream_wrappers)) {
  1589. /* The file:// wrapper may have been disabled/overridden */
  1590. if (wrapper) {
  1591. /* It was found so go ahead and provide it */
  1592. return wrapper;
  1593. }
  1594. /* Check again, the original check might have not known the protocol name */
  1595. if ((wrapper = zend_hash_find_ex_ptr(wrapper_hash, ZSTR_KNOWN(ZEND_STR_FILE), 1)) != NULL) {
  1596. return wrapper;
  1597. }
  1598. if (options & REPORT_ERRORS) {
  1599. php_error_docref(NULL, E_WARNING, "file:// wrapper is disabled in the server configuration");
  1600. }
  1601. return NULL;
  1602. }
  1603. return plain_files_wrapper;
  1604. }
  1605. if (wrapper && wrapper->is_url &&
  1606. (options & STREAM_DISABLE_URL_PROTECTION) == 0 &&
  1607. (!PG(allow_url_fopen) ||
  1608. (((options & STREAM_OPEN_FOR_INCLUDE) ||
  1609. PG(in_user_include)) && !PG(allow_url_include)))) {
  1610. if (options & REPORT_ERRORS) {
  1611. /* protocol[n] probably isn't '\0' */
  1612. if (!PG(allow_url_fopen)) {
  1613. php_error_docref(NULL, E_WARNING, "%.*s:// wrapper is disabled in the server configuration by allow_url_fopen=0", (int)n, protocol);
  1614. } else {
  1615. php_error_docref(NULL, E_WARNING, "%.*s:// wrapper is disabled in the server configuration by allow_url_include=0", (int)n, protocol);
  1616. }
  1617. }
  1618. return NULL;
  1619. }
  1620. return wrapper;
  1621. }
  1622. /* }}} */
  1623. /* {{{ _php_stream_mkdir */
  1624. PHPAPI int _php_stream_mkdir(const char *path, int mode, int options, php_stream_context *context)
  1625. {
  1626. php_stream_wrapper *wrapper = NULL;
  1627. wrapper = php_stream_locate_url_wrapper(path, NULL, 0);
  1628. if (!wrapper || !wrapper->wops || !wrapper->wops->stream_mkdir) {
  1629. return 0;
  1630. }
  1631. return wrapper->wops->stream_mkdir(wrapper, path, mode, options, context);
  1632. }
  1633. /* }}} */
  1634. /* {{{ _php_stream_rmdir */
  1635. PHPAPI int _php_stream_rmdir(const char *path, int options, php_stream_context *context)
  1636. {
  1637. php_stream_wrapper *wrapper = NULL;
  1638. wrapper = php_stream_locate_url_wrapper(path, NULL, 0);
  1639. if (!wrapper || !wrapper->wops || !wrapper->wops->stream_rmdir) {
  1640. return 0;
  1641. }
  1642. return wrapper->wops->stream_rmdir(wrapper, path, options, context);
  1643. }
  1644. /* }}} */
  1645. /* {{{ _php_stream_stat_path */
  1646. PHPAPI int _php_stream_stat_path(const char *path, int flags, php_stream_statbuf *ssb, php_stream_context *context)
  1647. {
  1648. php_stream_wrapper *wrapper = NULL;
  1649. const char *path_to_open = path;
  1650. memset(ssb, 0, sizeof(*ssb));
  1651. wrapper = php_stream_locate_url_wrapper(path, &path_to_open, 0);
  1652. if (wrapper && wrapper->wops->url_stat) {
  1653. return wrapper->wops->url_stat(wrapper, path_to_open, flags, ssb, context);
  1654. }
  1655. return -1;
  1656. }
  1657. /* }}} */
  1658. /* {{{ php_stream_opendir */
  1659. PHPAPI php_stream *_php_stream_opendir(const char *path, int options,
  1660. php_stream_context *context STREAMS_DC)
  1661. {
  1662. php_stream *stream = NULL;
  1663. php_stream_wrapper *wrapper = NULL;
  1664. const char *path_to_open;
  1665. if (!path || !*path) {
  1666. return NULL;
  1667. }
  1668. path_to_open = path;
  1669. wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options);
  1670. if (wrapper && wrapper->wops->dir_opener) {
  1671. stream = wrapper->wops->dir_opener(wrapper,
  1672. path_to_open, "r", options & ~REPORT_ERRORS, NULL,
  1673. context STREAMS_REL_CC);
  1674. if (stream) {
  1675. stream->wrapper = wrapper;
  1676. stream->flags |= PHP_STREAM_FLAG_NO_BUFFER | PHP_STREAM_FLAG_IS_DIR;
  1677. }
  1678. } else if (wrapper) {
  1679. php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS, "not implemented");
  1680. }
  1681. if (stream == NULL && (options & REPORT_ERRORS)) {
  1682. php_stream_display_wrapper_errors(wrapper, path, "Failed to open directory");
  1683. }
  1684. php_stream_tidy_wrapper_error_log(wrapper);
  1685. return stream;
  1686. }
  1687. /* }}} */
  1688. /* {{{ _php_stream_readdir */
  1689. PHPAPI php_stream_dirent *_php_stream_readdir(php_stream *dirstream, php_stream_dirent *ent)
  1690. {
  1691. if (sizeof(php_stream_dirent) == php_stream_read(dirstream, (char*)ent, sizeof(php_stream_dirent))) {
  1692. return ent;
  1693. }
  1694. return NULL;
  1695. }
  1696. /* }}} */
  1697. /* {{{ php_stream_open_wrapper_ex */
  1698. PHPAPI php_stream *_php_stream_open_wrapper_ex(const char *path, const char *mode, int options,
  1699. zend_string **opened_path, php_stream_context *context STREAMS_DC)
  1700. {
  1701. php_stream *stream = NULL;
  1702. php_stream_wrapper *wrapper = NULL;
  1703. const char *path_to_open;
  1704. int persistent = options & STREAM_OPEN_PERSISTENT;
  1705. zend_string *path_str = NULL;
  1706. zend_string *resolved_path = NULL;
  1707. char *copy_of_path = NULL;
  1708. if (opened_path) {
  1709. if (options & STREAM_OPEN_FOR_ZEND_STREAM) {
  1710. path_str = *opened_path;
  1711. }
  1712. *opened_path = NULL;
  1713. }
  1714. if (!path || !*path) {
  1715. zend_value_error("Path cannot be empty");
  1716. return NULL;
  1717. }
  1718. if (options & USE_PATH) {
  1719. if (path_str) {
  1720. resolved_path = zend_resolve_path(path_str);
  1721. } else {
  1722. resolved_path = php_resolve_path(path, strlen(path), PG(include_path));
  1723. }
  1724. if (resolved_path) {
  1725. path = ZSTR_VAL(resolved_path);
  1726. /* we've found this file, don't re-check include_path or run realpath */
  1727. options |= STREAM_ASSUME_REALPATH;
  1728. options &= ~USE_PATH;
  1729. }
  1730. if (EG(exception)) {
  1731. return NULL;
  1732. }
  1733. }
  1734. path_to_open = path;
  1735. wrapper = php_stream_locate_url_wrapper(path, &path_to_open, options);
  1736. if ((options & STREAM_USE_URL) && (!wrapper || !wrapper->is_url)) {
  1737. php_error_docref(NULL, E_WARNING, "This function may only be used against URLs");
  1738. if (resolved_path) {
  1739. zend_string_release_ex(resolved_path, 0);
  1740. }
  1741. return NULL;
  1742. }
  1743. if (wrapper) {
  1744. if (!wrapper->wops->stream_opener) {
  1745. php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS,
  1746. "wrapper does not support stream open");
  1747. } else {
  1748. stream = wrapper->wops->stream_opener(wrapper,
  1749. path_to_open, mode, options & ~REPORT_ERRORS,
  1750. opened_path, context STREAMS_REL_CC);
  1751. }
  1752. /* if the caller asked for a persistent stream but the wrapper did not
  1753. * return one, force an error here */
  1754. if (stream && (options & STREAM_OPEN_PERSISTENT) && !stream->is_persistent) {
  1755. php_stream_wrapper_log_error(wrapper, options & ~REPORT_ERRORS,
  1756. "wrapper does not support persistent streams");
  1757. php_stream_close(stream);
  1758. stream = NULL;
  1759. }
  1760. if (stream) {
  1761. stream->wrapper = wrapper;
  1762. }
  1763. }
  1764. if (stream) {
  1765. if (opened_path && !*opened_path && resolved_path) {
  1766. *opened_path = resolved_path;
  1767. resolved_path = NULL;
  1768. }
  1769. if (stream->orig_path) {
  1770. pefree(stream->orig_path, persistent);
  1771. }
  1772. copy_of_path = pestrdup(path, persistent);
  1773. stream->orig_path = copy_of_path;
  1774. #if ZEND_DEBUG
  1775. stream->open_filename = __zend_orig_filename ? __zend_orig_filename : __zend_filename;
  1776. stream->open_lineno = __zend_orig_lineno ? __zend_orig_lineno : __zend_lineno;
  1777. #endif
  1778. }
  1779. if (stream != NULL && (options & STREAM_MUST_SEEK)) {
  1780. php_stream *newstream;
  1781. switch(php_stream_make_seekable_rel(stream, &newstream,
  1782. (options & STREAM_WILL_CAST)
  1783. ? PHP_STREAM_PREFER_STDIO : PHP_STREAM_NO_PREFERENCE)) {
  1784. case PHP_STREAM_UNCHANGED:
  1785. if (resolved_path) {
  1786. zend_string_release_ex(resolved_path, 0);
  1787. }
  1788. return stream;
  1789. case PHP_STREAM_RELEASED:
  1790. if (newstream->orig_path) {
  1791. pefree(newstream->orig_path, persistent);
  1792. }
  1793. newstream->orig_path = pestrdup(path, persistent);
  1794. if (resolved_path) {
  1795. zend_string_release_ex(resolved_path, 0);
  1796. }
  1797. return newstream;
  1798. default:
  1799. php_stream_close(stream);
  1800. stream = NULL;
  1801. if (options & REPORT_ERRORS) {
  1802. char *tmp = estrdup(path);
  1803. php_strip_url_passwd(tmp);
  1804. php_error_docref1(NULL, tmp, E_WARNING, "could not make seekable - %s",
  1805. tmp);
  1806. efree(tmp);
  1807. options &= ~REPORT_ERRORS;
  1808. }
  1809. }
  1810. }
  1811. if (stream && stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && strchr(mode, 'a') && stream->position == 0) {
  1812. zend_off_t newpos = 0;
  1813. /* if opened for append, we need to revise our idea of the initial file position */
  1814. if (0 == stream->ops->seek(stream, 0, SEEK_CUR, &newpos)) {
  1815. stream->position = newpos;
  1816. }
  1817. }
  1818. if (stream == NULL && (options & REPORT_ERRORS)) {
  1819. php_stream_display_wrapper_errors(wrapper, path, "Failed to open stream");
  1820. if (opened_path && *opened_path) {
  1821. zend_string_release_ex(*opened_path, 0);
  1822. *opened_path = NULL;
  1823. }
  1824. }
  1825. php_stream_tidy_wrapper_error_log(wrapper);
  1826. #if ZEND_DEBUG
  1827. if (stream == NULL && copy_of_path != NULL) {
  1828. pefree(copy_of_path, persistent);
  1829. }
  1830. #endif
  1831. if (resolved_path) {
  1832. zend_string_release_ex(resolved_path, 0);
  1833. }
  1834. return stream;
  1835. }
  1836. /* }}} */
  1837. /* {{{ context API */
  1838. PHPAPI php_stream_context *php_stream_context_set(php_stream *stream, php_stream_context *context)
  1839. {
  1840. php_stream_context *oldcontext = PHP_STREAM_CONTEXT(stream);
  1841. if (context) {
  1842. stream->ctx = context->res;
  1843. GC_ADDREF(context->res);
  1844. } else {
  1845. stream->ctx = NULL;
  1846. }
  1847. if (oldcontext) {
  1848. zend_list_delete(oldcontext->res);
  1849. }
  1850. return oldcontext;
  1851. }
  1852. PHPAPI void php_stream_notification_notify(php_stream_context *context, int notifycode, int severity,
  1853. char *xmsg, int xcode, size_t bytes_sofar, size_t bytes_max, void * ptr)
  1854. {
  1855. if (context && context->notifier)
  1856. context->notifier->func(context, notifycode, severity, xmsg, xcode, bytes_sofar, bytes_max, ptr);
  1857. }
  1858. PHPAPI void php_stream_context_free(php_stream_context *context)
  1859. {
  1860. if (Z_TYPE(context->options) != IS_UNDEF) {
  1861. zval_ptr_dtor(&context->options);
  1862. ZVAL_UNDEF(&context->options);
  1863. }
  1864. if (context->notifier) {
  1865. php_stream_notification_free(context->notifier);
  1866. context->notifier = NULL;
  1867. }
  1868. efree(context);
  1869. }
  1870. PHPAPI php_stream_context *php_stream_context_alloc(void)
  1871. {
  1872. php_stream_context *context;
  1873. context = ecalloc(1, sizeof(php_stream_context));
  1874. context->notifier = NULL;
  1875. array_init(&context->options);
  1876. context->res = zend_register_resource(context, php_le_stream_context());
  1877. return context;
  1878. }
  1879. PHPAPI php_stream_notifier *php_stream_notification_alloc(void)
  1880. {
  1881. return ecalloc(1, sizeof(php_stream_notifier));
  1882. }
  1883. PHPAPI void php_stream_notification_free(php_stream_notifier *notifier)
  1884. {
  1885. if (notifier->dtor) {
  1886. notifier->dtor(notifier);
  1887. }
  1888. efree(notifier);
  1889. }
  1890. PHPAPI zval *php_stream_context_get_option(php_stream_context *context,
  1891. const char *wrappername, const char *optionname)
  1892. {
  1893. zval *wrapperhash;
  1894. if (NULL == (wrapperhash = zend_hash_str_find(Z_ARRVAL(context->options), wrappername, strlen(wrappername)))) {
  1895. return NULL;
  1896. }
  1897. return zend_hash_str_find(Z_ARRVAL_P(wrapperhash), optionname, strlen(optionname));
  1898. }
  1899. PHPAPI int php_stream_context_set_option(php_stream_context *context,
  1900. const char *wrappername, const char *optionname, zval *optionvalue)
  1901. {
  1902. zval *wrapperhash;
  1903. zval category;
  1904. SEPARATE_ARRAY(&context->options);
  1905. wrapperhash = zend_hash_str_find(Z_ARRVAL(context->options), wrappername, strlen(wrappername));
  1906. if (NULL == wrapperhash) {
  1907. array_init(&category);
  1908. wrapperhash = zend_hash_str_update(Z_ARRVAL(context->options), (char*)wrappername, strlen(wrappername), &category);
  1909. }
  1910. ZVAL_DEREF(optionvalue);
  1911. Z_TRY_ADDREF_P(optionvalue);
  1912. SEPARATE_ARRAY(wrapperhash);
  1913. zend_hash_str_update(Z_ARRVAL_P(wrapperhash), optionname, strlen(optionname), optionvalue);
  1914. return SUCCESS;
  1915. }
  1916. /* }}} */
  1917. /* {{{ php_stream_dirent_alphasort */
  1918. PHPAPI int php_stream_dirent_alphasort(const zend_string **a, const zend_string **b)
  1919. {
  1920. return strcoll(ZSTR_VAL(*a), ZSTR_VAL(*b));
  1921. }
  1922. /* }}} */
  1923. /* {{{ php_stream_dirent_alphasortr */
  1924. PHPAPI int php_stream_dirent_alphasortr(const zend_string **a, const zend_string **b)
  1925. {
  1926. return strcoll(ZSTR_VAL(*b), ZSTR_VAL(*a));
  1927. }
  1928. /* }}} */
  1929. /* {{{ php_stream_scandir */
  1930. PHPAPI int _php_stream_scandir(const char *dirname, zend_string **namelist[], int flags, php_stream_context *context,
  1931. int (*compare) (const zend_string **a, const zend_string **b))
  1932. {
  1933. php_stream *stream;
  1934. php_stream_dirent sdp;
  1935. zend_string **vector = NULL;
  1936. unsigned int vector_size = 0;
  1937. unsigned int nfiles = 0;
  1938. if (!namelist) {
  1939. return FAILURE;
  1940. }
  1941. stream = php_stream_opendir(dirname, REPORT_ERRORS, context);
  1942. if (!stream) {
  1943. return FAILURE;
  1944. }
  1945. while (php_stream_readdir(stream, &sdp)) {
  1946. if (nfiles == vector_size) {
  1947. if (vector_size == 0) {
  1948. vector_size = 10;
  1949. } else {
  1950. if(vector_size*2 < vector_size) {
  1951. /* overflow */
  1952. php_stream_closedir(stream);
  1953. efree(vector);
  1954. return FAILURE;
  1955. }
  1956. vector_size *= 2;
  1957. }
  1958. vector = (zend_string **) safe_erealloc(vector, vector_size, sizeof(char *), 0);
  1959. }
  1960. vector[nfiles] = zend_string_init(sdp.d_name, strlen(sdp.d_name), 0);
  1961. nfiles++;
  1962. if(vector_size < 10 || nfiles == 0) {
  1963. /* overflow */
  1964. php_stream_closedir(stream);
  1965. efree(vector);
  1966. return FAILURE;
  1967. }
  1968. }
  1969. php_stream_closedir(stream);
  1970. *namelist = vector;
  1971. if (nfiles > 0 && compare) {
  1972. qsort(*namelist, nfiles, sizeof(zend_string *), (int(*)(const void *, const void *))compare);
  1973. }
  1974. return nfiles;
  1975. }
  1976. /* }}} */