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