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