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