streams.c 64 KB

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