xref: /php-src/main/streams/cast.c (revision 577b8ae4)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | https://www.php.net/license/3_01.txt                                 |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Authors: Wez Furlong <wez@thebrainroom.com>                          |
14    +----------------------------------------------------------------------+
15  */
16 
17 #ifndef _GNU_SOURCE
18 # define _GNU_SOURCE
19 #endif
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 # else
108 static int stream_cookie_seeker(void *cookie, off_t *position, int whence)
109 # endif
110 {
111 
112 	*position = php_stream_seek((php_stream *)cookie, (zend_off_t)*position, whence);
113 
114 	if (*position == -1) {
115 		return -1;
116 	}
117 	return 0;
118 }
119 
stream_cookie_closer(void * cookie)120 static int stream_cookie_closer(void *cookie)
121 {
122 	php_stream *stream = (php_stream*)cookie;
123 
124 	/* prevent recursion */
125 	stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE;
126 	return php_stream_free(stream,
127 		PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_KEEP_RSRC | PHP_STREAM_FREE_RSRC_DTOR);
128 }
129 #endif /* elif defined(HAVE_FOPENCOOKIE) */
130 
131 #if HAVE_FOPENCOOKIE
132 static cookie_io_functions_t stream_cookie_functions =
133 {
134 	stream_cookie_reader, stream_cookie_writer,
135 	stream_cookie_seeker, stream_cookie_closer
136 };
137 #else
138 /* TODO: use socketpair() to emulate fopencookie, as suggested by Hartmut ? */
139 #endif
140 /* }}} */
141 
142 /* {{{ php_stream_mode_sanitize_fdopen_fopencookie
143  * Result should have at least size 5, e.g. to write wbx+\0 */
php_stream_mode_sanitize_fdopen_fopencookie(php_stream * stream,char * result)144 void php_stream_mode_sanitize_fdopen_fopencookie(php_stream *stream, char *result)
145 {
146 	/* replace modes not supported by fdopen and fopencookie, but supported
147 	 * by PHP's fread(), so that their calls won't fail */
148 	const char *cur_mode = stream->mode;
149 	int         has_plus = 0,
150 		        has_bin  = 0,
151 				i,
152 				res_curs = 0;
153 
154 	if (cur_mode[0] == 'r' || cur_mode[0] == 'w' || cur_mode[0] == 'a') {
155 		result[res_curs++] = cur_mode[0];
156 	} else {
157 		/* assume cur_mode[0] is 'c' or 'x'; substitute by 'w', which should not
158 		 * truncate anything in fdopen/fopencookie */
159 		result[res_curs++] = 'w';
160 
161 		/* x is allowed (at least by glibc & compat), but not as the 1st mode
162 		 * as in PHP and in any case is (at best) ignored by fdopen and fopencookie */
163 	}
164 
165 	/* assume current mode has at most length 4 (e.g. wbn+) */
166 	for (i = 1; i < 4 && cur_mode[i] != '\0'; i++) {
167 		if (cur_mode[i] == 'b') {
168 			has_bin = 1;
169 		} else if (cur_mode[i] == '+') {
170 			has_plus = 1;
171 		}
172 		/* ignore 'n', 't' or other stuff */
173 	}
174 
175 	if (has_bin) {
176 		result[res_curs++] = 'b';
177 	}
178 	if (has_plus) {
179 		result[res_curs++] = '+';
180 	}
181 
182 	result[res_curs] = '\0';
183 }
184 /* }}} */
185 
186 /* {{{ php_stream_cast */
_php_stream_cast(php_stream * stream,int castas,void ** ret,int show_err)187 PHPAPI int _php_stream_cast(php_stream *stream, int castas, void **ret, int show_err)
188 {
189 	int flags = castas & PHP_STREAM_CAST_MASK;
190 	castas &= ~PHP_STREAM_CAST_MASK;
191 
192 	/* synchronize our buffer (if possible) */
193 	if (ret && castas != PHP_STREAM_AS_FD_FOR_SELECT) {
194 		php_stream_flush(stream);
195 		if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) {
196 			zend_off_t dummy;
197 
198 			stream->ops->seek(stream, stream->position, SEEK_SET, &dummy);
199 			stream->readpos = stream->writepos = 0;
200 		}
201 	}
202 
203 	/* filtered streams can only be cast as stdio, and only when fopencookie is present */
204 
205 	if (castas == PHP_STREAM_AS_STDIO) {
206 		if (stream->stdiocast) {
207 			if (ret) {
208 				*(FILE**)ret = stream->stdiocast;
209 			}
210 			goto exit_success;
211 		}
212 
213 		/* if the stream is a stdio stream let's give it a chance to respond
214 		 * first, to avoid doubling up the layers of stdio with an fopencookie */
215 		if (php_stream_is(stream, PHP_STREAM_IS_STDIO) &&
216 			stream->ops->cast &&
217 			!php_stream_is_filtered(stream) &&
218 			stream->ops->cast(stream, castas, ret) == SUCCESS
219 		) {
220 			goto exit_success;
221 		}
222 
223 #if HAVE_FOPENCOOKIE
224 		/* if just checking, say yes we can be a FILE*, but don't actually create it yet */
225 		if (ret == NULL) {
226 			goto exit_success;
227 		}
228 
229 		{
230 			char fixed_mode[5];
231 			php_stream_mode_sanitize_fdopen_fopencookie(stream, fixed_mode);
232 			*(FILE**)ret = fopencookie(stream, fixed_mode, PHP_STREAM_COOKIE_FUNCTIONS);
233 		}
234 
235 		if (*ret != NULL) {
236 			zend_off_t pos;
237 
238 			stream->fclose_stdiocast = PHP_STREAM_FCLOSE_FOPENCOOKIE;
239 
240 			/* If the stream position is not at the start, we need to force
241 			 * the stdio layer to believe it's real location. */
242 			pos = php_stream_tell(stream);
243 			if (pos > 0) {
244 				zend_fseek(*ret, pos, SEEK_SET);
245 			}
246 
247 			goto exit_success;
248 		}
249 
250 		/* must be either:
251 			a) programmer error
252 			b) no memory
253 			-> lets bail
254 		*/
255 		php_error_docref(NULL, E_ERROR, "fopencookie failed");
256 		return FAILURE;
257 #endif
258 
259 		if (!php_stream_is_filtered(stream) && stream->ops->cast && stream->ops->cast(stream, castas, NULL) == SUCCESS) {
260 			if (FAILURE == stream->ops->cast(stream, castas, ret)) {
261 				return FAILURE;
262 			}
263 			goto exit_success;
264 		} else if (flags & PHP_STREAM_CAST_TRY_HARD) {
265 			php_stream *newstream;
266 
267 			newstream = php_stream_fopen_tmpfile();
268 			if (newstream) {
269 				int retcopy = php_stream_copy_to_stream_ex(stream, newstream, PHP_STREAM_COPY_ALL, NULL);
270 
271 				if (retcopy != SUCCESS) {
272 					php_stream_close(newstream);
273 				} else {
274 					int retcast = php_stream_cast(newstream, castas | flags, (void **)ret, show_err);
275 
276 					if (retcast == SUCCESS) {
277 						rewind(*(FILE**)ret);
278 					}
279 
280 					/* do some specialized cleanup */
281 					if ((flags & PHP_STREAM_CAST_RELEASE)) {
282 						php_stream_free(stream, PHP_STREAM_FREE_CLOSE_CASTED);
283 					}
284 
285 					/* TODO: we probably should be setting .stdiocast and .fclose_stdiocast or
286 					 * we may be leaking the FILE*. Needs investigation, though. */
287 					return retcast;
288 				}
289 			}
290 		}
291 	}
292 
293 	if (php_stream_is_filtered(stream)) {
294 		if (show_err) {
295 			php_error_docref(NULL, E_WARNING, "Cannot cast a filtered stream on this system");
296 		}
297 		return FAILURE;
298 	} else if (stream->ops->cast && stream->ops->cast(stream, castas, ret) == SUCCESS) {
299 		goto exit_success;
300 	}
301 
302 	if (show_err) {
303 		/* these names depend on the values of the PHP_STREAM_AS_XXX defines in php_streams.h */
304 		static const char *cast_names[4] = {
305 			"STDIO FILE*",
306 			"File Descriptor",
307 			"Socket Descriptor",
308 			"select()able descriptor"
309 		};
310 
311 		php_error_docref(NULL, E_WARNING, "Cannot represent a stream of type %s as a %s", stream->ops->label, cast_names[castas]);
312 	}
313 
314 	return FAILURE;
315 
316 exit_success:
317 
318 	if ((stream->writepos - stream->readpos) > 0 &&
319 		stream->fclose_stdiocast != PHP_STREAM_FCLOSE_FOPENCOOKIE &&
320 		(flags & PHP_STREAM_CAST_INTERNAL) == 0
321 	) {
322 		/* the data we have buffered will be lost to the third party library that
323 		 * will be accessing the stream.  Emit a warning so that the end-user will
324 		 * know that they should try something else */
325 
326 		php_error_docref(NULL, E_WARNING, ZEND_LONG_FMT " bytes of buffered data lost during stream conversion!", (zend_long)(stream->writepos - stream->readpos));
327 	}
328 
329 	if (castas == PHP_STREAM_AS_STDIO && ret) {
330 		stream->stdiocast = *(FILE**)ret;
331 	}
332 
333 	if (flags & PHP_STREAM_CAST_RELEASE) {
334 		php_stream_free(stream, PHP_STREAM_FREE_CLOSE_CASTED);
335 	}
336 
337 	return SUCCESS;
338 
339 }
340 /* }}} */
341 
342 /* {{{ php_stream_open_wrapper_as_file */
_php_stream_open_wrapper_as_file(char * path,char * mode,int options,zend_string ** opened_path STREAMS_DC)343 PHPAPI FILE * _php_stream_open_wrapper_as_file(char *path, char *mode, int options, zend_string **opened_path STREAMS_DC)
344 {
345 	FILE *fp = NULL;
346 	php_stream *stream = NULL;
347 
348 	stream = php_stream_open_wrapper_rel(path, mode, options|STREAM_WILL_CAST, opened_path);
349 
350 	if (stream == NULL) {
351 		return NULL;
352 	}
353 
354 	if (php_stream_cast(stream, PHP_STREAM_AS_STDIO|PHP_STREAM_CAST_TRY_HARD|PHP_STREAM_CAST_RELEASE, (void**)&fp, REPORT_ERRORS) == FAILURE) {
355 		php_stream_close(stream);
356 		if (opened_path && *opened_path) {
357 			zend_string_release_ex(*opened_path, 0);
358 		}
359 		return NULL;
360 	}
361 	return fp;
362 }
363 /* }}} */
364 
365 /* {{{ php_stream_make_seekable */
_php_stream_make_seekable(php_stream * origstream,php_stream ** newstream,int flags STREAMS_DC)366 PHPAPI int _php_stream_make_seekable(php_stream *origstream, php_stream **newstream, int flags STREAMS_DC)
367 {
368 	if (newstream == NULL) {
369 		return PHP_STREAM_FAILED;
370 	}
371 	*newstream = NULL;
372 
373 	if (((flags & PHP_STREAM_FORCE_CONVERSION) == 0) && origstream->ops->seek != NULL) {
374 		*newstream = origstream;
375 		return PHP_STREAM_UNCHANGED;
376 	}
377 
378 	/* Use a tmpfile and copy the old streams contents into it */
379 
380 	if (flags & PHP_STREAM_PREFER_STDIO) {
381 		*newstream = php_stream_fopen_tmpfile();
382 	} else {
383 		*newstream = php_stream_temp_new();
384 	}
385 
386 	if (*newstream == NULL) {
387 		return PHP_STREAM_FAILED;
388 	}
389 
390 #if ZEND_DEBUG
391 	(*newstream)->open_filename = origstream->open_filename;
392 	(*newstream)->open_lineno = origstream->open_lineno;
393 #endif
394 
395 	if (php_stream_copy_to_stream_ex(origstream, *newstream, PHP_STREAM_COPY_ALL, NULL) != SUCCESS) {
396 		php_stream_close(*newstream);
397 		*newstream = NULL;
398 		return PHP_STREAM_CRITICAL;
399 	}
400 
401 	php_stream_close(origstream);
402 	php_stream_seek(*newstream, 0, SEEK_SET);
403 
404 	return PHP_STREAM_RELEASED;
405 }
406 /* }}} */
407