xref: /php-src/ext/standard/file.c (revision 84a0da15)
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: Rasmus Lerdorf <rasmus@php.net>                             |
14    |          Stig Bakken <ssb@php.net>                                   |
15    |          Andi Gutmans <andi@php.net>                                 |
16    |          Zeev Suraski <zeev@php.net>                                 |
17    | PHP 4.0 patches by Thies C. Arntzen (thies@thieso.net)               |
18    | PHP streams by Wez Furlong (wez@thebrainroom.com)                    |
19    +----------------------------------------------------------------------+
20 */
21 
22 /* {{{ includes */
23 
24 #include "php.h"
25 #include "ext/standard/flock_compat.h"
26 #include "ext/standard/php_filestat.h"
27 #include "php_open_temporary_file.h"
28 #include "ext/standard/basic_functions.h"
29 #include "php_ini.h"
30 #include "zend_smart_str.h"
31 
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <errno.h>
35 #include <wchar.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <fcntl.h>
39 
40 #ifdef PHP_WIN32
41 # include <io.h>
42 # define O_RDONLY _O_RDONLY
43 # include "win32/param.h"
44 # include "win32/winutil.h"
45 # include "win32/fnmatch.h"
46 # include "win32/ioutil.h"
47 #else
48 # ifdef HAVE_SYS_PARAM_H
49 #  include <sys/param.h>
50 # endif
51 # if HAVE_SYS_SELECT_H
52 #  include <sys/select.h>
53 # endif
54 # include <sys/socket.h>
55 # include <netinet/in.h>
56 # include <netdb.h>
57 # ifdef HAVE_ARPA_INET_H
58 #  include <arpa/inet.h>
59 # endif
60 #endif
61 
62 #include "php_string.h"
63 #include "file.h"
64 
65 #ifdef HAVE_PWD_H
66 # ifdef PHP_WIN32
67 #  include "win32/pwd.h"
68 # else
69 #  include <pwd.h>
70 # endif
71 #endif
72 
73 #include "fsock.h"
74 #include "fopen_wrappers.h"
75 #include "streamsfuncs.h" /* To define constants in the arg_info */
76 
77 #ifdef HAVE_SYS_FILE_H
78 # include <sys/file.h>
79 #endif
80 
81 #ifdef HAVE_SYS_MMAN_H
82 # include <sys/mman.h>
83 #endif
84 
85 #include "scanf.h"
86 #include "zend_API.h"
87 
88 #ifdef ZTS
89 int file_globals_id;
90 #else
91 php_file_globals file_globals;
92 #endif
93 
94 #if defined(HAVE_FNMATCH) && !defined(PHP_WIN32)
95 # ifndef _GNU_SOURCE
96 #  define _GNU_SOURCE
97 # endif
98 # include <fnmatch.h>
99 #endif
100 
101 #include "file_arginfo.h"
102 
103 /* }}} */
104 
105 #define PHP_STREAM_FROM_ZVAL(stream, arg) \
106 	ZEND_ASSERT(Z_TYPE_P(arg) == IS_RESOURCE); \
107 	php_stream_from_res(stream, Z_RES_P(arg));
108 
109 /* {{{ ZTS-stuff / Globals / Prototypes */
110 
111 /* sharing globals is *evil* */
112 static int le_stream_context = FAILURE;
113 
php_le_stream_context(void)114 PHPAPI int php_le_stream_context(void)
115 {
116 	return le_stream_context;
117 }
118 /* }}} */
119 
120 /* {{{ Module-Stuff */
ZEND_RSRC_DTOR_FUNC(file_context_dtor)121 static ZEND_RSRC_DTOR_FUNC(file_context_dtor)
122 {
123 	php_stream_context *context = (php_stream_context*)res->ptr;
124 	if (Z_TYPE(context->options) != IS_UNDEF) {
125 		zval_ptr_dtor(&context->options);
126 		ZVAL_UNDEF(&context->options);
127 	}
128 	php_stream_context_free(context);
129 }
130 
file_globals_ctor(php_file_globals * file_globals_p)131 static void file_globals_ctor(php_file_globals *file_globals_p)
132 {
133 	memset(file_globals_p, 0, sizeof(php_file_globals));
134 	file_globals_p->def_chunk_size = PHP_SOCK_CHUNK_SIZE;
135 }
136 
file_globals_dtor(php_file_globals * file_globals_p)137 static void file_globals_dtor(php_file_globals *file_globals_p)
138 {
139 #if defined(HAVE_GETHOSTBYNAME_R)
140 	if (file_globals_p->tmp_host_buf) {
141 		free(file_globals_p->tmp_host_buf);
142 	}
143 #endif
144 }
145 
PHP_INI_MH(OnUpdateAutoDetectLineEndings)146 static PHP_INI_MH(OnUpdateAutoDetectLineEndings)
147 {
148 	if (zend_ini_parse_bool(new_value)) {
149 		zend_error(E_DEPRECATED, "auto_detect_line_endings is deprecated");
150 	}
151 	return OnUpdateBool(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
152 }
153 
154 PHP_INI_BEGIN()
155 	STD_PHP_INI_ENTRY("user_agent", NULL, PHP_INI_ALL, OnUpdateString, user_agent, php_file_globals, file_globals)
156 	STD_PHP_INI_ENTRY("from", NULL, PHP_INI_ALL, OnUpdateString, from_address, php_file_globals, file_globals)
157 	STD_PHP_INI_ENTRY("default_socket_timeout", "60", PHP_INI_ALL, OnUpdateLong, default_socket_timeout, php_file_globals, file_globals)
158 	STD_PHP_INI_BOOLEAN("auto_detect_line_endings", "0", PHP_INI_ALL, OnUpdateAutoDetectLineEndings, auto_detect_line_endings, php_file_globals, file_globals)
PHP_INI_END()159 PHP_INI_END()
160 
161 PHP_MINIT_FUNCTION(file)
162 {
163 	le_stream_context = zend_register_list_destructors_ex(file_context_dtor, NULL, "stream-context", module_number);
164 
165 #ifdef ZTS
166 	ts_allocate_id(&file_globals_id, sizeof(php_file_globals), (ts_allocate_ctor) file_globals_ctor, (ts_allocate_dtor) file_globals_dtor);
167 #else
168 	file_globals_ctor(&file_globals);
169 #endif
170 
171 	REGISTER_INI_ENTRIES();
172 
173 	register_file_symbols(module_number);
174 
175 	return SUCCESS;
176 }
177 /* }}} */
178 
PHP_MSHUTDOWN_FUNCTION(file)179 PHP_MSHUTDOWN_FUNCTION(file) /* {{{ */
180 {
181 #ifndef ZTS
182 	file_globals_dtor(&file_globals);
183 #endif
184 	return SUCCESS;
185 }
186 /* }}} */
187 
php_flock_common(php_stream * stream,zend_long operation,uint32_t operation_arg_num,zval * wouldblock,zval * return_value)188 PHPAPI void php_flock_common(php_stream *stream, zend_long operation,
189 	uint32_t operation_arg_num, zval *wouldblock, zval *return_value)
190 {
191 	int flock_values[] = { LOCK_SH, LOCK_EX, LOCK_UN };
192 	int act;
193 
194 	act = operation & PHP_LOCK_UN;
195 	if (act < 1 || act > 3) {
196 		zend_argument_value_error(operation_arg_num, "must be one of LOCK_SH, LOCK_EX, or LOCK_UN");
197 		RETURN_THROWS();
198 	}
199 
200 	if (wouldblock) {
201 		ZEND_TRY_ASSIGN_REF_LONG(wouldblock, 0);
202 	}
203 
204 	/* flock_values contains all possible actions if (operation & PHP_LOCK_NB) we won't block on the lock */
205 	act = flock_values[act - 1] | (operation & PHP_LOCK_NB ? LOCK_NB : 0);
206 	if (php_stream_lock(stream, act)) {
207 		if (operation && errno == EWOULDBLOCK && wouldblock) {
208 			ZEND_TRY_ASSIGN_REF_LONG(wouldblock, 1);
209 		}
210 		RETURN_FALSE;
211 	}
212 	RETURN_TRUE;
213 }
214 
215 /* {{{ Portable file locking */
PHP_FUNCTION(flock)216 PHP_FUNCTION(flock)
217 {
218 	zval *res, *wouldblock = NULL;
219 	php_stream *stream;
220 	zend_long operation = 0;
221 
222 	ZEND_PARSE_PARAMETERS_START(2, 3)
223 		Z_PARAM_RESOURCE(res)
224 		Z_PARAM_LONG(operation)
225 		Z_PARAM_OPTIONAL
226 		Z_PARAM_ZVAL(wouldblock)
227 	ZEND_PARSE_PARAMETERS_END();
228 
229 	PHP_STREAM_FROM_ZVAL(stream, res);
230 
231 	php_flock_common(stream, operation, 2, wouldblock, return_value);
232 }
233 /* }}} */
234 
235 #define PHP_META_UNSAFE ".\\+*?[^]$() "
236 
237 /* {{{ Extracts all meta tag content attributes from a file and returns an array */
PHP_FUNCTION(get_meta_tags)238 PHP_FUNCTION(get_meta_tags)
239 {
240 	char *filename;
241 	size_t filename_len;
242 	bool use_include_path = 0;
243 	int in_tag = 0, done = 0;
244 	int looking_for_val = 0, have_name = 0, have_content = 0;
245 	int saw_name = 0, saw_content = 0;
246 	char *name = NULL, *value = NULL, *temp = NULL;
247 	php_meta_tags_token tok, tok_last;
248 	php_meta_tags_data md;
249 
250 	/* Initialize our structure */
251 	memset(&md, 0, sizeof(md));
252 
253 	/* Parse arguments */
254 	ZEND_PARSE_PARAMETERS_START(1, 2)
255 		Z_PARAM_PATH(filename, filename_len)
256 		Z_PARAM_OPTIONAL
257 		Z_PARAM_BOOL(use_include_path)
258 	ZEND_PARSE_PARAMETERS_END();
259 
260 	md.stream = php_stream_open_wrapper(filename, "rb",
261 			(use_include_path ? USE_PATH : 0) | REPORT_ERRORS,
262 			NULL);
263 	if (!md.stream)	{
264 		RETURN_FALSE;
265 	}
266 
267 	array_init(return_value);
268 
269 	tok_last = TOK_EOF;
270 
271 	while (!done && (tok = php_next_meta_token(&md)) != TOK_EOF) {
272 		if (tok == TOK_ID) {
273 			if (tok_last == TOK_OPENTAG) {
274 				md.in_meta = !strcasecmp("meta", md.token_data);
275 			} else if (tok_last == TOK_SLASH && in_tag) {
276 				if (strcasecmp("head", md.token_data) == 0) {
277 					/* We are done here! */
278 					done = 1;
279 				}
280 			} else if (tok_last == TOK_EQUAL && looking_for_val) {
281 				if (saw_name) {
282 					if (name) efree(name);
283 					/* Get the NAME attr (Single word attr, non-quoted) */
284 					temp = name = estrndup(md.token_data, md.token_len);
285 
286 					while (temp && *temp) {
287 						if (strchr(PHP_META_UNSAFE, *temp)) {
288 							*temp = '_';
289 						}
290 						temp++;
291 					}
292 
293 					have_name = 1;
294 				} else if (saw_content) {
295 					if (value) efree(value);
296 					value = estrndup(md.token_data, md.token_len);
297 					have_content = 1;
298 				}
299 
300 				looking_for_val = 0;
301 			} else {
302 				if (md.in_meta) {
303 					if (strcasecmp("name", md.token_data) == 0) {
304 						saw_name = 1;
305 						saw_content = 0;
306 						looking_for_val = 1;
307 					} else if (strcasecmp("content", md.token_data) == 0) {
308 						saw_name = 0;
309 						saw_content = 1;
310 						looking_for_val = 1;
311 					}
312 				}
313 			}
314 		} else if (tok == TOK_STRING && tok_last == TOK_EQUAL && looking_for_val) {
315 			if (saw_name) {
316 				if (name) efree(name);
317 				/* Get the NAME attr (Quoted single/double) */
318 				temp = name = estrndup(md.token_data, md.token_len);
319 
320 				while (temp && *temp) {
321 					if (strchr(PHP_META_UNSAFE, *temp)) {
322 						*temp = '_';
323 					}
324 					temp++;
325 				}
326 
327 				have_name = 1;
328 			} else if (saw_content) {
329 				if (value) efree(value);
330 				value = estrndup(md.token_data, md.token_len);
331 				have_content = 1;
332 			}
333 
334 			looking_for_val = 0;
335 		} else if (tok == TOK_OPENTAG) {
336 			if (looking_for_val) {
337 				looking_for_val = 0;
338 				have_name = saw_name = 0;
339 				have_content = saw_content = 0;
340 			}
341 			in_tag = 1;
342 		} else if (tok == TOK_CLOSETAG) {
343 			if (have_name) {
344 				/* For BC */
345 				zend_str_tolower(name, strlen(name));
346 				if (have_content) {
347 					add_assoc_string(return_value, name, value);
348 				} else {
349 					add_assoc_string(return_value, name, "");
350 				}
351 
352 				efree(name);
353 				if (value) efree(value);
354 			} else if (have_content) {
355 				efree(value);
356 			}
357 
358 			name = value = NULL;
359 
360 			/* Reset all of our flags */
361 			in_tag = looking_for_val = 0;
362 			have_name = saw_name = 0;
363 			have_content = saw_content = 0;
364 			md.in_meta = 0;
365 		}
366 
367 		tok_last = tok;
368 
369 		if (md.token_data)
370 			efree(md.token_data);
371 
372 		md.token_data = NULL;
373 	}
374 
375 	if (value) efree(value);
376 	if (name) efree(name);
377 	php_stream_close(md.stream);
378 }
379 /* }}} */
380 
381 /* {{{ Read the entire file into a string */
PHP_FUNCTION(file_get_contents)382 PHP_FUNCTION(file_get_contents)
383 {
384 	char *filename;
385 	size_t filename_len;
386 	bool use_include_path = 0;
387 	php_stream *stream;
388 	zend_long offset = 0;
389 	zend_long maxlen;
390 	bool maxlen_is_null = 1;
391 	zval *zcontext = NULL;
392 	php_stream_context *context = NULL;
393 	zend_string *contents;
394 
395 	/* Parse arguments */
396 	ZEND_PARSE_PARAMETERS_START(1, 5)
397 		Z_PARAM_PATH(filename, filename_len)
398 		Z_PARAM_OPTIONAL
399 		Z_PARAM_BOOL(use_include_path)
400 		Z_PARAM_RESOURCE_OR_NULL(zcontext)
401 		Z_PARAM_LONG(offset)
402 		Z_PARAM_LONG_OR_NULL(maxlen, maxlen_is_null)
403 	ZEND_PARSE_PARAMETERS_END();
404 
405 	if (maxlen_is_null) {
406 		maxlen = (ssize_t) PHP_STREAM_COPY_ALL;
407 	} else if (maxlen < 0) {
408 		zend_argument_value_error(5, "must be greater than or equal to 0");
409 		RETURN_THROWS();
410 	}
411 
412 	context = php_stream_context_from_zval(zcontext, 0);
413 
414 	stream = php_stream_open_wrapper_ex(filename, "rb",
415 				(use_include_path ? USE_PATH : 0) | REPORT_ERRORS,
416 				NULL, context);
417 	if (!stream) {
418 		RETURN_FALSE;
419 	}
420 
421 	/* disabling the read buffer allows doing the whole transfer
422 	   in just one read() system call */
423 	if (php_stream_is(stream, PHP_STREAM_IS_STDIO)) {
424 		php_stream_set_option(stream, PHP_STREAM_OPTION_READ_BUFFER, PHP_STREAM_BUFFER_NONE, NULL);
425 	}
426 
427 	if (offset != 0 && php_stream_seek(stream, offset, ((offset > 0) ? SEEK_SET : SEEK_END)) < 0) {
428 		php_error_docref(NULL, E_WARNING, "Failed to seek to position " ZEND_LONG_FMT " in the stream", offset);
429 		php_stream_close(stream);
430 		RETURN_FALSE;
431 	}
432 
433 	if ((contents = php_stream_copy_to_mem(stream, maxlen, 0)) != NULL) {
434 		RETVAL_STR(contents);
435 	} else {
436 		RETVAL_EMPTY_STRING();
437 	}
438 
439 	php_stream_close(stream);
440 }
441 /* }}} */
442 
443 /* {{{ Write/Create a file with contents data and return the number of bytes written */
PHP_FUNCTION(file_put_contents)444 PHP_FUNCTION(file_put_contents)
445 {
446 	php_stream *stream;
447 	char *filename;
448 	size_t filename_len;
449 	zval *data;
450 	ssize_t numbytes = 0;
451 	zend_long flags = 0;
452 	zval *zcontext = NULL;
453 	php_stream_context *context = NULL;
454 	php_stream *srcstream = NULL;
455 	char mode[3] = "wb";
456 
457 	ZEND_PARSE_PARAMETERS_START(2, 4)
458 		Z_PARAM_PATH(filename, filename_len)
459 		Z_PARAM_ZVAL(data)
460 		Z_PARAM_OPTIONAL
461 		Z_PARAM_LONG(flags)
462 		Z_PARAM_RESOURCE_OR_NULL(zcontext)
463 	ZEND_PARSE_PARAMETERS_END();
464 
465 	if (Z_TYPE_P(data) == IS_RESOURCE) {
466 		php_stream_from_zval(srcstream, data);
467 	}
468 
469 	context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT);
470 
471 	if (flags & PHP_FILE_APPEND) {
472 		mode[0] = 'a';
473 	} else if (flags & LOCK_EX) {
474 		/* check to make sure we are dealing with a regular file */
475 		if (php_memnstr(filename, "://", sizeof("://") - 1, filename + filename_len)) {
476 			if (strncasecmp(filename, "file://", sizeof("file://") - 1)) {
477 				php_error_docref(NULL, E_WARNING, "Exclusive locks may only be set for regular files");
478 				RETURN_FALSE;
479 			}
480 		}
481 		mode[0] = 'c';
482 	}
483 	mode[2] = '\0';
484 
485 	stream = php_stream_open_wrapper_ex(filename, mode, ((flags & PHP_FILE_USE_INCLUDE_PATH) ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
486 	if (stream == NULL) {
487 		RETURN_FALSE;
488 	}
489 
490 	if ((flags & LOCK_EX) && (!php_stream_supports_lock(stream) || php_stream_lock(stream, LOCK_EX))) {
491 		php_stream_close(stream);
492 		php_error_docref(NULL, E_WARNING, "Exclusive locks are not supported for this stream");
493 		RETURN_FALSE;
494 	}
495 
496 	if (mode[0] == 'c') {
497 		php_stream_truncate_set_size(stream, 0);
498 	}
499 
500 	switch (Z_TYPE_P(data)) {
501 		case IS_RESOURCE: {
502 			size_t len;
503 			if (php_stream_copy_to_stream_ex(srcstream, stream, PHP_STREAM_COPY_ALL, &len) != SUCCESS) {
504 				numbytes = -1;
505 			} else {
506 				if (len > ZEND_LONG_MAX) {
507 					php_error_docref(NULL, E_WARNING, "content truncated from %zu to " ZEND_LONG_FMT " bytes", len, ZEND_LONG_MAX);
508 					len = ZEND_LONG_MAX;
509 				}
510 				numbytes = len;
511 			}
512 			break;
513 		}
514 		case IS_NULL:
515 		case IS_LONG:
516 		case IS_DOUBLE:
517 		case IS_FALSE:
518 		case IS_TRUE:
519 			convert_to_string(data);
520 			ZEND_FALLTHROUGH;
521 		case IS_STRING:
522 			if (Z_STRLEN_P(data)) {
523 				numbytes = php_stream_write(stream, Z_STRVAL_P(data), Z_STRLEN_P(data));
524 				if (numbytes != -1 && numbytes != Z_STRLEN_P(data)) {
525 					php_error_docref(NULL, E_WARNING, "Only %zd of %zd bytes written, possibly out of free disk space", numbytes, Z_STRLEN_P(data));
526 					numbytes = -1;
527 				}
528 			}
529 			break;
530 
531 		case IS_ARRAY:
532 			if (zend_hash_num_elements(Z_ARRVAL_P(data))) {
533 				ssize_t bytes_written;
534 				zval *tmp;
535 
536 				ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(data), tmp) {
537 					zend_string *t;
538 					zend_string *str = zval_get_tmp_string(tmp, &t);
539 					if (ZSTR_LEN(str)) {
540 						numbytes += ZSTR_LEN(str);
541 						bytes_written = php_stream_write(stream, ZSTR_VAL(str), ZSTR_LEN(str));
542 						if (bytes_written != ZSTR_LEN(str)) {
543 							php_error_docref(NULL, E_WARNING, "Failed to write %zd bytes to %s", ZSTR_LEN(str), filename);
544 							zend_tmp_string_release(t);
545 							numbytes = -1;
546 							break;
547 						}
548 					}
549 					zend_tmp_string_release(t);
550 				} ZEND_HASH_FOREACH_END();
551 			}
552 			break;
553 
554 		case IS_OBJECT:
555 			if (Z_OBJ_HT_P(data) != NULL) {
556 				zval out;
557 
558 				if (zend_std_cast_object_tostring(Z_OBJ_P(data), &out, IS_STRING) == SUCCESS) {
559 					numbytes = php_stream_write(stream, Z_STRVAL(out), Z_STRLEN(out));
560 					if (numbytes != -1 && numbytes != Z_STRLEN(out)) {
561 						php_error_docref(NULL, E_WARNING, "Only %zd of %zd bytes written, possibly out of free disk space", numbytes, Z_STRLEN(out));
562 						numbytes = -1;
563 					}
564 					zval_ptr_dtor_str(&out);
565 					break;
566 				}
567 			}
568 			ZEND_FALLTHROUGH;
569 		default:
570 			numbytes = -1;
571 			break;
572 	}
573 	php_stream_close(stream);
574 
575 	if (numbytes < 0) {
576 		RETURN_FALSE;
577 	}
578 
579 	RETURN_LONG(numbytes);
580 }
581 /* }}} */
582 
583 #define PHP_FILE_BUF_SIZE	80
584 
585 /* {{{ Read entire file into an array */
PHP_FUNCTION(file)586 PHP_FUNCTION(file)
587 {
588 	char *filename;
589 	size_t filename_len;
590 	char *p, *s, *e;
591 	int i = 0;
592 	char eol_marker = '\n';
593 	zend_long flags = 0;
594 	bool use_include_path;
595 	bool include_new_line;
596 	bool skip_blank_lines;
597 	php_stream *stream;
598 	zval *zcontext = NULL;
599 	php_stream_context *context = NULL;
600 	zend_string *target_buf;
601 
602 	/* Parse arguments */
603 	ZEND_PARSE_PARAMETERS_START(1, 3)
604 		Z_PARAM_PATH(filename, filename_len)
605 		Z_PARAM_OPTIONAL
606 		Z_PARAM_LONG(flags)
607 		Z_PARAM_RESOURCE_OR_NULL(zcontext)
608 	ZEND_PARSE_PARAMETERS_END();
609 
610 	if ((flags & ~(PHP_FILE_USE_INCLUDE_PATH | PHP_FILE_IGNORE_NEW_LINES | PHP_FILE_SKIP_EMPTY_LINES | PHP_FILE_NO_DEFAULT_CONTEXT)) != 0) {
611 		zend_argument_value_error(2, "must be a valid flag value");
612 		RETURN_THROWS();
613 	}
614 
615 	use_include_path = flags & PHP_FILE_USE_INCLUDE_PATH;
616 	include_new_line = !(flags & PHP_FILE_IGNORE_NEW_LINES);
617 	skip_blank_lines = flags & PHP_FILE_SKIP_EMPTY_LINES;
618 
619 	context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT);
620 
621 	stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
622 	if (!stream) {
623 		RETURN_FALSE;
624 	}
625 
626 	/* Initialize return array */
627 	array_init(return_value);
628 
629 	if ((target_buf = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0)) != NULL) {
630 		s = ZSTR_VAL(target_buf);
631 		e = ZSTR_VAL(target_buf) + ZSTR_LEN(target_buf);
632 
633 		if (!(p = (char*)php_stream_locate_eol(stream, target_buf))) {
634 			p = e;
635 			goto parse_eol;
636 		}
637 
638 		if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) {
639 			eol_marker = '\r';
640 		}
641 
642 		/* for performance reasons the code is duplicated, so that the if (include_new_line)
643 		 * will not need to be done for every single line in the file. */
644 		if (include_new_line) {
645 			do {
646 				p++;
647 parse_eol:
648 				add_index_stringl(return_value, i++, s, p-s);
649 				s = p;
650 			} while ((p = memchr(p, eol_marker, (e-p))));
651 		} else {
652 			do {
653 				int windows_eol = 0;
654 				if (p != ZSTR_VAL(target_buf) && eol_marker == '\n' && *(p - 1) == '\r') {
655 					windows_eol++;
656 				}
657 				if (skip_blank_lines && !(p-s-windows_eol)) {
658 					s = ++p;
659 					continue;
660 				}
661 				add_index_stringl(return_value, i++, s, p-s-windows_eol);
662 				s = ++p;
663 			} while ((p = memchr(p, eol_marker, (e-p))));
664 		}
665 
666 		/* handle any leftovers of files without new lines */
667 		if (s != e) {
668 			p = e;
669 			goto parse_eol;
670 		}
671 	}
672 
673 	if (target_buf) {
674 		zend_string_free(target_buf);
675 	}
676 	php_stream_close(stream);
677 }
678 /* }}} */
679 
680 /* {{{ Create a unique filename in a directory */
PHP_FUNCTION(tempnam)681 PHP_FUNCTION(tempnam)
682 {
683 	char *dir, *prefix;
684 	size_t dir_len, prefix_len;
685 	zend_string *opened_path;
686 	int fd;
687 	zend_string *p;
688 
689 	ZEND_PARSE_PARAMETERS_START(2, 2)
690 		Z_PARAM_PATH(dir, dir_len)
691 		Z_PARAM_PATH(prefix, prefix_len)
692 	ZEND_PARSE_PARAMETERS_END();
693 
694 	p = php_basename(prefix, prefix_len, NULL, 0);
695 	if (ZSTR_LEN(p) >= 64) {
696 		ZSTR_VAL(p)[63] = '\0';
697 	}
698 
699 	RETVAL_FALSE;
700 
701 	if ((fd = php_open_temporary_fd_ex(dir, ZSTR_VAL(p), &opened_path, PHP_TMP_FILE_OPEN_BASEDIR_CHECK_ALWAYS)) >= 0) {
702 		close(fd);
703 		RETVAL_STR(opened_path);
704 	}
705 	zend_string_release_ex(p, 0);
706 }
707 /* }}} */
708 
709 /* {{{ Create a temporary file that will be deleted automatically after use */
PHP_FUNCTION(tmpfile)710 PHP_FUNCTION(tmpfile)
711 {
712 	php_stream *stream;
713 
714 	ZEND_PARSE_PARAMETERS_NONE();
715 
716 	stream = php_stream_fopen_tmpfile();
717 
718 	if (stream) {
719 		php_stream_to_zval(stream, return_value);
720 	} else {
721 		RETURN_FALSE;
722 	}
723 }
724 /* }}} */
725 
726 /* {{{ Open a file or a URL and return a file pointer */
PHP_FUNCTION(fopen)727 PHP_FUNCTION(fopen)
728 {
729 	char *filename, *mode;
730 	size_t filename_len, mode_len;
731 	bool use_include_path = 0;
732 	zval *zcontext = NULL;
733 	php_stream *stream;
734 	php_stream_context *context = NULL;
735 
736 	ZEND_PARSE_PARAMETERS_START(2, 4)
737 		Z_PARAM_PATH(filename, filename_len)
738 		Z_PARAM_STRING(mode, mode_len)
739 		Z_PARAM_OPTIONAL
740 		Z_PARAM_BOOL(use_include_path)
741 		Z_PARAM_RESOURCE_OR_NULL(zcontext)
742 	ZEND_PARSE_PARAMETERS_END();
743 
744 	context = php_stream_context_from_zval(zcontext, 0);
745 
746 	stream = php_stream_open_wrapper_ex(filename, mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
747 
748 	if (stream == NULL) {
749 		RETURN_FALSE;
750 	}
751 
752 	php_stream_to_zval(stream, return_value);
753 }
754 /* }}} */
755 
756 /* {{{ Close an open file pointer */
PHP_FUNCTION(fclose)757 PHPAPI PHP_FUNCTION(fclose)
758 {
759 	zval *res;
760 	php_stream *stream;
761 
762 	ZEND_PARSE_PARAMETERS_START(1, 1)
763 		Z_PARAM_RESOURCE(res)
764 	ZEND_PARSE_PARAMETERS_END();
765 
766 	PHP_STREAM_FROM_ZVAL(stream, res);
767 
768 	if ((stream->flags & PHP_STREAM_FLAG_NO_FCLOSE) != 0) {
769 		php_error_docref(NULL, E_WARNING, ZEND_LONG_FMT " is not a valid stream resource", stream->res->handle);
770 		RETURN_FALSE;
771 	}
772 
773 	php_stream_free(stream,
774 		PHP_STREAM_FREE_KEEP_RSRC |
775 		(stream->is_persistent ? PHP_STREAM_FREE_CLOSE_PERSISTENT : PHP_STREAM_FREE_CLOSE));
776 
777 	RETURN_TRUE;
778 }
779 /* }}} */
780 
781 /* {{{ Execute a command and open either a read or a write pipe to it */
PHP_FUNCTION(popen)782 PHP_FUNCTION(popen)
783 {
784 	char *command, *mode;
785 	size_t command_len, mode_len;
786 	FILE *fp;
787 	php_stream *stream;
788 	char *posix_mode;
789 
790 	ZEND_PARSE_PARAMETERS_START(2, 2)
791 		Z_PARAM_PATH(command, command_len)
792 		Z_PARAM_STRING(mode, mode_len)
793 	ZEND_PARSE_PARAMETERS_END();
794 
795 	posix_mode = estrndup(mode, mode_len);
796 #ifndef PHP_WIN32
797 	{
798 		char *z = memchr(posix_mode, 'b', mode_len);
799 		if (z) {
800 			memmove(z, z + 1, mode_len - (z - posix_mode));
801 			mode_len--;
802 		}
803 	}
804 #endif
805 
806 	/* Musl only partially validates the mode. Manually check it to ensure consistent behavior. */
807 	if (mode_len > 2 ||
808 		(mode_len == 1 && (*posix_mode != 'r' && *posix_mode != 'w')) ||
809 		(mode_len == 2 && (memcmp(posix_mode, "rb", 2) && memcmp(posix_mode, "wb", 2)))
810 	) {
811 		zend_argument_value_error(2, "must be one of \"r\", \"rb\", \"w\", or \"wb\"");
812 		efree(posix_mode);
813 		RETURN_THROWS();
814 	}
815 
816 	fp = VCWD_POPEN(command, posix_mode);
817 	if (!fp) {
818 		php_error_docref2(NULL, command, posix_mode, E_WARNING, "%s", strerror(errno));
819 		efree(posix_mode);
820 		RETURN_FALSE;
821 	}
822 
823 	stream = php_stream_fopen_from_pipe(fp, mode);
824 
825 	if (stream == NULL)	{
826 		php_error_docref2(NULL, command, mode, E_WARNING, "%s", strerror(errno));
827 		RETVAL_FALSE;
828 	} else {
829 		php_stream_to_zval(stream, return_value);
830 	}
831 
832 	efree(posix_mode);
833 }
834 /* }}} */
835 
836 /* {{{ Close a file pointer opened by popen() */
PHP_FUNCTION(pclose)837 PHP_FUNCTION(pclose)
838 {
839 	zval *res;
840 	php_stream *stream;
841 
842 	ZEND_PARSE_PARAMETERS_START(1, 1)
843 		Z_PARAM_RESOURCE(res)
844 	ZEND_PARSE_PARAMETERS_END();
845 
846 	PHP_STREAM_FROM_ZVAL(stream, res);
847 
848 	FG(pclose_wait) = 1;
849 	zend_list_close(stream->res);
850 	FG(pclose_wait) = 0;
851 	RETURN_LONG(FG(pclose_ret));
852 }
853 /* }}} */
854 
855 /* {{{ Test for end-of-file on a file pointer */
PHP_FUNCTION(feof)856 PHPAPI PHP_FUNCTION(feof)
857 {
858 	zval *res;
859 	php_stream *stream;
860 
861 	ZEND_PARSE_PARAMETERS_START(1, 1)
862 		Z_PARAM_RESOURCE(res)
863 	ZEND_PARSE_PARAMETERS_END();
864 
865 	PHP_STREAM_FROM_ZVAL(stream, res);
866 
867 	if (php_stream_eof(stream)) {
868 		RETURN_TRUE;
869 	} else {
870 		RETURN_FALSE;
871 	}
872 }
873 /* }}} */
874 
875 /* {{{ Get a line from file pointer */
PHP_FUNCTION(fgets)876 PHPAPI PHP_FUNCTION(fgets)
877 {
878 	zval *res;
879 	zend_long len = 1024;
880 	bool len_is_null = 1;
881 	char *buf = NULL;
882 	size_t line_len = 0;
883 	zend_string *str;
884 	php_stream *stream;
885 
886 	ZEND_PARSE_PARAMETERS_START(1, 2)
887 		Z_PARAM_RESOURCE(res)
888 		Z_PARAM_OPTIONAL
889 		Z_PARAM_LONG_OR_NULL(len, len_is_null)
890 	ZEND_PARSE_PARAMETERS_END();
891 
892 	PHP_STREAM_FROM_ZVAL(stream, res);
893 
894 	if (len_is_null) {
895 		/* ask streams to give us a buffer of an appropriate size */
896 		buf = php_stream_get_line(stream, NULL, 0, &line_len);
897 		if (buf == NULL) {
898 			RETURN_FALSE;
899 		}
900 		// TODO: avoid reallocation ???
901 		RETVAL_STRINGL(buf, line_len);
902 		efree(buf);
903 	} else {
904 		if (len <= 0) {
905 			zend_argument_value_error(2, "must be greater than 0");
906 			RETURN_THROWS();
907 		}
908 
909 		str = zend_string_alloc(len, 0);
910 		if (php_stream_get_line(stream, ZSTR_VAL(str), len, &line_len) == NULL) {
911 			zend_string_efree(str);
912 			RETURN_FALSE;
913 		}
914 		/* resize buffer if it's much larger than the result.
915 		 * Only needed if the user requested a buffer size. */
916 		if (line_len < (size_t)len / 2) {
917 			str = zend_string_truncate(str, line_len, 0);
918 		} else {
919 			ZSTR_LEN(str) = line_len;
920 		}
921 		RETURN_NEW_STR(str);
922 	}
923 }
924 /* }}} */
925 
926 /* {{{ Get a character from file pointer */
PHP_FUNCTION(fgetc)927 PHPAPI PHP_FUNCTION(fgetc)
928 {
929 	zval *res;
930 	php_stream *stream;
931 
932 	ZEND_PARSE_PARAMETERS_START(1, 1)
933 		Z_PARAM_RESOURCE(res)
934 	ZEND_PARSE_PARAMETERS_END();
935 
936 	PHP_STREAM_FROM_ZVAL(stream, res);
937 
938 	int result = php_stream_getc(stream);
939 
940 	if (result == EOF) {
941 		RETVAL_FALSE;
942 	} else {
943 		RETURN_CHAR(result);
944 	}
945 }
946 /* }}} */
947 
948 /* {{{ Implements a mostly ANSI compatible fscanf() */
PHP_FUNCTION(fscanf)949 PHP_FUNCTION(fscanf)
950 {
951 	int result, argc = 0;
952 	size_t format_len;
953 	zval *args = NULL;
954 	zval *file_handle;
955 	char *buf, *format;
956 	size_t len;
957 	void *what;
958 
959 	ZEND_PARSE_PARAMETERS_START(2, -1)
960 		Z_PARAM_RESOURCE(file_handle)
961 		Z_PARAM_STRING(format, format_len)
962 		Z_PARAM_VARIADIC('*', args, argc)
963 	ZEND_PARSE_PARAMETERS_END();
964 
965 	what = zend_fetch_resource2(Z_RES_P(file_handle), "File-Handle", php_file_le_stream(), php_file_le_pstream());
966 
967 	/* we can't do a ZEND_VERIFY_RESOURCE(what), otherwise we end up
968 	 * with a leak if we have an invalid filehandle. This needs changing
969 	 * if the code behind ZEND_VERIFY_RESOURCE changed. - cc */
970 	if (!what) {
971 		RETURN_THROWS();
972 	}
973 
974 	buf = php_stream_get_line((php_stream *) what, NULL, 0, &len);
975 	if (buf == NULL) {
976 		RETURN_FALSE;
977 	}
978 
979 	result = php_sscanf_internal(buf, format, argc, args, 0, return_value);
980 
981 	efree(buf);
982 
983 	if (SCAN_ERROR_WRONG_PARAM_COUNT == result) {
984 		WRONG_PARAM_COUNT;
985 	}
986 }
987 /* }}} */
988 
989 /* {{{ Binary-safe file write */
PHP_FUNCTION(fwrite)990 PHPAPI PHP_FUNCTION(fwrite)
991 {
992 	zval *res;
993 	char *input;
994 	size_t inputlen;
995 	ssize_t ret;
996 	size_t num_bytes;
997 	zend_long maxlen = 0;
998 	bool maxlen_is_null = 1;
999 	php_stream *stream;
1000 
1001 	ZEND_PARSE_PARAMETERS_START(2, 3)
1002 		Z_PARAM_RESOURCE(res)
1003 		Z_PARAM_STRING(input, inputlen)
1004 		Z_PARAM_OPTIONAL
1005 		Z_PARAM_LONG_OR_NULL(maxlen, maxlen_is_null)
1006 	ZEND_PARSE_PARAMETERS_END();
1007 
1008 	if (maxlen_is_null) {
1009 		num_bytes = inputlen;
1010 	} else if (maxlen <= 0) {
1011 		num_bytes = 0;
1012 	} else {
1013 		num_bytes = MIN((size_t) maxlen, inputlen);
1014 	}
1015 
1016 	if (!num_bytes) {
1017 		RETURN_LONG(0);
1018 	}
1019 
1020 	PHP_STREAM_FROM_ZVAL(stream, res);
1021 
1022 	ret = php_stream_write(stream, input, num_bytes);
1023 	if (ret < 0) {
1024 		RETURN_FALSE;
1025 	}
1026 
1027 	RETURN_LONG(ret);
1028 }
1029 /* }}} */
1030 
1031 /* {{{ Flushes output */
PHP_FUNCTION(fflush)1032 PHPAPI PHP_FUNCTION(fflush)
1033 {
1034 	zval *res;
1035 	int ret;
1036 	php_stream *stream;
1037 
1038 	ZEND_PARSE_PARAMETERS_START(1, 1)
1039 		Z_PARAM_RESOURCE(res)
1040 	ZEND_PARSE_PARAMETERS_END();
1041 
1042 	PHP_STREAM_FROM_ZVAL(stream, res);
1043 
1044 	ret = php_stream_flush(stream);
1045 	if (ret) {
1046 		RETURN_FALSE;
1047 	}
1048 	RETURN_TRUE;
1049 }
1050 /* }}} */
1051 
1052 /* {{{ Rewind the position of a file pointer */
PHP_FUNCTION(rewind)1053 PHPAPI PHP_FUNCTION(rewind)
1054 {
1055 	zval *res;
1056 	php_stream *stream;
1057 
1058 	ZEND_PARSE_PARAMETERS_START(1, 1)
1059 		Z_PARAM_RESOURCE(res)
1060 	ZEND_PARSE_PARAMETERS_END();
1061 
1062 	PHP_STREAM_FROM_ZVAL(stream, res);
1063 
1064 	if (-1 == php_stream_rewind(stream)) {
1065 		RETURN_FALSE;
1066 	}
1067 	RETURN_TRUE;
1068 }
1069 /* }}} */
1070 
1071 /* {{{ Get file pointer's read/write position */
PHP_FUNCTION(ftell)1072 PHPAPI PHP_FUNCTION(ftell)
1073 {
1074 	zval *res;
1075 	zend_long ret;
1076 	php_stream *stream;
1077 
1078 	ZEND_PARSE_PARAMETERS_START(1, 1)
1079 		Z_PARAM_RESOURCE(res)
1080 	ZEND_PARSE_PARAMETERS_END();
1081 
1082 	PHP_STREAM_FROM_ZVAL(stream, res);
1083 
1084 	ret = php_stream_tell(stream);
1085 	if (ret == -1)	{
1086 		RETURN_FALSE;
1087 	}
1088 	RETURN_LONG(ret);
1089 }
1090 /* }}} */
1091 
1092 /* {{{ Seek on a file pointer */
PHP_FUNCTION(fseek)1093 PHPAPI PHP_FUNCTION(fseek)
1094 {
1095 	zval *res;
1096 	zend_long offset, whence = SEEK_SET;
1097 	php_stream *stream;
1098 
1099 	ZEND_PARSE_PARAMETERS_START(2, 3)
1100 		Z_PARAM_RESOURCE(res)
1101 		Z_PARAM_LONG(offset)
1102 		Z_PARAM_OPTIONAL
1103 		Z_PARAM_LONG(whence)
1104 	ZEND_PARSE_PARAMETERS_END();
1105 
1106 	PHP_STREAM_FROM_ZVAL(stream, res);
1107 
1108 	RETURN_LONG(php_stream_seek(stream, offset, (int) whence));
1109 }
1110 /* }}} */
1111 
1112 /* {{{ php_mkdir */
1113 
1114 /* DEPRECATED APIs: Use php_stream_mkdir() instead */
php_mkdir_ex(const char * dir,zend_long mode,int options)1115 PHPAPI int php_mkdir_ex(const char *dir, zend_long mode, int options)
1116 {
1117 	int ret;
1118 
1119 	if (php_check_open_basedir(dir)) {
1120 		return -1;
1121 	}
1122 
1123 	if ((ret = VCWD_MKDIR(dir, (mode_t)mode)) < 0 && (options & REPORT_ERRORS)) {
1124 		php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
1125 	}
1126 
1127 	return ret;
1128 }
1129 
php_mkdir(const char * dir,zend_long mode)1130 PHPAPI int php_mkdir(const char *dir, zend_long mode)
1131 {
1132 	return php_mkdir_ex(dir, mode, REPORT_ERRORS);
1133 }
1134 /* }}} */
1135 
1136 /* {{{ Create a directory */
PHP_FUNCTION(mkdir)1137 PHP_FUNCTION(mkdir)
1138 {
1139 	char *dir;
1140 	size_t dir_len;
1141 	zval *zcontext = NULL;
1142 	zend_long mode = 0777;
1143 	bool recursive = 0;
1144 	php_stream_context *context;
1145 
1146 	ZEND_PARSE_PARAMETERS_START(1, 4)
1147 		Z_PARAM_PATH(dir, dir_len)
1148 		Z_PARAM_OPTIONAL
1149 		Z_PARAM_LONG(mode)
1150 		Z_PARAM_BOOL(recursive)
1151 		Z_PARAM_RESOURCE_OR_NULL(zcontext)
1152 	ZEND_PARSE_PARAMETERS_END();
1153 
1154 	context = php_stream_context_from_zval(zcontext, 0);
1155 
1156 	RETURN_BOOL(php_stream_mkdir(dir, (int)mode, (recursive ? PHP_STREAM_MKDIR_RECURSIVE : 0) | REPORT_ERRORS, context));
1157 }
1158 /* }}} */
1159 
1160 /* {{{ Remove a directory */
PHP_FUNCTION(rmdir)1161 PHP_FUNCTION(rmdir)
1162 {
1163 	char *dir;
1164 	size_t dir_len;
1165 	zval *zcontext = NULL;
1166 	php_stream_context *context;
1167 
1168 	ZEND_PARSE_PARAMETERS_START(1, 2)
1169 		Z_PARAM_PATH(dir, dir_len)
1170 		Z_PARAM_OPTIONAL
1171 		Z_PARAM_RESOURCE_OR_NULL(zcontext)
1172 	ZEND_PARSE_PARAMETERS_END();
1173 
1174 	context = php_stream_context_from_zval(zcontext, 0);
1175 
1176 	RETURN_BOOL(php_stream_rmdir(dir, REPORT_ERRORS, context));
1177 }
1178 /* }}} */
1179 
1180 /* {{{ Output a file or a URL */
PHP_FUNCTION(readfile)1181 PHP_FUNCTION(readfile)
1182 {
1183 	char *filename;
1184 	size_t filename_len;
1185 	size_t size = 0;
1186 	bool use_include_path = 0;
1187 	zval *zcontext = NULL;
1188 	php_stream *stream;
1189 	php_stream_context *context = NULL;
1190 
1191 	ZEND_PARSE_PARAMETERS_START(1, 3)
1192 		Z_PARAM_PATH(filename, filename_len)
1193 		Z_PARAM_OPTIONAL
1194 		Z_PARAM_BOOL(use_include_path)
1195 		Z_PARAM_RESOURCE_OR_NULL(zcontext)
1196 	ZEND_PARSE_PARAMETERS_END();
1197 
1198 	context = php_stream_context_from_zval(zcontext, 0);
1199 
1200 	stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
1201 	if (stream) {
1202 		size = php_stream_passthru(stream);
1203 		php_stream_close(stream);
1204 		RETURN_LONG(size);
1205 	}
1206 
1207 	RETURN_FALSE;
1208 }
1209 /* }}} */
1210 
1211 /* {{{ Return or change the umask */
PHP_FUNCTION(umask)1212 PHP_FUNCTION(umask)
1213 {
1214 	zend_long mask = 0;
1215 	bool mask_is_null = 1;
1216 	int oldumask;
1217 
1218 	ZEND_PARSE_PARAMETERS_START(0, 1)
1219 		Z_PARAM_OPTIONAL
1220 		Z_PARAM_LONG_OR_NULL(mask, mask_is_null)
1221 	ZEND_PARSE_PARAMETERS_END();
1222 
1223 	oldumask = umask(077);
1224 
1225 	if (BG(umask) == -1) {
1226 		BG(umask) = oldumask;
1227 	}
1228 
1229 	if (mask_is_null) {
1230 		umask(oldumask);
1231 	} else {
1232 		umask((int) mask);
1233 	}
1234 
1235 	RETURN_LONG(oldumask);
1236 }
1237 /* }}} */
1238 
1239 /* {{{ Output all remaining data from a file pointer */
PHP_FUNCTION(fpassthru)1240 PHPAPI PHP_FUNCTION(fpassthru)
1241 {
1242 	zval *res;
1243 	size_t size;
1244 	php_stream *stream;
1245 
1246 	ZEND_PARSE_PARAMETERS_START(1, 1)
1247 		Z_PARAM_RESOURCE(res)
1248 	ZEND_PARSE_PARAMETERS_END();
1249 
1250 	PHP_STREAM_FROM_ZVAL(stream, res);
1251 
1252 	size = php_stream_passthru(stream);
1253 	RETURN_LONG(size);
1254 }
1255 /* }}} */
1256 
1257 /* {{{ Rename a file */
PHP_FUNCTION(rename)1258 PHP_FUNCTION(rename)
1259 {
1260 	char *old_name, *new_name;
1261 	size_t old_name_len, new_name_len;
1262 	zval *zcontext = NULL;
1263 	php_stream_wrapper *wrapper;
1264 	php_stream_context *context;
1265 
1266 	ZEND_PARSE_PARAMETERS_START(2, 3)
1267 		Z_PARAM_PATH(old_name, old_name_len)
1268 		Z_PARAM_PATH(new_name, new_name_len)
1269 		Z_PARAM_OPTIONAL
1270 		Z_PARAM_RESOURCE_OR_NULL(zcontext)
1271 	ZEND_PARSE_PARAMETERS_END();
1272 
1273 	wrapper = php_stream_locate_url_wrapper(old_name, NULL, 0);
1274 
1275 	if (!wrapper || !wrapper->wops) {
1276 		php_error_docref(NULL, E_WARNING, "Unable to locate stream wrapper");
1277 		RETURN_FALSE;
1278 	}
1279 
1280 	if (!wrapper->wops->rename) {
1281 		php_error_docref(NULL, E_WARNING, "%s wrapper does not support renaming", wrapper->wops->label ? wrapper->wops->label : "Source");
1282 		RETURN_FALSE;
1283 	}
1284 
1285 	if (wrapper != php_stream_locate_url_wrapper(new_name, NULL, 0)) {
1286 		php_error_docref(NULL, E_WARNING, "Cannot rename a file across wrapper types");
1287 		RETURN_FALSE;
1288 	}
1289 
1290 	context = php_stream_context_from_zval(zcontext, 0);
1291 
1292 	RETURN_BOOL(wrapper->wops->rename(wrapper, old_name, new_name, 0, context));
1293 }
1294 /* }}} */
1295 
1296 /* {{{ Delete a file */
PHP_FUNCTION(unlink)1297 PHP_FUNCTION(unlink)
1298 {
1299 	char *filename;
1300 	size_t filename_len;
1301 	php_stream_wrapper *wrapper;
1302 	zval *zcontext = NULL;
1303 	php_stream_context *context = NULL;
1304 
1305 	ZEND_PARSE_PARAMETERS_START(1, 2)
1306 		Z_PARAM_PATH(filename, filename_len)
1307 		Z_PARAM_OPTIONAL
1308 		Z_PARAM_RESOURCE_OR_NULL(zcontext)
1309 	ZEND_PARSE_PARAMETERS_END();
1310 
1311 	context = php_stream_context_from_zval(zcontext, 0);
1312 
1313 	wrapper = php_stream_locate_url_wrapper(filename, NULL, 0);
1314 
1315 	if (!wrapper || !wrapper->wops) {
1316 		php_error_docref(NULL, E_WARNING, "Unable to locate stream wrapper");
1317 		RETURN_FALSE;
1318 	}
1319 
1320 	if (!wrapper->wops->unlink) {
1321 		php_error_docref(NULL, E_WARNING, "%s does not allow unlinking", wrapper->wops->label ? wrapper->wops->label : "Wrapper");
1322 		RETURN_FALSE;
1323 	}
1324 	RETURN_BOOL(wrapper->wops->unlink(wrapper, filename, REPORT_ERRORS, context));
1325 }
1326 /* }}} */
1327 
PHP_FUNCTION(fsync)1328 PHP_FUNCTION(fsync)
1329 {
1330 	zval *res;
1331 	php_stream *stream;
1332 
1333 	ZEND_PARSE_PARAMETERS_START(1, 1)
1334 		Z_PARAM_RESOURCE(res)
1335 	ZEND_PARSE_PARAMETERS_END();
1336 
1337 	PHP_STREAM_FROM_ZVAL(stream, res);
1338 
1339 	if (!php_stream_sync_supported(stream)) {
1340 		php_error_docref(NULL, E_WARNING, "Can't fsync this stream!");
1341 		RETURN_FALSE;
1342 	}
1343 
1344 	RETURN_BOOL(php_stream_sync(stream, /* data_only */ 0) == 0);
1345 }
1346 
PHP_FUNCTION(fdatasync)1347 PHP_FUNCTION(fdatasync)
1348 {
1349 	zval *res;
1350 	php_stream *stream;
1351 
1352 	ZEND_PARSE_PARAMETERS_START(1, 1)
1353 		Z_PARAM_RESOURCE(res)
1354 	ZEND_PARSE_PARAMETERS_END();
1355 
1356 	PHP_STREAM_FROM_ZVAL(stream, res);
1357 
1358 	if (!php_stream_sync_supported(stream)) {
1359 		php_error_docref(NULL, E_WARNING, "Can't fsync this stream!");
1360 		RETURN_FALSE;
1361 	}
1362 
1363 	RETURN_BOOL(php_stream_sync(stream, /* data_only */ 1) == 0);
1364 }
1365 
1366 /* {{{ Truncate file to 'size' length */
PHP_FUNCTION(ftruncate)1367 PHP_FUNCTION(ftruncate)
1368 {
1369 	zval *fp;
1370 	zend_long size;
1371 	php_stream *stream;
1372 
1373 	ZEND_PARSE_PARAMETERS_START(2, 2)
1374 		Z_PARAM_RESOURCE(fp)
1375 		Z_PARAM_LONG(size)
1376 	ZEND_PARSE_PARAMETERS_END();
1377 
1378 	if (size < 0) {
1379 		zend_argument_value_error(2, "must be greater than or equal to 0");
1380 		RETURN_THROWS();
1381 	}
1382 
1383 	PHP_STREAM_FROM_ZVAL(stream, fp);
1384 
1385 	if (!php_stream_truncate_supported(stream)) {
1386 		php_error_docref(NULL, E_WARNING, "Can't truncate this stream!");
1387 		RETURN_FALSE;
1388 	}
1389 
1390 	RETURN_BOOL(0 == php_stream_truncate_set_size(stream, size));
1391 }
1392 /* }}} */
php_fstat(php_stream * stream,zval * return_value)1393 PHPAPI void php_fstat(php_stream *stream, zval *return_value)
1394 {
1395 	php_stream_statbuf stat_ssb;
1396 	zval stat_dev, stat_ino, stat_mode, stat_nlink, stat_uid, stat_gid, stat_rdev,
1397 		 stat_size, stat_atime, stat_mtime, stat_ctime, stat_blksize, stat_blocks;
1398 	char *stat_sb_names[13] = {
1399 		"dev", "ino", "mode", "nlink", "uid", "gid", "rdev",
1400 		"size", "atime", "mtime", "ctime", "blksize", "blocks"
1401 	};
1402 
1403 	if (php_stream_stat(stream, &stat_ssb)) {
1404 		RETURN_FALSE;
1405 	}
1406 
1407 	array_init(return_value);
1408 
1409 	ZVAL_LONG(&stat_dev, stat_ssb.sb.st_dev);
1410 	ZVAL_LONG(&stat_ino, stat_ssb.sb.st_ino);
1411 	ZVAL_LONG(&stat_mode, stat_ssb.sb.st_mode);
1412 	ZVAL_LONG(&stat_nlink, stat_ssb.sb.st_nlink);
1413 	ZVAL_LONG(&stat_uid, stat_ssb.sb.st_uid);
1414 	ZVAL_LONG(&stat_gid, stat_ssb.sb.st_gid);
1415 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1416 	ZVAL_LONG(&stat_rdev, stat_ssb.sb.st_rdev);
1417 #else
1418 	ZVAL_LONG(&stat_rdev, -1);
1419 #endif
1420 	ZVAL_LONG(&stat_size, stat_ssb.sb.st_size);
1421 	ZVAL_LONG(&stat_atime, stat_ssb.sb.st_atime);
1422 	ZVAL_LONG(&stat_mtime, stat_ssb.sb.st_mtime);
1423 	ZVAL_LONG(&stat_ctime, stat_ssb.sb.st_ctime);
1424 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1425 	ZVAL_LONG(&stat_blksize, stat_ssb.sb.st_blksize);
1426 #else
1427 	ZVAL_LONG(&stat_blksize,-1);
1428 #endif
1429 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1430 	ZVAL_LONG(&stat_blocks, stat_ssb.sb.st_blocks);
1431 #else
1432 	ZVAL_LONG(&stat_blocks,-1);
1433 #endif
1434 	/* Store numeric indexes in proper order */
1435 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_dev);
1436 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_ino);
1437 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_mode);
1438 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_nlink);
1439 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_uid);
1440 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_gid);
1441 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_rdev);
1442 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_size);
1443 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_atime);
1444 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_mtime);
1445 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_ctime);
1446 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_blksize);
1447 	zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &stat_blocks);
1448 
1449 	/* Store string indexes referencing the same zval*/
1450 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[0], strlen(stat_sb_names[0]), &stat_dev);
1451 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[1], strlen(stat_sb_names[1]), &stat_ino);
1452 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[2], strlen(stat_sb_names[2]), &stat_mode);
1453 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[3], strlen(stat_sb_names[3]), &stat_nlink);
1454 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[4], strlen(stat_sb_names[4]), &stat_uid);
1455 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[5], strlen(stat_sb_names[5]), &stat_gid);
1456 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[6], strlen(stat_sb_names[6]), &stat_rdev);
1457 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[7], strlen(stat_sb_names[7]), &stat_size);
1458 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[8], strlen(stat_sb_names[8]), &stat_atime);
1459 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[9], strlen(stat_sb_names[9]), &stat_mtime);
1460 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[10], strlen(stat_sb_names[10]), &stat_ctime);
1461 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[11], strlen(stat_sb_names[11]), &stat_blksize);
1462 	zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[12], strlen(stat_sb_names[12]), &stat_blocks);
1463 }
1464 
1465 /* {{{ Stat() on a filehandle */
PHP_FUNCTION(fstat)1466 PHP_FUNCTION(fstat)
1467 {
1468 	zval *fp;
1469 	php_stream *stream;
1470 
1471 	ZEND_PARSE_PARAMETERS_START(1, 1)
1472 		Z_PARAM_RESOURCE(fp)
1473 	ZEND_PARSE_PARAMETERS_END();
1474 
1475 	PHP_STREAM_FROM_ZVAL(stream, fp);
1476 
1477 	php_fstat(stream, return_value);
1478 }
1479 /* }}} */
1480 
1481 /* {{{ Copy a file */
PHP_FUNCTION(copy)1482 PHP_FUNCTION(copy)
1483 {
1484 	char *source, *target;
1485 	size_t source_len, target_len;
1486 	zval *zcontext = NULL;
1487 	php_stream_context *context;
1488 
1489 	ZEND_PARSE_PARAMETERS_START(2, 3)
1490 		Z_PARAM_PATH(source, source_len)
1491 		Z_PARAM_PATH(target, target_len)
1492 		Z_PARAM_OPTIONAL
1493 		Z_PARAM_RESOURCE_OR_NULL(zcontext)
1494 	ZEND_PARSE_PARAMETERS_END();
1495 
1496 	if (php_stream_locate_url_wrapper(source, NULL, 0) == &php_plain_files_wrapper && php_check_open_basedir(source)) {
1497 		RETURN_FALSE;
1498 	}
1499 
1500 	context = php_stream_context_from_zval(zcontext, 0);
1501 
1502 	if (php_copy_file_ctx(source, target, 0, context) == SUCCESS) {
1503 		RETURN_TRUE;
1504 	} else {
1505 		RETURN_FALSE;
1506 	}
1507 }
1508 /* }}} */
1509 
1510 /* {{{ php_copy_file */
php_copy_file(const char * src,const char * dest)1511 PHPAPI int php_copy_file(const char *src, const char *dest)
1512 {
1513 	return php_copy_file_ctx(src, dest, 0, NULL);
1514 }
1515 /* }}} */
1516 
1517 /* {{{ php_copy_file_ex */
php_copy_file_ex(const char * src,const char * dest,int src_flg)1518 PHPAPI int php_copy_file_ex(const char *src, const char *dest, int src_flg)
1519 {
1520 	return php_copy_file_ctx(src, dest, src_flg, NULL);
1521 }
1522 /* }}} */
1523 
1524 /* {{{ php_copy_file_ctx */
php_copy_file_ctx(const char * src,const char * dest,int src_flg,php_stream_context * ctx)1525 PHPAPI int php_copy_file_ctx(const char *src, const char *dest, int src_flg, php_stream_context *ctx)
1526 {
1527 	php_stream *srcstream = NULL, *deststream = NULL;
1528 	int ret = FAILURE;
1529 	php_stream_statbuf src_s, dest_s;
1530 	int src_stat_flags = (src_flg & STREAM_DISABLE_OPEN_BASEDIR) ? PHP_STREAM_URL_STAT_IGNORE_OPEN_BASEDIR : 0;
1531 
1532 	switch (php_stream_stat_path_ex(src, src_stat_flags, &src_s, ctx)) {
1533 		case -1:
1534 			/* non-statable stream */
1535 			goto safe_to_copy;
1536 			break;
1537 		case 0:
1538 			break;
1539 		default: /* failed to stat file, does not exist? */
1540 			return ret;
1541 	}
1542 	if (S_ISDIR(src_s.sb.st_mode)) {
1543 		php_error_docref(NULL, E_WARNING, "The first argument to copy() function cannot be a directory");
1544 		return FAILURE;
1545 	}
1546 
1547 	switch (php_stream_stat_path_ex(dest, PHP_STREAM_URL_STAT_QUIET, &dest_s, ctx)) {
1548 		case -1:
1549 			/* non-statable stream */
1550 			goto safe_to_copy;
1551 			break;
1552 		case 0:
1553 			break;
1554 		default: /* failed to stat file, does not exist? */
1555 			return ret;
1556 	}
1557 	if (S_ISDIR(dest_s.sb.st_mode)) {
1558 		php_error_docref(NULL, E_WARNING, "The second argument to copy() function cannot be a directory");
1559 		return FAILURE;
1560 	}
1561 	if (!src_s.sb.st_ino || !dest_s.sb.st_ino) {
1562 		goto no_stat;
1563 	}
1564 	if (src_s.sb.st_ino == dest_s.sb.st_ino && src_s.sb.st_dev == dest_s.sb.st_dev) {
1565 		return ret;
1566 	} else {
1567 		goto safe_to_copy;
1568 	}
1569 no_stat:
1570 	{
1571 		char *sp, *dp;
1572 		int res;
1573 
1574 		if ((sp = expand_filepath(src, NULL)) == NULL) {
1575 			return ret;
1576 		}
1577 		if ((dp = expand_filepath(dest, NULL)) == NULL) {
1578 			efree(sp);
1579 			goto safe_to_copy;
1580 		}
1581 
1582 		res =
1583 #ifndef PHP_WIN32
1584 			!strcmp(sp, dp);
1585 #else
1586 			!strcasecmp(sp, dp);
1587 #endif
1588 
1589 		efree(sp);
1590 		efree(dp);
1591 		if (res) {
1592 			return ret;
1593 		}
1594 	}
1595 safe_to_copy:
1596 
1597 	srcstream = php_stream_open_wrapper_ex(src, "rb", src_flg | REPORT_ERRORS, NULL, ctx);
1598 
1599 	if (!srcstream) {
1600 		return ret;
1601 	}
1602 
1603 	deststream = php_stream_open_wrapper_ex(dest, "wb", REPORT_ERRORS, NULL, ctx);
1604 
1605 	if (deststream) {
1606 		ret = php_stream_copy_to_stream_ex(srcstream, deststream, PHP_STREAM_COPY_ALL, NULL);
1607 	}
1608 	php_stream_close(srcstream);
1609 	if (deststream) {
1610 		php_stream_close(deststream);
1611 	}
1612 	return ret;
1613 }
1614 /* }}} */
1615 
1616 /* {{{ Binary-safe file read */
PHP_FUNCTION(fread)1617 PHPAPI PHP_FUNCTION(fread)
1618 {
1619 	zval *res;
1620 	zend_long len;
1621 	php_stream *stream;
1622 	zend_string *str;
1623 
1624 	ZEND_PARSE_PARAMETERS_START(2, 2)
1625 		Z_PARAM_RESOURCE(res)
1626 		Z_PARAM_LONG(len)
1627 	ZEND_PARSE_PARAMETERS_END();
1628 
1629 	PHP_STREAM_FROM_ZVAL(stream, res);
1630 
1631 	if (len <= 0) {
1632 		zend_argument_value_error(2, "must be greater than 0");
1633 		RETURN_THROWS();
1634 	}
1635 
1636 	str = php_stream_read_to_str(stream, len);
1637 	if (!str) {
1638 		zval_ptr_dtor_str(return_value);
1639 		RETURN_FALSE;
1640 	}
1641 
1642 	RETURN_STR(str);
1643 }
1644 /* }}} */
1645 
php_fgetcsv_lookup_trailing_spaces(const char * ptr,size_t len)1646 static const char *php_fgetcsv_lookup_trailing_spaces(const char *ptr, size_t len) /* {{{ */
1647 {
1648 	int inc_len;
1649 	unsigned char last_chars[2] = { 0, 0 };
1650 
1651 	while (len > 0) {
1652 		inc_len = (*ptr == '\0' ? 1 : php_mblen(ptr, len));
1653 		switch (inc_len) {
1654 			case -2:
1655 			case -1:
1656 				inc_len = 1;
1657 				php_mb_reset();
1658 				break;
1659 			case 0:
1660 				goto quit_loop;
1661 			case 1:
1662 			default:
1663 				last_chars[0] = last_chars[1];
1664 				last_chars[1] = *ptr;
1665 				break;
1666 		}
1667 		ptr += inc_len;
1668 		len -= inc_len;
1669 	}
1670 quit_loop:
1671 	switch (last_chars[1]) {
1672 		case '\n':
1673 			if (last_chars[0] == '\r') {
1674 				return ptr - 2;
1675 			}
1676 			ZEND_FALLTHROUGH;
1677 		case '\r':
1678 			return ptr - 1;
1679 	}
1680 	return ptr;
1681 }
1682 /* }}} */
1683 
1684 #define FPUTCSV_FLD_CHK(c) memchr(ZSTR_VAL(field_str), c, ZSTR_LEN(field_str))
1685 
1686 /* {{{ Format line as CSV and write to file pointer */
PHP_FUNCTION(fputcsv)1687 PHP_FUNCTION(fputcsv)
1688 {
1689 	char delimiter = ',';					/* allow this to be set as parameter */
1690 	char enclosure = '"';					/* allow this to be set as parameter */
1691 	int escape_char = (unsigned char) '\\';	/* allow this to be set as parameter */
1692 	php_stream *stream;
1693 	zval *fp = NULL, *fields = NULL;
1694 	ssize_t ret;
1695 	char *delimiter_str = NULL, *enclosure_str = NULL, *escape_str = NULL;
1696 	size_t delimiter_str_len = 0, enclosure_str_len = 0, escape_str_len = 0;
1697 	zend_string *eol_str = NULL;
1698 
1699 	ZEND_PARSE_PARAMETERS_START(2, 6)
1700 		Z_PARAM_RESOURCE(fp)
1701 		Z_PARAM_ARRAY(fields)
1702 		Z_PARAM_OPTIONAL
1703 		Z_PARAM_STRING(delimiter_str, delimiter_str_len)
1704 		Z_PARAM_STRING(enclosure_str, enclosure_str_len)
1705 		Z_PARAM_STRING(escape_str, escape_str_len)
1706 		Z_PARAM_STR_OR_NULL(eol_str)
1707 	ZEND_PARSE_PARAMETERS_END();
1708 
1709 	if (delimiter_str != NULL) {
1710 		/* Make sure that there is at least one character in string */
1711 		if (delimiter_str_len != 1) {
1712 			zend_argument_value_error(3, "must be a single character");
1713 			RETURN_THROWS();
1714 		}
1715 
1716 		/* use first character from string */
1717 		delimiter = *delimiter_str;
1718 	}
1719 
1720 	if (enclosure_str != NULL) {
1721 		if (enclosure_str_len != 1) {
1722 			zend_argument_value_error(4, "must be a single character");
1723 			RETURN_THROWS();
1724 		}
1725 		/* use first character from string */
1726 		enclosure = *enclosure_str;
1727 	}
1728 
1729 	if (escape_str != NULL) {
1730 		if (escape_str_len > 1) {
1731 			zend_argument_value_error(5, "must be empty or a single character");
1732 			RETURN_THROWS();
1733 		}
1734 		if (escape_str_len < 1) {
1735 			escape_char = PHP_CSV_NO_ESCAPE;
1736 		} else {
1737 			/* use first character from string */
1738 			escape_char = (unsigned char) *escape_str;
1739 		}
1740 	}
1741 
1742 	PHP_STREAM_FROM_ZVAL(stream, fp);
1743 
1744 	ret = php_fputcsv(stream, fields, delimiter, enclosure, escape_char, eol_str);
1745 	if (ret < 0) {
1746 		RETURN_FALSE;
1747 	}
1748 	RETURN_LONG(ret);
1749 }
1750 /* }}} */
1751 
1752 /* {{{ PHPAPI size_t php_fputcsv(php_stream *stream, zval *fields, char delimiter, char enclosure, int escape_char, zend_string *eol_str) */
php_fputcsv(php_stream * stream,zval * fields,char delimiter,char enclosure,int escape_char,zend_string * eol_str)1753 PHPAPI ssize_t php_fputcsv(php_stream *stream, zval *fields, char delimiter, char enclosure, int escape_char, zend_string *eol_str)
1754 {
1755 	uint32_t count, i = 0;
1756 	size_t ret;
1757 	zval *field_tmp;
1758 	smart_str csvline = {0};
1759 
1760 	ZEND_ASSERT((escape_char >= 0 && escape_char <= UCHAR_MAX) || escape_char == PHP_CSV_NO_ESCAPE);
1761 	count = zend_hash_num_elements(Z_ARRVAL_P(fields));
1762 	ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(fields), field_tmp) {
1763 		zend_string *tmp_field_str;
1764 		zend_string *field_str = zval_get_tmp_string(field_tmp, &tmp_field_str);
1765 
1766 		/* enclose a field that contains a delimiter, an enclosure character, or a newline */
1767 		if (FPUTCSV_FLD_CHK(delimiter) ||
1768 			FPUTCSV_FLD_CHK(enclosure) ||
1769 			(escape_char != PHP_CSV_NO_ESCAPE && FPUTCSV_FLD_CHK(escape_char)) ||
1770 			FPUTCSV_FLD_CHK('\n') ||
1771 			FPUTCSV_FLD_CHK('\r') ||
1772 			FPUTCSV_FLD_CHK('\t') ||
1773 			FPUTCSV_FLD_CHK(' ')
1774 		) {
1775 			char *ch = ZSTR_VAL(field_str);
1776 			char *end = ch + ZSTR_LEN(field_str);
1777 			int escaped = 0;
1778 
1779 			smart_str_appendc(&csvline, enclosure);
1780 			while (ch < end) {
1781 				if (escape_char != PHP_CSV_NO_ESCAPE && *ch == escape_char) {
1782 					escaped = 1;
1783 				} else if (!escaped && *ch == enclosure) {
1784 					smart_str_appendc(&csvline, enclosure);
1785 				} else {
1786 					escaped = 0;
1787 				}
1788 				smart_str_appendc(&csvline, *ch);
1789 				ch++;
1790 			}
1791 			smart_str_appendc(&csvline, enclosure);
1792 		} else {
1793 			smart_str_append(&csvline, field_str);
1794 		}
1795 
1796 		if (++i != count) {
1797 			smart_str_appendl(&csvline, &delimiter, 1);
1798 		}
1799 		zend_tmp_string_release(tmp_field_str);
1800 	} ZEND_HASH_FOREACH_END();
1801 
1802 	if (eol_str) {
1803 		smart_str_append(&csvline, eol_str);
1804 	} else {
1805 		smart_str_appendc(&csvline, '\n');
1806 	}
1807 	smart_str_0(&csvline);
1808 
1809 	ret = php_stream_write(stream, ZSTR_VAL(csvline.s), ZSTR_LEN(csvline.s));
1810 
1811 	smart_str_free(&csvline);
1812 
1813 	return ret;
1814 }
1815 /* }}} */
1816 
1817 /* {{{ Get line from file pointer and parse for CSV fields */
PHP_FUNCTION(fgetcsv)1818 PHP_FUNCTION(fgetcsv)
1819 {
1820 	char delimiter = ',';	/* allow this to be set as parameter */
1821 	char enclosure = '"';	/* allow this to be set as parameter */
1822 	int escape = (unsigned char) '\\';
1823 
1824 	zend_long len = 0;
1825 	size_t buf_len;
1826 	char *buf;
1827 	php_stream *stream;
1828 
1829 	{
1830 		zval *fd;
1831 		bool len_is_null = 1;
1832 		char *delimiter_str = NULL;
1833 		size_t delimiter_str_len = 0;
1834 		char *enclosure_str = NULL;
1835 		size_t enclosure_str_len = 0;
1836 		char *escape_str = NULL;
1837 		size_t escape_str_len = 0;
1838 
1839 		ZEND_PARSE_PARAMETERS_START(1, 5)
1840 			Z_PARAM_RESOURCE(fd)
1841 			Z_PARAM_OPTIONAL
1842 			Z_PARAM_LONG_OR_NULL(len, len_is_null)
1843 			Z_PARAM_STRING(delimiter_str, delimiter_str_len)
1844 			Z_PARAM_STRING(enclosure_str, enclosure_str_len)
1845 			Z_PARAM_STRING(escape_str, escape_str_len)
1846 		ZEND_PARSE_PARAMETERS_END();
1847 
1848 		if (delimiter_str != NULL) {
1849 			/* Make sure that there is at least one character in string */
1850 			if (delimiter_str_len != 1) {
1851 				zend_argument_value_error(3, "must be a single character");
1852 				RETURN_THROWS();
1853 			}
1854 
1855 			/* use first character from string */
1856 			delimiter = delimiter_str[0];
1857 		}
1858 
1859 		if (enclosure_str != NULL) {
1860 			if (enclosure_str_len != 1) {
1861 				zend_argument_value_error(4, "must be a single character");
1862 				RETURN_THROWS();
1863 			}
1864 
1865 			/* use first character from string */
1866 			enclosure = enclosure_str[0];
1867 		}
1868 
1869 		if (escape_str != NULL) {
1870 			if (escape_str_len > 1) {
1871 				zend_argument_value_error(5, "must be empty or a single character");
1872 				RETURN_THROWS();
1873 			}
1874 
1875 			if (escape_str_len < 1) {
1876 				escape = PHP_CSV_NO_ESCAPE;
1877 			} else {
1878 				escape = (unsigned char) escape_str[0];
1879 			}
1880 		}
1881 
1882 		if (len_is_null || len == 0) {
1883 			len = -1;
1884 		} else if (len < 0) {
1885 			zend_argument_value_error(2, "must be a greater than or equal to 0");
1886 			RETURN_THROWS();
1887 		}
1888 
1889 		PHP_STREAM_FROM_ZVAL(stream, fd);
1890 	}
1891 
1892 	if (len < 0) {
1893 		if ((buf = php_stream_get_line(stream, NULL, 0, &buf_len)) == NULL) {
1894 			RETURN_FALSE;
1895 		}
1896 	} else {
1897 		buf = emalloc(len + 1);
1898 		if (php_stream_get_line(stream, buf, len + 1, &buf_len) == NULL) {
1899 			efree(buf);
1900 			RETURN_FALSE;
1901 		}
1902 	}
1903 
1904 	HashTable *values = php_fgetcsv(stream, delimiter, enclosure, escape, buf_len, buf);
1905 	if (values == NULL) {
1906 		values = php_bc_fgetcsv_empty_line();
1907 	}
1908 	RETURN_ARR(values);
1909 }
1910 /* }}} */
1911 
php_bc_fgetcsv_empty_line(void)1912 PHPAPI HashTable *php_bc_fgetcsv_empty_line(void)
1913 {
1914 	HashTable *values = zend_new_array(1);
1915 	zval tmp;
1916 	ZVAL_NULL(&tmp);
1917 	zend_hash_next_index_insert(values, &tmp);
1918 	return values;
1919 }
1920 
php_fgetcsv(php_stream * stream,char delimiter,char enclosure,int escape_char,size_t buf_len,char * buf)1921 PHPAPI HashTable *php_fgetcsv(php_stream *stream, char delimiter, char enclosure, int escape_char, size_t buf_len, char *buf) /* {{{ */
1922 {
1923 	char *temp, *bptr, *line_end, *limit;
1924 	size_t temp_len, line_end_len;
1925 	int inc_len;
1926 	bool first_field = true;
1927 
1928 	ZEND_ASSERT((escape_char >= 0 && escape_char <= UCHAR_MAX) || escape_char == PHP_CSV_NO_ESCAPE);
1929 
1930 	/* initialize internal state */
1931 	php_mb_reset();
1932 
1933 	/* Now into new section that parses buf for delimiter/enclosure fields */
1934 
1935 	/* Strip trailing space from buf, saving end of line in case required for enclosure field */
1936 
1937 	bptr = buf;
1938 	line_end = limit = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len);
1939 	line_end_len = buf_len - (size_t)(limit - buf);
1940 
1941 	/* reserve workspace for building each individual field */
1942 	temp_len = buf_len;
1943 	temp = emalloc(temp_len + line_end_len + 1);
1944 
1945 	/* Initialize values HashTable */
1946 	HashTable *values = zend_new_array(0);
1947 
1948 	/* Main loop to read CSV fields */
1949 	/* NB this routine will return NULL for a blank line */
1950 	do {
1951 		char *comp_end, *hunk_begin;
1952 		char *tptr = temp;
1953 
1954 		inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
1955 		if (inc_len == 1) {
1956 			char *tmp = bptr;
1957 			while ((*tmp != delimiter) && isspace((int)*(unsigned char *)tmp)) {
1958 				tmp++;
1959 			}
1960 			if (*tmp == enclosure && tmp < limit) {
1961 				bptr = tmp;
1962 			}
1963 		}
1964 
1965 		if (first_field && bptr == line_end) {
1966 			zend_array_destroy(values);
1967 			values = NULL;
1968 			break;
1969 		}
1970 		first_field = false;
1971 		/* 2. Read field, leaving bptr pointing at start of next field */
1972 		if (inc_len != 0 && *bptr == enclosure) {
1973 			int state = 0;
1974 
1975 			bptr++;	/* move on to first character in field */
1976 			hunk_begin = bptr;
1977 
1978 			/* 2A. handle enclosure delimited field */
1979 			for (;;) {
1980 				switch (inc_len) {
1981 					case 0:
1982 						switch (state) {
1983 							case 2:
1984 								tptr = zend_mempcpy(tptr, hunk_begin, (bptr - hunk_begin - 1));
1985 								hunk_begin = bptr;
1986 								goto quit_loop_2;
1987 
1988 							case 1:
1989 								tptr = zend_mempcpy(tptr, hunk_begin, (bptr - hunk_begin));
1990 								hunk_begin = bptr;
1991 								ZEND_FALLTHROUGH;
1992 
1993 							case 0: {
1994 								if (hunk_begin != line_end) {
1995 									tptr = zend_mempcpy(tptr, hunk_begin, (bptr - hunk_begin));
1996 									hunk_begin = bptr;
1997 								}
1998 
1999 								/* add the embedded line end to the field */
2000 								tptr = zend_mempcpy(tptr, line_end, line_end_len);
2001 
2002 								/* nothing can be fetched if stream is NULL (e.g. str_getcsv()) */
2003 								if (stream == NULL) {
2004 									/* the enclosure is unterminated */
2005 									if (bptr > limit) {
2006 										/* if the line ends with enclosure, we need to go back by
2007 										 * one character so the \0 character is not copied. */
2008 										if (hunk_begin == bptr) {
2009 											--hunk_begin;
2010 										}
2011 										--bptr;
2012 									}
2013 									goto quit_loop_2;
2014 								}
2015 
2016 								size_t new_len;
2017 								char *new_buf = php_stream_get_line(stream, NULL, 0, &new_len);
2018 								if (!new_buf) {
2019 									/* we've got an unterminated enclosure,
2020 									 * assign all the data from the start of
2021 									 * the enclosure to end of data to the
2022 									 * last element */
2023 									if (bptr > limit) {
2024 										/* if the line ends with enclosure, we need to go back by
2025 										 * one character so the \0 character is not copied. */
2026 										if (hunk_begin == bptr) {
2027 											--hunk_begin;
2028 										}
2029 										--bptr;
2030 									}
2031 									goto quit_loop_2;
2032 								}
2033 
2034 								temp_len += new_len;
2035 								char *new_temp = erealloc(temp, temp_len);
2036 								tptr = new_temp + (size_t)(tptr - temp);
2037 								temp = new_temp;
2038 
2039 								efree(buf);
2040 								buf_len = new_len;
2041 								bptr = buf = new_buf;
2042 								hunk_begin = buf;
2043 
2044 								line_end = limit = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len);
2045 								line_end_len = buf_len - (size_t)(limit - buf);
2046 
2047 								state = 0;
2048 							} break;
2049 						}
2050 						break;
2051 
2052 					case -2:
2053 					case -1:
2054 						php_mb_reset();
2055 						ZEND_FALLTHROUGH;
2056 					case 1:
2057 						/* we need to determine if the enclosure is
2058 						 * 'real' or is it escaped */
2059 						switch (state) {
2060 							case 1: /* escaped */
2061 								bptr++;
2062 								state = 0;
2063 								break;
2064 							case 2: /* embedded enclosure ? let's check it */
2065 								if (*bptr != enclosure) {
2066 									/* real enclosure */
2067 									tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin - 1);
2068 									hunk_begin = bptr;
2069 									goto quit_loop_2;
2070 								}
2071 								tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin);
2072 								bptr++;
2073 								hunk_begin = bptr;
2074 								state = 0;
2075 								break;
2076 							default:
2077 								if (*bptr == enclosure) {
2078 									state = 2;
2079 								} else if (escape_char != PHP_CSV_NO_ESCAPE && *bptr == escape_char) {
2080 									state = 1;
2081 								}
2082 								bptr++;
2083 								break;
2084 						}
2085 						break;
2086 
2087 					default:
2088 						switch (state) {
2089 							case 2:
2090 								/* real enclosure */
2091 								tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin - 1);
2092 								hunk_begin = bptr;
2093 								goto quit_loop_2;
2094 							case 1:
2095 								bptr += inc_len;
2096 								tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin);
2097 								hunk_begin = bptr;
2098 								state = 0;
2099 								break;
2100 							default:
2101 								bptr += inc_len;
2102 								break;
2103 						}
2104 						break;
2105 				}
2106 				inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2107 			}
2108 
2109 		quit_loop_2:
2110 			/* look up for a delimiter */
2111 			for (;;) {
2112 				switch (inc_len) {
2113 					case 0:
2114 						goto quit_loop_3;
2115 
2116 					case -2:
2117 					case -1:
2118 						inc_len = 1;
2119 						php_mb_reset();
2120 						ZEND_FALLTHROUGH;
2121 					case 1:
2122 						if (*bptr == delimiter) {
2123 							goto quit_loop_3;
2124 						}
2125 						break;
2126 					default:
2127 						break;
2128 				}
2129 				bptr += inc_len;
2130 				inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2131 			}
2132 
2133 		quit_loop_3:
2134 			tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin);
2135 			bptr += inc_len;
2136 			comp_end = tptr;
2137 		} else {
2138 			/* 2B. Handle non-enclosure field */
2139 
2140 			hunk_begin = bptr;
2141 
2142 			for (;;) {
2143 				switch (inc_len) {
2144 					case 0:
2145 						goto quit_loop_4;
2146 					case -2:
2147 					case -1:
2148 						inc_len = 1;
2149 						php_mb_reset();
2150 						ZEND_FALLTHROUGH;
2151 					case 1:
2152 						if (*bptr == delimiter) {
2153 							goto quit_loop_4;
2154 						}
2155 						break;
2156 					default:
2157 						break;
2158 				}
2159 				bptr += inc_len;
2160 				inc_len = (bptr < limit ? (*bptr == '\0' ? 1 : php_mblen(bptr, limit - bptr)): 0);
2161 			}
2162 		quit_loop_4:
2163 			tptr = zend_mempcpy(tptr, hunk_begin, bptr - hunk_begin);
2164 
2165 			comp_end = (char *)php_fgetcsv_lookup_trailing_spaces(temp, tptr - temp);
2166 			if (*bptr == delimiter) {
2167 				bptr++;
2168 			}
2169 		}
2170 
2171 		/* 3. Now pass our field back to php */
2172 		*comp_end = '\0';
2173 
2174 		zval z_tmp;
2175 		ZVAL_STRINGL(&z_tmp, temp, comp_end - temp);
2176 		zend_hash_next_index_insert(values, &z_tmp);
2177 	} while (inc_len > 0);
2178 
2179 	efree(temp);
2180 	if (stream) {
2181 		efree(buf);
2182 	}
2183 
2184 	return values;
2185 }
2186 /* }}} */
2187 
2188 /* {{{ Return the resolved path */
PHP_FUNCTION(realpath)2189 PHP_FUNCTION(realpath)
2190 {
2191 	char *filename;
2192 	size_t filename_len;
2193 	char resolved_path_buff[MAXPATHLEN];
2194 
2195 	ZEND_PARSE_PARAMETERS_START(1, 1)
2196 		Z_PARAM_PATH(filename, filename_len)
2197 	ZEND_PARSE_PARAMETERS_END();
2198 
2199 	if (VCWD_REALPATH(filename, resolved_path_buff)) {
2200 		if (php_check_open_basedir(resolved_path_buff)) {
2201 			RETURN_FALSE;
2202 		}
2203 
2204 #ifdef ZTS
2205 		if (VCWD_ACCESS(resolved_path_buff, F_OK)) {
2206 			RETURN_FALSE;
2207 		}
2208 #endif
2209 		RETURN_STRING(resolved_path_buff);
2210 	} else {
2211 		RETURN_FALSE;
2212 	}
2213 }
2214 /* }}} */
2215 
2216 /* See http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2 */
2217 #define PHP_META_HTML401_CHARS "-_.:"
2218 
2219 /* {{{ php_next_meta_token
2220    Tokenizes an HTML file for get_meta_tags */
php_next_meta_token(php_meta_tags_data * md)2221 php_meta_tags_token php_next_meta_token(php_meta_tags_data *md)
2222 {
2223 	int ch = 0, compliment;
2224 	char buff[META_DEF_BUFSIZE + 1];
2225 
2226 	memset((void *)buff, 0, META_DEF_BUFSIZE + 1);
2227 
2228 	while (md->ulc || (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)))) {
2229 		if (php_stream_eof(md->stream)) {
2230 			break;
2231 		}
2232 
2233 		if (md->ulc) {
2234 			ch = md->lc;
2235 			md->ulc = 0;
2236 		}
2237 
2238 		switch (ch) {
2239 			case '<':
2240 				return TOK_OPENTAG;
2241 				break;
2242 
2243 			case '>':
2244 				return TOK_CLOSETAG;
2245 				break;
2246 
2247 			case '=':
2248 				return TOK_EQUAL;
2249 				break;
2250 			case '/':
2251 				return TOK_SLASH;
2252 				break;
2253 
2254 			case '\'':
2255 			case '"':
2256 				compliment = ch;
2257 				md->token_len = 0;
2258 				while (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)) && ch != compliment && ch != '<' && ch != '>') {
2259 					buff[(md->token_len)++] = ch;
2260 
2261 					if (md->token_len == META_DEF_BUFSIZE) {
2262 						break;
2263 					}
2264 				}
2265 
2266 				if (ch == '<' || ch == '>') {
2267 					/* Was just an apostrophe */
2268 					md->ulc = 1;
2269 					md->lc = ch;
2270 				}
2271 
2272 				/* We don't need to alloc unless we are in a meta tag */
2273 				if (md->in_meta) {
2274 					md->token_data = (char *) emalloc(md->token_len + 1);
2275 					memcpy(md->token_data, buff, md->token_len+1);
2276 				}
2277 
2278 				return TOK_STRING;
2279 				break;
2280 
2281 			case '\n':
2282 			case '\r':
2283 			case '\t':
2284 				break;
2285 
2286 			case ' ':
2287 				return TOK_SPACE;
2288 				break;
2289 
2290 			default:
2291 				if (isalnum(ch)) {
2292 					md->token_len = 0;
2293 					buff[(md->token_len)++] = ch;
2294 					while (!php_stream_eof(md->stream) && (ch = php_stream_getc(md->stream)) && (isalnum(ch) || strchr(PHP_META_HTML401_CHARS, ch))) {
2295 						buff[(md->token_len)++] = ch;
2296 
2297 						if (md->token_len == META_DEF_BUFSIZE) {
2298 							break;
2299 						}
2300 					}
2301 
2302 					/* This is ugly, but we have to replace ungetc */
2303 					if (!isalpha(ch) && ch != '-') {
2304 						md->ulc = 1;
2305 						md->lc = ch;
2306 					}
2307 
2308 					md->token_data = (char *) emalloc(md->token_len + 1);
2309 					memcpy(md->token_data, buff, md->token_len+1);
2310 
2311 					return TOK_ID;
2312 				} else {
2313 					return TOK_OTHER;
2314 				}
2315 				break;
2316 		}
2317 	}
2318 
2319 	return TOK_EOF;
2320 }
2321 /* }}} */
2322 
2323 #ifdef HAVE_FNMATCH
2324 /* {{{ Match filename against pattern */
PHP_FUNCTION(fnmatch)2325 PHP_FUNCTION(fnmatch)
2326 {
2327 	char *pattern, *filename;
2328 	size_t pattern_len, filename_len;
2329 	zend_long flags = 0;
2330 
2331 	ZEND_PARSE_PARAMETERS_START(2, 3)
2332 		Z_PARAM_PATH(pattern, pattern_len)
2333 		Z_PARAM_PATH(filename, filename_len)
2334 		Z_PARAM_OPTIONAL
2335 		Z_PARAM_LONG(flags)
2336 	ZEND_PARSE_PARAMETERS_END();
2337 
2338 	if (filename_len >= MAXPATHLEN) {
2339 		php_error_docref(NULL, E_WARNING, "Filename exceeds the maximum allowed length of %d characters", MAXPATHLEN);
2340 		RETURN_FALSE;
2341 	}
2342 	if (pattern_len >= MAXPATHLEN) {
2343 		php_error_docref(NULL, E_WARNING, "Pattern exceeds the maximum allowed length of %d characters", MAXPATHLEN);
2344 		RETURN_FALSE;
2345 	}
2346 
2347 	RETURN_BOOL( ! fnmatch( pattern, filename, (int)flags ));
2348 }
2349 /* }}} */
2350 #endif
2351 
2352 /* {{{ Returns directory path used for temporary files */
PHP_FUNCTION(sys_get_temp_dir)2353 PHP_FUNCTION(sys_get_temp_dir)
2354 {
2355 	ZEND_PARSE_PARAMETERS_NONE();
2356 
2357 	RETURN_STRING((char *)php_get_temporary_directory());
2358 }
2359 /* }}} */
2360