xref: /PHP-7.2/main/streams/cast.c (revision 7a7ec01a)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1997-2018 The PHP Group                                |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.php.net/license/3_01.txt                                  |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Authors: Wez Furlong <wez@thebrainroom.com>                          |
16    +----------------------------------------------------------------------+
17  */
18 
19 /* $Id$ */
20 
21 #define _GNU_SOURCE
22 #include "php.h"
23 #include "php_globals.h"
24 #include "php_network.h"
25 #include "php_open_temporary_file.h"
26 #include "ext/standard/file.h"
27 #include <stddef.h>
28 #include <fcntl.h>
29 
30 #include "php_streams_int.h"
31 
32 /* Under BSD, emulate fopencookie using funopen */
33 #if defined(HAVE_FUNOPEN) && !defined(HAVE_FOPENCOOKIE)
34 
35 /* NetBSD 6.0+ uses off_t instead of fpos_t in funopen */
36 # if defined(__NetBSD__) && (__NetBSD_Version__ >= 600000000)
37 #  define PHP_FPOS_T off_t
38 # else
39 #  define PHP_FPOS_T fpos_t
40 # endif
41 
42 typedef struct {
43 	int (*reader)(void *, char *, int);
44 	int (*writer)(void *, const char *, int);
45 	PHP_FPOS_T (*seeker)(void *, PHP_FPOS_T, int);
46 	int (*closer)(void *);
47 } COOKIE_IO_FUNCTIONS_T;
48 
fopencookie(void * cookie,const char * mode,COOKIE_IO_FUNCTIONS_T * funcs)49 FILE *fopencookie(void *cookie, const char *mode, COOKIE_IO_FUNCTIONS_T *funcs)
50 {
51 	return funopen(cookie, funcs->reader, funcs->writer, funcs->seeker, funcs->closer);
52 }
53 # define HAVE_FOPENCOOKIE 1
54 # define PHP_EMULATE_FOPENCOOKIE 1
55 # define PHP_STREAM_COOKIE_FUNCTIONS	&stream_cookie_functions
56 #elif defined(HAVE_FOPENCOOKIE)
57 # define PHP_STREAM_COOKIE_FUNCTIONS	stream_cookie_functions
58 #endif
59 
60 /* {{{ STDIO with fopencookie */
61 #if defined(PHP_EMULATE_FOPENCOOKIE)
62 /* use our fopencookie emulation */
stream_cookie_reader(void * cookie,char * buffer,int size)63 static int stream_cookie_reader(void *cookie, char *buffer, int size)
64 {
65 	int ret;
66 
67 	ret = php_stream_read((php_stream*)cookie, buffer, size);
68 	return ret;
69 }
70 
stream_cookie_writer(void * cookie,const char * buffer,int size)71 static int stream_cookie_writer(void *cookie, const char *buffer, int size)
72 {
73 
74 	return php_stream_write((php_stream *)cookie, (char *)buffer, size);
75 }
76 
stream_cookie_seeker(void * cookie,zend_off_t position,int whence)77 static PHP_FPOS_T stream_cookie_seeker(void *cookie, zend_off_t position, int whence)
78 {
79 
80 	return (PHP_FPOS_T)php_stream_seek((php_stream *)cookie, position, whence);
81 }
82 
stream_cookie_closer(void * cookie)83 static int stream_cookie_closer(void *cookie)
84 {
85 	php_stream *stream = (php_stream*)cookie;
86 
87 	/* prevent recursion */
88 	stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE;
89 	return php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_KEEP_RSRC);
90 }
91 #elif defined(HAVE_FOPENCOOKIE)
stream_cookie_reader(void * cookie,char * buffer,size_t size)92 static ssize_t stream_cookie_reader(void *cookie, char *buffer, size_t size)
93 {
94 	ssize_t ret;
95 
96 	ret = php_stream_read(((php_stream *)cookie), buffer, size);
97 	return ret;
98 }
99 
stream_cookie_writer(void * cookie,const char * buffer,size_t size)100 static ssize_t stream_cookie_writer(void *cookie, const char *buffer, size_t size)
101 {
102 
103 	return php_stream_write(((php_stream *)cookie), (char *)buffer, size);
104 }
105 
106 # ifdef COOKIE_SEEKER_USES_OFF64_T
stream_cookie_seeker(void * cookie,__off64_t * position,int whence)107 static int stream_cookie_seeker(void *cookie, __off64_t *position, int whence)
108 {
109 
110 	*position = php_stream_seek((php_stream *)cookie, (zend_off_t)*position, whence);
111 
112 	if (*position == -1) {
113 		return -1;
114 	}
115 	return 0;
116 }
117 # else
stream_cookie_seeker(void * cookie,zend_off_t position,int whence)118 static int stream_cookie_seeker(void *cookie, zend_off_t position, int whence)
119 {
120 
121 	return php_stream_seek((php_stream *)cookie, position, whence);
122 }
123 # endif
124 
stream_cookie_closer(void * cookie)125 static int stream_cookie_closer(void *cookie)
126 {
127 	php_stream *stream = (php_stream*)cookie;
128 
129 	/* prevent recursion */
130 	stream->fclose_stdiocast = PHP_STREAM_FCLOSE_NONE;
131 	return php_stream_free(stream, PHP_STREAM_FREE_CLOSE | PHP_STREAM_FREE_KEEP_RSRC);
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 		php_error_docref(NULL, E_WARNING, "cannot cast a filtered stream on this system");
299 		return FAILURE;
300 	} else if (stream->ops->cast && stream->ops->cast(stream, castas, ret) == SUCCESS) {
301 		goto exit_success;
302 	}
303 
304 	if (show_err) {
305 		/* these names depend on the values of the PHP_STREAM_AS_XXX defines in php_streams.h */
306 		static const char *cast_names[4] = {
307 			"STDIO FILE*",
308 			"File Descriptor",
309 			"Socket Descriptor",
310 			"select()able descriptor"
311 		};
312 
313 		php_error_docref(NULL, E_WARNING, "cannot represent a stream of type %s as a %s", stream->ops->label, cast_names[castas]);
314 	}
315 
316 	return FAILURE;
317 
318 exit_success:
319 
320 	if ((stream->writepos - stream->readpos) > 0 &&
321 		stream->fclose_stdiocast != PHP_STREAM_FCLOSE_FOPENCOOKIE &&
322 		(flags & PHP_STREAM_CAST_INTERNAL) == 0
323 	) {
324 		/* the data we have buffered will be lost to the third party library that
325 		 * will be accessing the stream.  Emit a warning so that the end-user will
326 		 * know that they should try something else */
327 
328 		php_error_docref(NULL, E_WARNING, ZEND_LONG_FMT " bytes of buffered data lost during stream conversion!", (zend_long)(stream->writepos - stream->readpos));
329 	}
330 
331 	if (castas == PHP_STREAM_AS_STDIO && ret) {
332 		stream->stdiocast = *(FILE**)ret;
333 	}
334 
335 	if (flags & PHP_STREAM_CAST_RELEASE) {
336 		php_stream_free(stream, PHP_STREAM_FREE_CLOSE_CASTED);
337 	}
338 
339 	return SUCCESS;
340 
341 }
342 /* }}} */
343 
344 /* {{{ php_stream_open_wrapper_as_file */
_php_stream_open_wrapper_as_file(char * path,char * mode,int options,zend_string ** opened_path STREAMS_DC)345 PHPAPI FILE * _php_stream_open_wrapper_as_file(char *path, char *mode, int options, zend_string **opened_path STREAMS_DC)
346 {
347 	FILE *fp = NULL;
348 	php_stream *stream = NULL;
349 
350 	stream = php_stream_open_wrapper_rel(path, mode, options|STREAM_WILL_CAST, opened_path);
351 
352 	if (stream == NULL) {
353 		return NULL;
354 	}
355 
356 	if (php_stream_cast(stream, PHP_STREAM_AS_STDIO|PHP_STREAM_CAST_TRY_HARD|PHP_STREAM_CAST_RELEASE, (void**)&fp, REPORT_ERRORS) == FAILURE) {
357 		php_stream_close(stream);
358 		if (opened_path && *opened_path) {
359 			zend_string_release(*opened_path);
360 		}
361 		return NULL;
362 	}
363 	return fp;
364 }
365 /* }}} */
366 
367 /* {{{ php_stream_make_seekable */
_php_stream_make_seekable(php_stream * origstream,php_stream ** newstream,int flags STREAMS_DC)368 PHPAPI int _php_stream_make_seekable(php_stream *origstream, php_stream **newstream, int flags STREAMS_DC)
369 {
370 	if (newstream == NULL) {
371 		return PHP_STREAM_FAILED;
372 	}
373 	*newstream = NULL;
374 
375 	if (((flags & PHP_STREAM_FORCE_CONVERSION) == 0) && origstream->ops->seek != NULL) {
376 		*newstream = origstream;
377 		return PHP_STREAM_UNCHANGED;
378 	}
379 
380 	/* Use a tmpfile and copy the old streams contents into it */
381 
382 	if (flags & PHP_STREAM_PREFER_STDIO) {
383 		*newstream = php_stream_fopen_tmpfile();
384 	} else {
385 		*newstream = php_stream_temp_new();
386 	}
387 
388 	if (*newstream == NULL) {
389 		return PHP_STREAM_FAILED;
390 	}
391 
392 #if ZEND_DEBUG
393 	(*newstream)->open_filename = origstream->open_filename;
394 	(*newstream)->open_lineno = origstream->open_lineno;
395 #endif
396 
397 	if (php_stream_copy_to_stream_ex(origstream, *newstream, PHP_STREAM_COPY_ALL, NULL) != SUCCESS) {
398 		php_stream_close(*newstream);
399 		*newstream = NULL;
400 		return PHP_STREAM_CRITICAL;
401 	}
402 
403 	php_stream_close(origstream);
404 	php_stream_seek(*newstream, 0, SEEK_SET);
405 
406 	return PHP_STREAM_RELEASED;
407 }
408 /* }}} */
409 
410 /*
411  * Local variables:
412  * tab-width: 4
413  * c-basic-offset: 4
414  * End:
415  * vim600: noet sw=4 ts=4 fdm=marker
416  * vim<600: noet sw=4 ts=4
417  */
418