xref: /PHP-7.4/main/streams/cast.c (revision 23e13e2c)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 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    +----------------------------------------------------------------------+
17  */
18 
19 #define _GNU_SOURCE
20 #include "php.h"
21 #include "php_globals.h"
22 #include "php_network.h"
23 #include "php_open_temporary_file.h"
24 #include "ext/standard/file.h"
25 #include <stddef.h>
26 #include <fcntl.h>
27 
28 #include "php_streams_int.h"
29 
30 /* Under BSD, emulate fopencookie using funopen */
31 #if defined(HAVE_FUNOPEN) && !defined(HAVE_FOPENCOOKIE)
32 
33 /* NetBSD 6.0+ uses off_t instead of fpos_t in funopen */
34 # if defined(__NetBSD__) && (__NetBSD_Version__ >= 600000000)
35 #  define PHP_FPOS_T off_t
36 # else
37 #  define PHP_FPOS_T fpos_t
38 # endif
39 
40 typedef struct {
41 	int (*reader)(void *, char *, int);
42 	int (*writer)(void *, const char *, int);
43 	PHP_FPOS_T (*seeker)(void *, PHP_FPOS_T, int);
44 	int (*closer)(void *);
45 } COOKIE_IO_FUNCTIONS_T;
46 
fopencookie(void * cookie,const char * mode,COOKIE_IO_FUNCTIONS_T * funcs)47 FILE *fopencookie(void *cookie, const char *mode, COOKIE_IO_FUNCTIONS_T *funcs)
48 {
49 	return funopen(cookie, funcs->reader, funcs->writer, funcs->seeker, funcs->closer);
50 }
51 # define HAVE_FOPENCOOKIE 1
52 # define PHP_EMULATE_FOPENCOOKIE 1
53 # define PHP_STREAM_COOKIE_FUNCTIONS	&stream_cookie_functions
54 #elif defined(HAVE_FOPENCOOKIE)
55 # define PHP_STREAM_COOKIE_FUNCTIONS	stream_cookie_functions
56 #endif
57 
58 /* {{{ STDIO with fopencookie */
59 #if defined(PHP_EMULATE_FOPENCOOKIE)
60 /* use our fopencookie emulation */
stream_cookie_reader(void * cookie,char * buffer,int size)61 static int stream_cookie_reader(void *cookie, char *buffer, int size)
62 {
63 	int ret;
64 
65 	ret = php_stream_read((php_stream*)cookie, buffer, size);
66 	return ret;
67 }
68 
stream_cookie_writer(void * cookie,const char * buffer,int size)69 static int stream_cookie_writer(void *cookie, const char *buffer, int size)
70 {
71 
72 	return php_stream_write((php_stream *)cookie, (char *)buffer, size);
73 }
74 
stream_cookie_seeker(void * cookie,zend_off_t position,int whence)75 static PHP_FPOS_T stream_cookie_seeker(void *cookie, zend_off_t position, int whence)
76 {
77 
78 	return (PHP_FPOS_T)php_stream_seek((php_stream *)cookie, position, whence);
79 }
80 
stream_cookie_closer(void * cookie)81 static int stream_cookie_closer(void *cookie)
82 {
83 	php_stream *stream = (php_stream*)cookie;
84 
85 	/* prevent recursion */
86 	stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE;
87 	return php_stream_free(stream,
88 		PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_KEEP_RSRC | PHP_STREAM_FREE_RSRC_DTOR);
89 }
90 #elif defined(HAVE_FOPENCOOKIE)
stream_cookie_reader(void * cookie,char * buffer,size_t size)91 static ssize_t stream_cookie_reader(void *cookie, char *buffer, size_t size)
92 {
93 	ssize_t ret;
94 
95 	ret = php_stream_read(((php_stream *)cookie), buffer, size);
96 	return ret;
97 }
98 
stream_cookie_writer(void * cookie,const char * buffer,size_t size)99 static ssize_t stream_cookie_writer(void *cookie, const char *buffer, size_t size)
100 {
101 
102 	return php_stream_write(((php_stream *)cookie), (char *)buffer, size);
103 }
104 
105 # ifdef COOKIE_SEEKER_USES_OFF64_T
stream_cookie_seeker(void * cookie,off64_t * position,int whence)106 static int stream_cookie_seeker(void *cookie, off64_t *position, int whence)
107 {
108 
109 	*position = php_stream_seek((php_stream *)cookie, (zend_off_t)*position, whence);
110 
111 	if (*position == -1) {
112 		return -1;
113 	}
114 	return 0;
115 }
116 # else
stream_cookie_seeker(void * cookie,zend_off_t position,int whence)117 static int stream_cookie_seeker(void *cookie, zend_off_t position, int whence)
118 {
119 
120 	return php_stream_seek((php_stream *)cookie, position, whence);
121 }
122 # endif
123 
stream_cookie_closer(void * cookie)124 static int stream_cookie_closer(void *cookie)
125 {
126 	php_stream *stream = (php_stream*)cookie;
127 
128 	/* prevent recursion */
129 	stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE;
130 	return php_stream_free(stream,
131 		PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_KEEP_RSRC | PHP_STREAM_FREE_RSRC_DTOR);
132 }
133 #endif /* elif defined(HAVE_FOPENCOOKIE) */
134 
135 #if HAVE_FOPENCOOKIE
136 static COOKIE_IO_FUNCTIONS_T stream_cookie_functions =
137 {
138 	stream_cookie_reader, stream_cookie_writer,
139 	stream_cookie_seeker, stream_cookie_closer
140 };
141 #else
142 /* TODO: use socketpair() to emulate fopencookie, as suggested by Hartmut ? */
143 #endif
144 /* }}} */
145 
146 /* {{{ php_stream_mode_sanitize_fdopen_fopencookie
147  * Result should have at least size 5, e.g. to write wbx+\0 */
php_stream_mode_sanitize_fdopen_fopencookie(php_stream * stream,char * result)148 void php_stream_mode_sanitize_fdopen_fopencookie(php_stream *stream, char *result)
149 {
150 	/* replace modes not supported by fdopen and fopencookie, but supported
151 	 * by PHP's fread(), so that their calls won't fail */
152 	const char *cur_mode = stream->mode;
153 	int         has_plus = 0,
154 		        has_bin  = 0,
155 				i,
156 				res_curs = 0;
157 
158 	if (cur_mode[0] == 'r' || cur_mode[0] == 'w' || cur_mode[0] == 'a') {
159 		result[res_curs++] = cur_mode[0];
160 	} else {
161 		/* assume cur_mode[0] is 'c' or 'x'; substitute by 'w', which should not
162 		 * truncate anything in fdopen/fopencookie */
163 		result[res_curs++] = 'w';
164 
165 		/* x is allowed (at least by glibc & compat), but not as the 1st mode
166 		 * as in PHP and in any case is (at best) ignored by fdopen and fopencookie */
167 	}
168 
169 	/* assume current mode has at most length 4 (e.g. wbn+) */
170 	for (i = 1; i < 4 && cur_mode[i] != '\0'; i++) {
171 		if (cur_mode[i] == 'b') {
172 			has_bin = 1;
173 		} else if (cur_mode[i] == '+') {
174 			has_plus = 1;
175 		}
176 		/* ignore 'n', 't' or other stuff */
177 	}
178 
179 	if (has_bin) {
180 		result[res_curs++] = 'b';
181 	}
182 	if (has_plus) {
183 		result[res_curs++] = '+';
184 	}
185 
186 	result[res_curs] = '\0';
187 }
188 /* }}} */
189 
190 /* {{{ php_stream_cast */
_php_stream_cast(php_stream * stream,int castas,void ** ret,int show_err)191 PHPAPI int _php_stream_cast(php_stream *stream, int castas, void **ret, int show_err)
192 {
193 	int flags = castas & PHP_STREAM_CAST_MASK;
194 	castas &= ~PHP_STREAM_CAST_MASK;
195 
196 	/* synchronize our buffer (if possible) */
197 	if (ret && castas != PHP_STREAM_AS_FD_FOR_SELECT) {
198 		php_stream_flush(stream);
199 		if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) {
200 			zend_off_t dummy;
201 
202 			stream->ops->seek(stream, stream->position, SEEK_SET, &dummy);
203 			stream->readpos = stream->writepos = 0;
204 		}
205 	}
206 
207 	/* filtered streams can only be cast as stdio, and only when fopencookie is present */
208 
209 	if (castas == PHP_STREAM_AS_STDIO) {
210 		if (stream->stdiocast) {
211 			if (ret) {
212 				*(FILE**)ret = stream->stdiocast;
213 			}
214 			goto exit_success;
215 		}
216 
217 		/* if the stream is a stdio stream let's give it a chance to respond
218 		 * first, to avoid doubling up the layers of stdio with an fopencookie */
219 		if (php_stream_is(stream, PHP_STREAM_IS_STDIO) &&
220 			stream->ops->cast &&
221 			!php_stream_is_filtered(stream) &&
222 			stream->ops->cast(stream, castas, ret) == SUCCESS
223 		) {
224 			goto exit_success;
225 		}
226 
227 #if HAVE_FOPENCOOKIE
228 		/* if just checking, say yes we can be a FILE*, but don't actually create it yet */
229 		if (ret == NULL) {
230 			goto exit_success;
231 		}
232 
233 		{
234 			char fixed_mode[5];
235 			php_stream_mode_sanitize_fdopen_fopencookie(stream, fixed_mode);
236 			*(FILE**)ret = fopencookie(stream, fixed_mode, PHP_STREAM_COOKIE_FUNCTIONS);
237 		}
238 
239 		if (*ret != NULL) {
240 			zend_off_t pos;
241 
242 			stream->fclose_stdiocast = PHP_STREAM_FCLOSE_FOPENCOOKIE;
243 
244 			/* If the stream position is not at the start, we need to force
245 			 * the stdio layer to believe it's real location. */
246 			pos = php_stream_tell(stream);
247 			if (pos > 0) {
248 				zend_fseek(*ret, pos, SEEK_SET);
249 			}
250 
251 			goto exit_success;
252 		}
253 
254 		/* must be either:
255 			a) programmer error
256 			b) no memory
257 			-> lets bail
258 		*/
259 		php_error_docref(NULL, E_ERROR, "fopencookie failed");
260 		return FAILURE;
261 #endif
262 
263 		if (!php_stream_is_filtered(stream) && stream->ops->cast && stream->ops->cast(stream, castas, NULL) == SUCCESS) {
264 			if (FAILURE == stream->ops->cast(stream, castas, ret)) {
265 				return FAILURE;
266 			}
267 			goto exit_success;
268 		} else if (flags & PHP_STREAM_CAST_TRY_HARD) {
269 			php_stream *newstream;
270 
271 			newstream = php_stream_fopen_tmpfile();
272 			if (newstream) {
273 				int retcopy = php_stream_copy_to_stream_ex(stream, newstream, PHP_STREAM_COPY_ALL, NULL);
274 
275 				if (retcopy != SUCCESS) {
276 					php_stream_close(newstream);
277 				} else {
278 					int retcast = php_stream_cast(newstream, castas | flags, (void **)ret, show_err);
279 
280 					if (retcast == SUCCESS) {
281 						rewind(*(FILE**)ret);
282 					}
283 
284 					/* do some specialized cleanup */
285 					if ((flags & PHP_STREAM_CAST_RELEASE)) {
286 						php_stream_free(stream, PHP_STREAM_FREE_CLOSE_CASTED);
287 					}
288 
289 					/* TODO: we probably should be setting .stdiocast and .fclose_stdiocast or
290 					 * we may be leaking the FILE*. Needs investigation, though. */
291 					return retcast;
292 				}
293 			}
294 		}
295 	}
296 
297 	if (php_stream_is_filtered(stream)) {
298 		if (show_err) {
299 			php_error_docref(NULL, E_WARNING, "cannot cast a filtered stream on this system");
300 		}
301 		return FAILURE;
302 	} else if (stream->ops->cast && stream->ops->cast(stream, castas, ret) == SUCCESS) {
303 		goto exit_success;
304 	}
305 
306 	if (show_err) {
307 		/* these names depend on the values of the PHP_STREAM_AS_XXX defines in php_streams.h */
308 		static const char *cast_names[4] = {
309 			"STDIO FILE*",
310 			"File Descriptor",
311 			"Socket Descriptor",
312 			"select()able descriptor"
313 		};
314 
315 		php_error_docref(NULL, E_WARNING, "cannot represent a stream of type %s as a %s", stream->ops->label, cast_names[castas]);
316 	}
317 
318 	return FAILURE;
319 
320 exit_success:
321 
322 	if ((stream->writepos - stream->readpos) > 0 &&
323 		stream->fclose_stdiocast != PHP_STREAM_FCLOSE_FOPENCOOKIE &&
324 		(flags & PHP_STREAM_CAST_INTERNAL) == 0
325 	) {
326 		/* the data we have buffered will be lost to the third party library that
327 		 * will be accessing the stream.  Emit a warning so that the end-user will
328 		 * know that they should try something else */
329 
330 		php_error_docref(NULL, E_WARNING, ZEND_LONG_FMT " bytes of buffered data lost during stream conversion!", (zend_long)(stream->writepos - stream->readpos));
331 	}
332 
333 	if (castas == PHP_STREAM_AS_STDIO && ret) {
334 		stream->stdiocast = *(FILE**)ret;
335 	}
336 
337 	if (flags & PHP_STREAM_CAST_RELEASE) {
338 		php_stream_free(stream, PHP_STREAM_FREE_CLOSE_CASTED);
339 	}
340 
341 	return SUCCESS;
342 
343 }
344 /* }}} */
345 
346 /* {{{ php_stream_open_wrapper_as_file */
_php_stream_open_wrapper_as_file(char * path,char * mode,int options,zend_string ** opened_path STREAMS_DC)347 PHPAPI FILE * _php_stream_open_wrapper_as_file(char *path, char *mode, int options, zend_string **opened_path STREAMS_DC)
348 {
349 	FILE *fp = NULL;
350 	php_stream *stream = NULL;
351 
352 	stream = php_stream_open_wrapper_rel(path, mode, options|STREAM_WILL_CAST, opened_path);
353 
354 	if (stream == NULL) {
355 		return NULL;
356 	}
357 
358 	if (php_stream_cast(stream, PHP_STREAM_AS_STDIO|PHP_STREAM_CAST_TRY_HARD|PHP_STREAM_CAST_RELEASE, (void**)&fp, REPORT_ERRORS) == FAILURE) {
359 		php_stream_close(stream);
360 		if (opened_path && *opened_path) {
361 			zend_string_release_ex(*opened_path, 0);
362 		}
363 		return NULL;
364 	}
365 	return fp;
366 }
367 /* }}} */
368 
369 /* {{{ php_stream_make_seekable */
_php_stream_make_seekable(php_stream * origstream,php_stream ** newstream,int flags STREAMS_DC)370 PHPAPI int _php_stream_make_seekable(php_stream *origstream, php_stream **newstream, int flags STREAMS_DC)
371 {
372 	if (newstream == NULL) {
373 		return PHP_STREAM_FAILED;
374 	}
375 	*newstream = NULL;
376 
377 	if (((flags & PHP_STREAM_FORCE_CONVERSION) == 0) && origstream->ops->seek != NULL) {
378 		*newstream = origstream;
379 		return PHP_STREAM_UNCHANGED;
380 	}
381 
382 	/* Use a tmpfile and copy the old streams contents into it */
383 
384 	if (flags & PHP_STREAM_PREFER_STDIO) {
385 		*newstream = php_stream_fopen_tmpfile();
386 	} else {
387 		*newstream = php_stream_temp_new();
388 	}
389 
390 	if (*newstream == NULL) {
391 		return PHP_STREAM_FAILED;
392 	}
393 
394 #if ZEND_DEBUG
395 	(*newstream)->open_filename = origstream->open_filename;
396 	(*newstream)->open_lineno = origstream->open_lineno;
397 #endif
398 
399 	if (php_stream_copy_to_stream_ex(origstream, *newstream, PHP_STREAM_COPY_ALL, NULL) != SUCCESS) {
400 		php_stream_close(*newstream);
401 		*newstream = NULL;
402 		return PHP_STREAM_CRITICAL;
403 	}
404 
405 	php_stream_close(origstream);
406 	php_stream_seek(*newstream, 0, SEEK_SET);
407 
408 	return PHP_STREAM_RELEASED;
409 }
410 /* }}} */
411