1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2016 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: Andi Gutmans <andi@zend.com>                                |
16   |          Rasmus Lerdorf <rasmus@lerdorf.on.ca>                       |
17   |          Zeev Suraski <zeev@zend.com>                                |
18   +----------------------------------------------------------------------+
19*/
20
21/* $Id$ */
22
23/* {{{ includes
24 */
25
26#define ZEND_INCLUDE_FULL_WINDOWS_HEADERS
27
28#include "php.h"
29#include <stdio.h>
30#include <fcntl.h>
31#ifdef PHP_WIN32
32#include "win32/time.h"
33#include "win32/signal.h"
34#include "win32/php_win32_globals.h"
35#include "win32/winutil.h"
36#include <process.h>
37#elif defined(NETWARE)
38#include <sys/timeval.h>
39#ifdef USE_WINSOCK
40#include <novsock2.h>
41#endif
42#endif
43#if HAVE_SYS_TIME_H
44#include <sys/time.h>
45#endif
46#if HAVE_UNISTD_H
47#include <unistd.h>
48#endif
49#if HAVE_SIGNAL_H
50#include <signal.h>
51#endif
52#if HAVE_SETLOCALE
53#include <locale.h>
54#endif
55#include "zend.h"
56#include "zend_types.h"
57#include "zend_extensions.h"
58#include "php_ini.h"
59#include "php_globals.h"
60#include "php_main.h"
61#include "fopen_wrappers.h"
62#include "ext/standard/php_standard.h"
63#include "ext/standard/php_string.h"
64#include "ext/date/php_date.h"
65#include "php_variables.h"
66#include "ext/standard/credits.h"
67#ifdef PHP_WIN32
68#include <io.h>
69#include "win32/php_registry.h"
70#include "ext/standard/flock_compat.h"
71#endif
72#include "php_syslog.h"
73#include "Zend/zend_exceptions.h"
74
75#if PHP_SIGCHILD
76#include <sys/types.h>
77#include <sys/wait.h>
78#endif
79
80#include "zend_compile.h"
81#include "zend_execute.h"
82#include "zend_highlight.h"
83#include "zend_extensions.h"
84#include "zend_ini.h"
85#include "zend_dtrace.h"
86
87#include "php_content_types.h"
88#include "php_ticks.h"
89#include "php_streams.h"
90#include "php_open_temporary_file.h"
91
92#include "SAPI.h"
93#include "rfc1867.h"
94
95#if HAVE_MMAP || defined(PHP_WIN32)
96# if HAVE_UNISTD_H
97#  include <unistd.h>
98#  if defined(_SC_PAGESIZE)
99#    define REAL_PAGE_SIZE sysconf(_SC_PAGESIZE);
100#  elif defined(_SC_PAGE_SIZE)
101#    define REAL_PAGE_SIZE sysconf(_SC_PAGE_SIZE);
102#  endif
103# endif
104# if HAVE_SYS_MMAN_H
105#  include <sys/mman.h>
106# endif
107# ifndef REAL_PAGE_SIZE
108#  ifdef PAGE_SIZE
109#   define REAL_PAGE_SIZE PAGE_SIZE
110#  else
111#   define REAL_PAGE_SIZE 4096
112#  endif
113# endif
114#endif
115/* }}} */
116
117PHPAPI int (*php_register_internal_extensions_func)(void) = php_register_internal_extensions;
118
119#ifndef ZTS
120php_core_globals core_globals;
121#else
122PHPAPI int core_globals_id;
123#endif
124
125#define SAFE_FILENAME(f) ((f)?(f):"-")
126
127/* {{{ PHP_INI_MH
128 */
129static PHP_INI_MH(OnSetPrecision)
130{
131	zend_long i;
132
133	ZEND_ATOL(i, ZSTR_VAL(new_value));
134	if (i >= 0) {
135		EG(precision) = i;
136		return SUCCESS;
137	} else {
138		return FAILURE;
139	}
140}
141/* }}} */
142
143/* {{{ PHP_INI_MH
144 */
145static PHP_INI_MH(OnChangeMemoryLimit)
146{
147	if (new_value) {
148		PG(memory_limit) = zend_atol(ZSTR_VAL(new_value), (int)ZSTR_LEN(new_value));
149	} else {
150		PG(memory_limit) = 1<<30;		/* effectively, no limit */
151	}
152	return zend_set_memory_limit(PG(memory_limit));
153}
154/* }}} */
155
156
157/* {{{ php_disable_functions
158 */
159static void php_disable_functions(void)
160{
161	char *s = NULL, *e;
162
163	if (!*(INI_STR("disable_functions"))) {
164		return;
165	}
166
167	e = PG(disable_functions) = strdup(INI_STR("disable_functions"));
168	if (e == NULL) {
169		return;
170	}
171	while (*e) {
172		switch (*e) {
173			case ' ':
174			case ',':
175				if (s) {
176					*e = '\0';
177					zend_disable_function(s, e-s);
178					s = NULL;
179				}
180				break;
181			default:
182				if (!s) {
183					s = e;
184				}
185				break;
186		}
187		e++;
188	}
189	if (s) {
190		zend_disable_function(s, e-s);
191	}
192}
193/* }}} */
194
195/* {{{ php_disable_classes
196 */
197static void php_disable_classes(void)
198{
199	char *s = NULL, *e;
200
201	if (!*(INI_STR("disable_classes"))) {
202		return;
203	}
204
205	e = PG(disable_classes) = strdup(INI_STR("disable_classes"));
206
207	while (*e) {
208		switch (*e) {
209			case ' ':
210			case ',':
211				if (s) {
212					*e = '\0';
213					zend_disable_class(s, e-s);
214					s = NULL;
215				}
216				break;
217			default:
218				if (!s) {
219					s = e;
220				}
221				break;
222		}
223		e++;
224	}
225	if (s) {
226		zend_disable_class(s, e-s);
227	}
228}
229/* }}} */
230
231/* {{{ php_binary_init
232 */
233static void php_binary_init(void)
234{
235	char *binary_location;
236#ifdef PHP_WIN32
237	binary_location = (char *)malloc(MAXPATHLEN);
238	if (GetModuleFileName(0, binary_location, MAXPATHLEN) == 0) {
239		free(binary_location);
240		PG(php_binary) = NULL;
241	}
242#else
243	if (sapi_module.executable_location) {
244		binary_location = (char *)malloc(MAXPATHLEN);
245		if (!strchr(sapi_module.executable_location, '/')) {
246			char *envpath, *path;
247			int found = 0;
248
249			if ((envpath = getenv("PATH")) != NULL) {
250				char *search_dir, search_path[MAXPATHLEN];
251				char *last = NULL;
252				zend_stat_t s;
253
254				path = estrdup(envpath);
255				search_dir = php_strtok_r(path, ":", &last);
256
257				while (search_dir) {
258					snprintf(search_path, MAXPATHLEN, "%s/%s", search_dir, sapi_module.executable_location);
259					if (VCWD_REALPATH(search_path, binary_location) && !VCWD_ACCESS(binary_location, X_OK) && VCWD_STAT(binary_location, &s) == 0 && S_ISREG(s.st_mode)) {
260						found = 1;
261						break;
262					}
263					search_dir = php_strtok_r(NULL, ":", &last);
264				}
265				efree(path);
266			}
267			if (!found) {
268				free(binary_location);
269				binary_location = NULL;
270			}
271		} else if (!VCWD_REALPATH(sapi_module.executable_location, binary_location) || VCWD_ACCESS(binary_location, X_OK)) {
272			free(binary_location);
273			binary_location = NULL;
274		}
275	} else {
276		binary_location = NULL;
277	}
278#endif
279	PG(php_binary) = binary_location;
280}
281/* }}} */
282
283/* {{{ PHP_INI_MH
284 */
285static PHP_INI_MH(OnUpdateTimeout)
286{
287	if (stage==PHP_INI_STAGE_STARTUP) {
288		/* Don't set a timeout on startup, only per-request */
289		ZEND_ATOL(EG(timeout_seconds), ZSTR_VAL(new_value));
290		return SUCCESS;
291	}
292	zend_unset_timeout();
293	ZEND_ATOL(EG(timeout_seconds), ZSTR_VAL(new_value));
294	zend_set_timeout(EG(timeout_seconds), 0);
295	return SUCCESS;
296}
297/* }}} */
298
299/* {{{ php_get_display_errors_mode() helper function
300 */
301static int php_get_display_errors_mode(char *value, int value_length)
302{
303	int mode;
304
305	if (!value) {
306		return PHP_DISPLAY_ERRORS_STDOUT;
307	}
308
309	if (value_length == 2 && !strcasecmp("on", value)) {
310		mode = PHP_DISPLAY_ERRORS_STDOUT;
311	} else if (value_length == 3 && !strcasecmp("yes", value)) {
312		mode = PHP_DISPLAY_ERRORS_STDOUT;
313	} else if (value_length == 4 && !strcasecmp("true", value)) {
314		mode = PHP_DISPLAY_ERRORS_STDOUT;
315	} else if (value_length == 6 && !strcasecmp(value, "stderr")) {
316		mode = PHP_DISPLAY_ERRORS_STDERR;
317	} else if (value_length == 6 && !strcasecmp(value, "stdout")) {
318		mode = PHP_DISPLAY_ERRORS_STDOUT;
319	} else {
320		ZEND_ATOL(mode, value);
321		if (mode && mode != PHP_DISPLAY_ERRORS_STDOUT && mode != PHP_DISPLAY_ERRORS_STDERR) {
322			mode = PHP_DISPLAY_ERRORS_STDOUT;
323		}
324	}
325
326	return mode;
327}
328/* }}} */
329
330/* {{{ PHP_INI_MH
331 */
332static PHP_INI_MH(OnUpdateDisplayErrors)
333{
334	PG(display_errors) = (zend_bool) php_get_display_errors_mode(ZSTR_VAL(new_value), (int)ZSTR_LEN(new_value));
335
336	return SUCCESS;
337}
338/* }}} */
339
340/* {{{ PHP_INI_DISP
341 */
342static PHP_INI_DISP(display_errors_mode)
343{
344	int mode, tmp_value_length, cgi_or_cli;
345	char *tmp_value;
346
347	if (type == ZEND_INI_DISPLAY_ORIG && ini_entry->modified) {
348		tmp_value = (ini_entry->orig_value ? ZSTR_VAL(ini_entry->orig_value) : NULL );
349		tmp_value_length = (int)(ini_entry->orig_value? ZSTR_LEN(ini_entry->orig_value) : 0);
350	} else if (ini_entry->value) {
351		tmp_value = ZSTR_VAL(ini_entry->value);
352		tmp_value_length = (int)ZSTR_LEN(ini_entry->value);
353	} else {
354		tmp_value = NULL;
355		tmp_value_length = 0;
356	}
357
358	mode = php_get_display_errors_mode(tmp_value, tmp_value_length);
359
360	/* Display 'On' for other SAPIs instead of STDOUT or STDERR */
361	cgi_or_cli = (!strcmp(sapi_module.name, "cli") || !strcmp(sapi_module.name, "cgi"));
362
363	switch (mode) {
364		case PHP_DISPLAY_ERRORS_STDERR:
365			if (cgi_or_cli ) {
366				PUTS("STDERR");
367			} else {
368				PUTS("On");
369			}
370			break;
371
372		case PHP_DISPLAY_ERRORS_STDOUT:
373			if (cgi_or_cli ) {
374				PUTS("STDOUT");
375			} else {
376				PUTS("On");
377			}
378			break;
379
380		default:
381			PUTS("Off");
382			break;
383	}
384}
385/* }}} */
386
387/* {{{ PHP_INI_MH
388 */
389static PHP_INI_MH(OnUpdateInternalEncoding)
390{
391	if (new_value) {
392		OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
393	}
394	return SUCCESS;
395}
396/* }}} */
397
398/* {{{ PHP_INI_MH
399 */
400static PHP_INI_MH(OnUpdateInputEncoding)
401{
402	if (new_value) {
403		OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
404	}
405	return SUCCESS;
406}
407/* }}} */
408
409/* {{{ PHP_INI_MH
410 */
411static PHP_INI_MH(OnUpdateOutputEncoding)
412{
413	if (new_value) {
414		OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
415	}
416	return SUCCESS;
417}
418/* }}} */
419
420/* {{{ PHP_INI_MH
421 */
422static PHP_INI_MH(OnUpdateErrorLog)
423{
424	/* Only do the safemode/open_basedir check at runtime */
425	if ((stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) && new_value && strcmp(ZSTR_VAL(new_value), "syslog")) {
426		if (PG(open_basedir) && php_check_open_basedir(ZSTR_VAL(new_value))) {
427			return FAILURE;
428		}
429	}
430	OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
431	return SUCCESS;
432}
433/* }}} */
434
435/* {{{ PHP_INI_MH
436 */
437static PHP_INI_MH(OnUpdateMailLog)
438{
439	/* Only do the safemode/open_basedir check at runtime */
440	if ((stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) && new_value) {
441		if (PG(open_basedir) && php_check_open_basedir(ZSTR_VAL(new_value))) {
442			return FAILURE;
443		}
444	}
445	OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
446	return SUCCESS;
447}
448/* }}} */
449
450/* {{{ PHP_INI_MH
451 */
452static PHP_INI_MH(OnChangeMailForceExtra)
453{
454	/* Don't allow changing it in htaccess */
455	if (stage == PHP_INI_STAGE_HTACCESS) {
456			return FAILURE;
457	}
458	return SUCCESS;
459}
460/* }}} */
461
462/* defined in browscap.c */
463PHP_INI_MH(OnChangeBrowscap);
464
465
466/* Need to be read from the environment (?):
467 * PHP_AUTO_PREPEND_FILE
468 * PHP_AUTO_APPEND_FILE
469 * PHP_DOCUMENT_ROOT
470 * PHP_USER_DIR
471 * PHP_INCLUDE_PATH
472 */
473
474 /* Windows and Netware use the internal mail */
475#if defined(PHP_WIN32) || defined(NETWARE)
476# define DEFAULT_SENDMAIL_PATH NULL
477#elif defined(PHP_PROG_SENDMAIL)
478# define DEFAULT_SENDMAIL_PATH PHP_PROG_SENDMAIL " -t -i "
479#else
480# define DEFAULT_SENDMAIL_PATH "/usr/sbin/sendmail -t -i"
481#endif
482
483/* {{{ PHP_INI
484 */
485PHP_INI_BEGIN()
486	PHP_INI_ENTRY_EX("highlight.comment",		HL_COMMENT_COLOR,	PHP_INI_ALL,	NULL,			php_ini_color_displayer_cb)
487	PHP_INI_ENTRY_EX("highlight.default",		HL_DEFAULT_COLOR,	PHP_INI_ALL,	NULL,			php_ini_color_displayer_cb)
488	PHP_INI_ENTRY_EX("highlight.html",			HL_HTML_COLOR,		PHP_INI_ALL,	NULL,			php_ini_color_displayer_cb)
489	PHP_INI_ENTRY_EX("highlight.keyword",		HL_KEYWORD_COLOR,	PHP_INI_ALL,	NULL,			php_ini_color_displayer_cb)
490	PHP_INI_ENTRY_EX("highlight.string",		HL_STRING_COLOR,	PHP_INI_ALL,	NULL,			php_ini_color_displayer_cb)
491
492	STD_PHP_INI_ENTRY_EX("display_errors",		"1",		PHP_INI_ALL,		OnUpdateDisplayErrors,	display_errors,			php_core_globals,	core_globals, display_errors_mode)
493	STD_PHP_INI_BOOLEAN("display_startup_errors",	"0",	PHP_INI_ALL,		OnUpdateBool,			display_startup_errors,	php_core_globals,	core_globals)
494	STD_PHP_INI_BOOLEAN("enable_dl",			"1",		PHP_INI_SYSTEM,		OnUpdateBool,			enable_dl,				php_core_globals,	core_globals)
495	STD_PHP_INI_BOOLEAN("expose_php",			"1",		PHP_INI_SYSTEM,		OnUpdateBool,			expose_php,				php_core_globals,	core_globals)
496	STD_PHP_INI_ENTRY("docref_root", 			"", 		PHP_INI_ALL,		OnUpdateString,			docref_root,			php_core_globals,	core_globals)
497	STD_PHP_INI_ENTRY("docref_ext",				"",			PHP_INI_ALL,		OnUpdateString,			docref_ext,				php_core_globals,	core_globals)
498	STD_PHP_INI_BOOLEAN("html_errors",			"1",		PHP_INI_ALL,		OnUpdateBool,			html_errors,			php_core_globals,	core_globals)
499	STD_PHP_INI_BOOLEAN("xmlrpc_errors",		"0",		PHP_INI_SYSTEM,		OnUpdateBool,			xmlrpc_errors,			php_core_globals,	core_globals)
500	STD_PHP_INI_ENTRY("xmlrpc_error_number",	"0",		PHP_INI_ALL,		OnUpdateLong,			xmlrpc_error_number,	php_core_globals,	core_globals)
501	STD_PHP_INI_ENTRY("max_input_time",			"-1",	PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnUpdateLong,			max_input_time,	php_core_globals,	core_globals)
502	STD_PHP_INI_BOOLEAN("ignore_user_abort",	"0",		PHP_INI_ALL,		OnUpdateBool,			ignore_user_abort,		php_core_globals,	core_globals)
503	STD_PHP_INI_BOOLEAN("implicit_flush",		"0",		PHP_INI_ALL,		OnUpdateBool,			implicit_flush,			php_core_globals,	core_globals)
504	STD_PHP_INI_BOOLEAN("log_errors",			"0",		PHP_INI_ALL,		OnUpdateBool,			log_errors,				php_core_globals,	core_globals)
505	STD_PHP_INI_ENTRY("log_errors_max_len",	 "1024",		PHP_INI_ALL,		OnUpdateLong,			log_errors_max_len,		php_core_globals,	core_globals)
506	STD_PHP_INI_BOOLEAN("ignore_repeated_errors",	"0",	PHP_INI_ALL,		OnUpdateBool,			ignore_repeated_errors,	php_core_globals,	core_globals)
507	STD_PHP_INI_BOOLEAN("ignore_repeated_source",	"0",	PHP_INI_ALL,		OnUpdateBool,			ignore_repeated_source,	php_core_globals,	core_globals)
508	STD_PHP_INI_BOOLEAN("report_memleaks",		"1",		PHP_INI_ALL,		OnUpdateBool,			report_memleaks,		php_core_globals,	core_globals)
509	STD_PHP_INI_BOOLEAN("report_zend_debug",	"1",		PHP_INI_ALL,		OnUpdateBool,			report_zend_debug,		php_core_globals,	core_globals)
510	STD_PHP_INI_ENTRY("output_buffering",		"0",		PHP_INI_PERDIR|PHP_INI_SYSTEM,	OnUpdateLong,	output_buffering,		php_core_globals,	core_globals)
511	STD_PHP_INI_ENTRY("output_handler",			NULL,		PHP_INI_PERDIR|PHP_INI_SYSTEM,	OnUpdateString,	output_handler,		php_core_globals,	core_globals)
512	STD_PHP_INI_BOOLEAN("register_argc_argv",	"1",		PHP_INI_PERDIR|PHP_INI_SYSTEM,	OnUpdateBool,	register_argc_argv,		php_core_globals,	core_globals)
513	STD_PHP_INI_BOOLEAN("auto_globals_jit",		"1",		PHP_INI_PERDIR|PHP_INI_SYSTEM,	OnUpdateBool,	auto_globals_jit,	php_core_globals,	core_globals)
514	STD_PHP_INI_BOOLEAN("short_open_tag",	DEFAULT_SHORT_OPEN_TAG,	PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnUpdateBool,			short_tags,				zend_compiler_globals,	compiler_globals)
515	STD_PHP_INI_BOOLEAN("sql.safe_mode",		"0",		PHP_INI_SYSTEM,		OnUpdateBool,			sql_safe_mode,			php_core_globals,	core_globals)
516	STD_PHP_INI_BOOLEAN("track_errors",			"0",		PHP_INI_ALL,		OnUpdateBool,			track_errors,			php_core_globals,	core_globals)
517
518	STD_PHP_INI_ENTRY("unserialize_callback_func",	NULL,	PHP_INI_ALL,		OnUpdateString,			unserialize_callback_func,	php_core_globals,	core_globals)
519	STD_PHP_INI_ENTRY("serialize_precision",	"17",	PHP_INI_ALL,		OnUpdateLongGEZero,			serialize_precision,	php_core_globals,	core_globals)
520	STD_PHP_INI_ENTRY("arg_separator.output",	"&",		PHP_INI_ALL,		OnUpdateStringUnempty,	arg_separator.output,	php_core_globals,	core_globals)
521	STD_PHP_INI_ENTRY("arg_separator.input",	"&",		PHP_INI_SYSTEM|PHP_INI_PERDIR,	OnUpdateStringUnempty,	arg_separator.input,	php_core_globals,	core_globals)
522
523	STD_PHP_INI_ENTRY("auto_append_file",		NULL,		PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnUpdateString,			auto_append_file,		php_core_globals,	core_globals)
524	STD_PHP_INI_ENTRY("auto_prepend_file",		NULL,		PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnUpdateString,			auto_prepend_file,		php_core_globals,	core_globals)
525	STD_PHP_INI_ENTRY("doc_root",				NULL,		PHP_INI_SYSTEM,		OnUpdateStringUnempty,	doc_root,				php_core_globals,	core_globals)
526	STD_PHP_INI_ENTRY("default_charset",		PHP_DEFAULT_CHARSET,	PHP_INI_ALL,	OnUpdateString,			default_charset,		sapi_globals_struct, sapi_globals)
527	STD_PHP_INI_ENTRY("default_mimetype",		SAPI_DEFAULT_MIMETYPE,	PHP_INI_ALL,	OnUpdateString,			default_mimetype,		sapi_globals_struct, sapi_globals)
528	STD_PHP_INI_ENTRY("internal_encoding",		NULL,			PHP_INI_ALL,	OnUpdateInternalEncoding,	internal_encoding,	php_core_globals, core_globals)
529	STD_PHP_INI_ENTRY("input_encoding",			NULL,			PHP_INI_ALL,	OnUpdateInputEncoding,				input_encoding,		php_core_globals, core_globals)
530	STD_PHP_INI_ENTRY("output_encoding",		NULL,			PHP_INI_ALL,	OnUpdateOutputEncoding,				output_encoding,	php_core_globals, core_globals)
531	STD_PHP_INI_ENTRY("error_log",				NULL,		PHP_INI_ALL,		OnUpdateErrorLog,			error_log,				php_core_globals,	core_globals)
532	STD_PHP_INI_ENTRY("extension_dir",			PHP_EXTENSION_DIR,		PHP_INI_SYSTEM,		OnUpdateStringUnempty,	extension_dir,			php_core_globals,	core_globals)
533	STD_PHP_INI_ENTRY("sys_temp_dir",			NULL,		PHP_INI_SYSTEM,		OnUpdateStringUnempty,	sys_temp_dir,			php_core_globals,	core_globals)
534	STD_PHP_INI_ENTRY("include_path",			PHP_INCLUDE_PATH,		PHP_INI_ALL,		OnUpdateStringUnempty,	include_path,			php_core_globals,	core_globals)
535	PHP_INI_ENTRY("max_execution_time",			"30",		PHP_INI_ALL,			OnUpdateTimeout)
536	STD_PHP_INI_ENTRY("open_basedir",			NULL,		PHP_INI_ALL,		OnUpdateBaseDir,			open_basedir,			php_core_globals,	core_globals)
537
538	STD_PHP_INI_BOOLEAN("file_uploads",			"1",		PHP_INI_SYSTEM,		OnUpdateBool,			file_uploads,			php_core_globals,	core_globals)
539	STD_PHP_INI_ENTRY("upload_max_filesize",	"2M",		PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnUpdateLong,			upload_max_filesize,	php_core_globals,	core_globals)
540	STD_PHP_INI_ENTRY("post_max_size",			"8M",		PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnUpdateLong,			post_max_size,			sapi_globals_struct,sapi_globals)
541	STD_PHP_INI_ENTRY("upload_tmp_dir",			NULL,		PHP_INI_SYSTEM,		OnUpdateStringUnempty,	upload_tmp_dir,			php_core_globals,	core_globals)
542	STD_PHP_INI_ENTRY("max_input_nesting_level", "64",		PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnUpdateLongGEZero,	max_input_nesting_level,			php_core_globals,	core_globals)
543	STD_PHP_INI_ENTRY("max_input_vars",			"1000",		PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnUpdateLongGEZero,	max_input_vars,						php_core_globals,	core_globals)
544
545	STD_PHP_INI_ENTRY("user_dir",				NULL,		PHP_INI_SYSTEM,		OnUpdateString,			user_dir,				php_core_globals,	core_globals)
546	STD_PHP_INI_ENTRY("variables_order",		"EGPCS",	PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnUpdateStringUnempty,	variables_order,		php_core_globals,	core_globals)
547	STD_PHP_INI_ENTRY("request_order",			NULL,		PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnUpdateString,	request_order,		php_core_globals,	core_globals)
548
549	STD_PHP_INI_ENTRY("error_append_string",	NULL,		PHP_INI_ALL,		OnUpdateString,			error_append_string,	php_core_globals,	core_globals)
550	STD_PHP_INI_ENTRY("error_prepend_string",	NULL,		PHP_INI_ALL,		OnUpdateString,			error_prepend_string,	php_core_globals,	core_globals)
551
552	PHP_INI_ENTRY("SMTP",						"localhost",PHP_INI_ALL,		NULL)
553	PHP_INI_ENTRY("smtp_port",					"25",		PHP_INI_ALL,		NULL)
554	STD_PHP_INI_BOOLEAN("mail.add_x_header",			"0",		PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnUpdateBool,			mail_x_header,			php_core_globals,	core_globals)
555	STD_PHP_INI_ENTRY("mail.log",					NULL,		PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnUpdateMailLog,			mail_log,			php_core_globals,	core_globals)
556	PHP_INI_ENTRY("browscap",					NULL,		PHP_INI_SYSTEM,		OnChangeBrowscap)
557	PHP_INI_ENTRY("memory_limit",				"128M",		PHP_INI_ALL,		OnChangeMemoryLimit)
558	PHP_INI_ENTRY("precision",					"14",		PHP_INI_ALL,		OnSetPrecision)
559	PHP_INI_ENTRY("sendmail_from",				NULL,		PHP_INI_ALL,		NULL)
560	PHP_INI_ENTRY("sendmail_path",	DEFAULT_SENDMAIL_PATH,	PHP_INI_SYSTEM,		NULL)
561	PHP_INI_ENTRY("mail.force_extra_parameters",NULL,		PHP_INI_SYSTEM|PHP_INI_PERDIR,		OnChangeMailForceExtra)
562	PHP_INI_ENTRY("disable_functions",			"",			PHP_INI_SYSTEM,		NULL)
563	PHP_INI_ENTRY("disable_classes",			"",			PHP_INI_SYSTEM,		NULL)
564	PHP_INI_ENTRY("max_file_uploads",			"20",			PHP_INI_SYSTEM|PHP_INI_PERDIR,		NULL)
565
566	STD_PHP_INI_BOOLEAN("allow_url_fopen",		"1",		PHP_INI_SYSTEM,		OnUpdateBool,		allow_url_fopen,		php_core_globals,		core_globals)
567	STD_PHP_INI_BOOLEAN("allow_url_include",	"0",		PHP_INI_SYSTEM,		OnUpdateBool,		allow_url_include,		php_core_globals,		core_globals)
568	STD_PHP_INI_BOOLEAN("enable_post_data_reading",	"1",	PHP_INI_SYSTEM|PHP_INI_PERDIR,	OnUpdateBool,	enable_post_data_reading,	php_core_globals,	core_globals)
569
570	STD_PHP_INI_ENTRY("realpath_cache_size",	"16K",		PHP_INI_SYSTEM,		OnUpdateLong,	realpath_cache_size_limit,	virtual_cwd_globals,	cwd_globals)
571	STD_PHP_INI_ENTRY("realpath_cache_ttl",		"120",		PHP_INI_SYSTEM,		OnUpdateLong,	realpath_cache_ttl,			virtual_cwd_globals,	cwd_globals)
572
573	STD_PHP_INI_ENTRY("user_ini.filename",		".user.ini",	PHP_INI_SYSTEM,		OnUpdateString,		user_ini_filename,	php_core_globals,		core_globals)
574	STD_PHP_INI_ENTRY("user_ini.cache_ttl",		"300",			PHP_INI_SYSTEM,		OnUpdateLong,		user_ini_cache_ttl,	php_core_globals,		core_globals)
575	STD_PHP_INI_BOOLEAN("exit_on_timeout",		"0",		PHP_INI_ALL,		OnUpdateBool,			exit_on_timeout,			php_core_globals,	core_globals)
576#ifdef PHP_WIN32
577	STD_PHP_INI_BOOLEAN("windows.show_crt_warning",		"0",		PHP_INI_ALL,		OnUpdateBool,			windows_show_crt_warning,			php_core_globals,	core_globals)
578#endif
579PHP_INI_END()
580/* }}} */
581
582/* True globals (no need for thread safety */
583/* But don't make them a single int bitfield */
584static int module_initialized = 0;
585static int module_startup = 1;
586static int module_shutdown = 0;
587
588/* {{{ php_during_module_startup */
589static int php_during_module_startup(void)
590{
591	return module_startup;
592}
593/* }}} */
594
595/* {{{ php_during_module_shutdown */
596static int php_during_module_shutdown(void)
597{
598	return module_shutdown;
599}
600/* }}} */
601
602/* {{{ php_get_module_initialized
603 */
604PHPAPI int php_get_module_initialized(void)
605{
606	return module_initialized;
607}
608/* }}} */
609
610/* {{{ php_log_err
611 */
612PHPAPI ZEND_COLD void php_log_err(char *log_message)
613{
614	int fd = -1;
615	time_t error_time;
616
617	if (PG(in_error_log)) {
618		/* prevent recursive invocation */
619		return;
620	}
621	PG(in_error_log) = 1;
622
623	/* Try to use the specified logging location. */
624	if (PG(error_log) != NULL) {
625#ifdef HAVE_SYSLOG_H
626		if (!strcmp(PG(error_log), "syslog")) {
627			php_syslog(LOG_NOTICE, "%s", log_message);
628			PG(in_error_log) = 0;
629			return;
630		}
631#endif
632		fd = VCWD_OPEN_MODE(PG(error_log), O_CREAT | O_APPEND | O_WRONLY, 0644);
633		if (fd != -1) {
634			char *tmp;
635			size_t len;
636			zend_string *error_time_str;
637
638			time(&error_time);
639#ifdef ZTS
640			if (!php_during_module_startup()) {
641				error_time_str = php_format_date("d-M-Y H:i:s e", 13, error_time, 1);
642			} else {
643				error_time_str = php_format_date("d-M-Y H:i:s e", 13, error_time, 0);
644			}
645#else
646			error_time_str = php_format_date("d-M-Y H:i:s e", 13, error_time, 1);
647#endif
648			len = spprintf(&tmp, 0, "[%s] %s%s", ZSTR_VAL(error_time_str), log_message, PHP_EOL);
649#ifdef PHP_WIN32
650			php_flock(fd, 2);
651			/* XXX should eventually write in a loop if len > UINT_MAX */
652			php_ignore_value(write(fd, tmp, (unsigned)len));
653#else
654			php_ignore_value(write(fd, tmp, len));
655#endif
656			efree(tmp);
657			zend_string_free(error_time_str);
658			close(fd);
659			PG(in_error_log) = 0;
660			return;
661		}
662	}
663
664	/* Otherwise fall back to the default logging location, if we have one */
665
666	if (sapi_module.log_message) {
667		sapi_module.log_message(log_message);
668	}
669	PG(in_error_log) = 0;
670}
671/* }}} */
672
673/* {{{ php_write
674   wrapper for modules to use PHPWRITE */
675PHPAPI size_t php_write(void *buf, size_t size)
676{
677	return PHPWRITE(buf, size);
678}
679/* }}} */
680
681/* {{{ php_printf
682 */
683PHPAPI size_t php_printf(const char *format, ...)
684{
685	va_list args;
686	size_t ret;
687	char *buffer;
688	size_t size;
689
690	va_start(args, format);
691	size = vspprintf(&buffer, 0, format, args);
692	ret = PHPWRITE(buffer, size);
693	efree(buffer);
694	va_end(args);
695
696	return ret;
697}
698/* }}} */
699
700/* {{{ php_verror */
701/* php_verror is called from php_error_docref<n> functions.
702 * Its purpose is to unify error messages and automatically generate clickable
703 * html error messages if correcponding ini setting (html_errors) is activated.
704 * See: CODING_STANDARDS for details.
705 */
706PHPAPI ZEND_COLD void php_verror(const char *docref, const char *params, int type, const char *format, va_list args)
707{
708	zend_string *replace_buffer = NULL, *replace_origin = NULL;
709	char *buffer = NULL, *docref_buf = NULL, *target = NULL;
710	char *docref_target = "", *docref_root = "";
711	char *p;
712	int buffer_len = 0;
713	const char *space = "";
714	const char *class_name = "";
715	const char *function;
716	int origin_len;
717	char *origin;
718	char *message;
719	int is_function = 0;
720
721	/* get error text into buffer and escape for html if necessary */
722	buffer_len = (int)vspprintf(&buffer, 0, format, args);
723
724	if (PG(html_errors)) {
725		replace_buffer = php_escape_html_entities((unsigned char*)buffer, buffer_len, 0, ENT_COMPAT, NULL);
726		/* Retry with substituting invalid chars on fail. */
727		if (!replace_buffer || ZSTR_LEN(replace_buffer) < 1) {
728			replace_buffer = php_escape_html_entities((unsigned char*)buffer, buffer_len, 0, ENT_COMPAT | ENT_HTML_SUBSTITUTE_ERRORS, NULL);
729		}
730
731		efree(buffer);
732
733		if (replace_buffer) {
734			buffer = ZSTR_VAL(replace_buffer);
735			buffer_len = (int)ZSTR_LEN(replace_buffer);
736		} else {
737			buffer = "";
738			buffer_len = 0;
739		}
740	}
741
742	/* which function caused the problem if any at all */
743	if (php_during_module_startup()) {
744		function = "PHP Startup";
745	} else if (php_during_module_shutdown()) {
746		function = "PHP Shutdown";
747	} else if (EG(current_execute_data) &&
748				EG(current_execute_data)->func &&
749				ZEND_USER_CODE(EG(current_execute_data)->func->common.type) &&
750				EG(current_execute_data)->opline &&
751				EG(current_execute_data)->opline->opcode == ZEND_INCLUDE_OR_EVAL
752	) {
753		switch (EG(current_execute_data)->opline->extended_value) {
754			case ZEND_EVAL:
755				function = "eval";
756				is_function = 1;
757				break;
758			case ZEND_INCLUDE:
759				function = "include";
760				is_function = 1;
761				break;
762			case ZEND_INCLUDE_ONCE:
763				function = "include_once";
764				is_function = 1;
765				break;
766			case ZEND_REQUIRE:
767				function = "require";
768				is_function = 1;
769				break;
770			case ZEND_REQUIRE_ONCE:
771				function = "require_once";
772				is_function = 1;
773				break;
774			default:
775				function = "Unknown";
776		}
777	} else {
778		function = get_active_function_name();
779		if (!function || !strlen(function)) {
780			function = "Unknown";
781		} else {
782			is_function = 1;
783			class_name = get_active_class_name(&space);
784		}
785	}
786
787	/* if we still have memory then format the origin */
788	if (is_function) {
789		origin_len = (int)spprintf(&origin, 0, "%s%s%s(%s)", class_name, space, function, params);
790	} else {
791		origin_len = (int)spprintf(&origin, 0, "%s", function);
792	}
793
794	if (PG(html_errors)) {
795		replace_origin = php_escape_html_entities((unsigned char*)origin, origin_len, 0, ENT_COMPAT, NULL);
796		efree(origin);
797		origin = ZSTR_VAL(replace_origin);
798	}
799
800	/* origin and buffer available, so lets come up with the error message */
801	if (docref && docref[0] == '#') {
802		docref_target = strchr(docref, '#');
803		docref = NULL;
804	}
805
806	/* no docref given but function is known (the default) */
807	if (!docref && is_function) {
808		int doclen;
809		while (*function == '_') {
810			function++;
811		}
812		if (space[0] == '\0') {
813			doclen = (int)spprintf(&docref_buf, 0, "function.%s", function);
814		} else {
815			doclen = (int)spprintf(&docref_buf, 0, "%s.%s", class_name, function);
816		}
817		while((p = strchr(docref_buf, '_')) != NULL) {
818			*p = '-';
819		}
820		docref = php_strtolower(docref_buf, doclen);
821	}
822
823	/* we have a docref for a function AND
824	 * - we show errors in html mode AND
825	 * - the user wants to see the links
826	 */
827	if (docref && is_function && PG(html_errors) && strlen(PG(docref_root))) {
828		if (strncmp(docref, "http://", 7)) {
829			/* We don't have 'http://' so we use docref_root */
830
831			char *ref;  /* temp copy for duplicated docref */
832
833			docref_root = PG(docref_root);
834
835			ref = estrdup(docref);
836			if (docref_buf) {
837				efree(docref_buf);
838			}
839			docref_buf = ref;
840			/* strip of the target if any */
841			p = strrchr(ref, '#');
842			if (p) {
843				target = estrdup(p);
844				if (target) {
845					docref_target = target;
846					*p = '\0';
847				}
848			}
849			/* add the extension if it is set in ini */
850			if (PG(docref_ext) && strlen(PG(docref_ext))) {
851				spprintf(&docref_buf, 0, "%s%s", ref, PG(docref_ext));
852				efree(ref);
853			}
854			docref = docref_buf;
855		}
856		/* display html formatted or only show the additional links */
857		if (PG(html_errors)) {
858			spprintf(&message, 0, "%s [<a href='%s%s%s'>%s</a>]: %s", origin, docref_root, docref, docref_target, docref, buffer);
859		} else {
860			spprintf(&message, 0, "%s [%s%s%s]: %s", origin, docref_root, docref, docref_target, buffer);
861		}
862		if (target) {
863			efree(target);
864		}
865	} else {
866		spprintf(&message, 0, "%s: %s", origin, buffer);
867	}
868	if (replace_origin) {
869		zend_string_free(replace_origin);
870	} else {
871		efree(origin);
872	}
873	if (docref_buf) {
874		efree(docref_buf);
875	}
876
877	if (PG(track_errors) && module_initialized && EG(valid_symbol_table) &&
878			(Z_TYPE(EG(user_error_handler)) == IS_UNDEF || !(EG(user_error_handler_error_reporting) & type))) {
879		zval tmp;
880		ZVAL_STRINGL(&tmp, buffer, buffer_len);
881		if (EG(current_execute_data)) {
882			if (zend_set_local_var_str("php_errormsg", sizeof("php_errormsg")-1, &tmp, 0) == FAILURE) {
883				zval_ptr_dtor(&tmp);
884			}
885		} else {
886			zend_hash_str_update_ind(&EG(symbol_table), "php_errormsg", sizeof("php_errormsg")-1, &tmp);
887		}
888	}
889	if (replace_buffer) {
890		zend_string_free(replace_buffer);
891	} else {
892		if (buffer_len > 0) {
893			efree(buffer);
894		}
895	}
896
897	php_error(type, "%s", message);
898	efree(message);
899}
900/* }}} */
901
902/* {{{ php_error_docref0 */
903/* See: CODING_STANDARDS for details. */
904PHPAPI ZEND_COLD void php_error_docref0(const char *docref, int type, const char *format, ...)
905{
906	va_list args;
907
908	va_start(args, format);
909	php_verror(docref, "", type, format, args);
910	va_end(args);
911}
912/* }}} */
913
914/* {{{ php_error_docref1 */
915/* See: CODING_STANDARDS for details. */
916PHPAPI ZEND_COLD void php_error_docref1(const char *docref, const char *param1, int type, const char *format, ...)
917{
918	va_list args;
919
920	va_start(args, format);
921	php_verror(docref, param1, type, format, args);
922	va_end(args);
923}
924/* }}} */
925
926/* {{{ php_error_docref2 */
927/* See: CODING_STANDARDS for details. */
928PHPAPI ZEND_COLD void php_error_docref2(const char *docref, const char *param1, const char *param2, int type, const char *format, ...)
929{
930	char *params;
931	va_list args;
932
933	spprintf(&params, 0, "%s,%s", param1, param2);
934	va_start(args, format);
935	php_verror(docref, params ? params : "...", type, format, args);
936	va_end(args);
937	if (params) {
938		efree(params);
939	}
940}
941/* }}} */
942
943#ifdef PHP_WIN32
944#define PHP_WIN32_ERROR_MSG_BUFFER_SIZE 512
945PHPAPI ZEND_COLD void php_win32_docref2_from_error(DWORD error, const char *param1, const char *param2) {
946	if (error == 0) {
947		php_error_docref2(NULL, param1, param2, E_WARNING, "%s", strerror(errno));
948	} else {
949		char buf[PHP_WIN32_ERROR_MSG_BUFFER_SIZE + 1];
950		int buf_len;
951
952		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, buf, PHP_WIN32_ERROR_MSG_BUFFER_SIZE, NULL);
953		buf_len = (int)strlen(buf);
954		if (buf_len >= 2) {
955			buf[buf_len - 1] = '\0';
956			buf[buf_len - 2] = '\0';
957		}
958		php_error_docref2(NULL, param1, param2, E_WARNING, "%s (code: %lu)", (char *)buf, error);
959	}
960}
961#undef PHP_WIN32_ERROR_MSG_BUFFER_SIZE
962#endif
963
964/* {{{ php_html_puts */
965PHPAPI void php_html_puts(const char *str, size_t size)
966{
967	zend_html_puts(str, size);
968}
969/* }}} */
970
971/* {{{ php_error_cb
972 extended error handling function */
973static ZEND_COLD void php_error_cb(int type, const char *error_filename, const uint error_lineno, const char *format, va_list args)
974{
975	char *buffer;
976	int buffer_len, display;
977
978	buffer_len = (int)vspprintf(&buffer, PG(log_errors_max_len), format, args);
979
980	/* check for repeated errors to be ignored */
981	if (PG(ignore_repeated_errors) && PG(last_error_message)) {
982		/* no check for PG(last_error_file) is needed since it cannot
983		 * be NULL if PG(last_error_message) is not NULL */
984		if (strcmp(PG(last_error_message), buffer)
985			|| (!PG(ignore_repeated_source)
986				&& ((PG(last_error_lineno) != (int)error_lineno)
987					|| strcmp(PG(last_error_file), error_filename)))) {
988			display = 1;
989		} else {
990			display = 0;
991		}
992	} else {
993		display = 1;
994	}
995
996	/* store the error if it has changed */
997	if (display) {
998		if (PG(last_error_message)) {
999			char *s = PG(last_error_message);
1000			PG(last_error_message) = NULL;
1001			free(s);
1002		}
1003		if (PG(last_error_file)) {
1004			char *s = PG(last_error_file);
1005			PG(last_error_file) = NULL;
1006			free(s);
1007		}
1008		if (!error_filename) {
1009			error_filename = "Unknown";
1010		}
1011		PG(last_error_type) = type;
1012		PG(last_error_message) = strdup(buffer);
1013		PG(last_error_file) = strdup(error_filename);
1014		PG(last_error_lineno) = error_lineno;
1015	}
1016
1017	/* according to error handling mode, suppress error, throw exception or show it */
1018	if (EG(error_handling) != EH_NORMAL) {
1019		switch (type) {
1020			case E_ERROR:
1021			case E_CORE_ERROR:
1022			case E_COMPILE_ERROR:
1023			case E_USER_ERROR:
1024			case E_PARSE:
1025				/* fatal errors are real errors and cannot be made exceptions */
1026				break;
1027			case E_STRICT:
1028			case E_DEPRECATED:
1029			case E_USER_DEPRECATED:
1030				/* for the sake of BC to old damaged code */
1031				break;
1032			case E_NOTICE:
1033			case E_USER_NOTICE:
1034				/* notices are no errors and are not treated as such like E_WARNINGS */
1035				break;
1036			default:
1037				/* throw an exception if we are in EH_THROW mode
1038				 * but DO NOT overwrite a pending exception
1039				 */
1040				if (EG(error_handling) == EH_THROW && !EG(exception)) {
1041					zend_throw_error_exception(EG(exception_class), buffer, 0, type);
1042				}
1043				efree(buffer);
1044				return;
1045		}
1046	}
1047
1048	/* display/log the error if necessary */
1049	if (display && (EG(error_reporting) & type || (type & E_CORE))
1050		&& (PG(log_errors) || PG(display_errors) || (!module_initialized))) {
1051		char *error_type_str;
1052
1053		switch (type) {
1054			case E_ERROR:
1055			case E_CORE_ERROR:
1056			case E_COMPILE_ERROR:
1057			case E_USER_ERROR:
1058				error_type_str = "Fatal error";
1059				break;
1060			case E_RECOVERABLE_ERROR:
1061				error_type_str = "Catchable fatal error";
1062				break;
1063			case E_WARNING:
1064			case E_CORE_WARNING:
1065			case E_COMPILE_WARNING:
1066			case E_USER_WARNING:
1067				error_type_str = "Warning";
1068				break;
1069			case E_PARSE:
1070				error_type_str = "Parse error";
1071				break;
1072			case E_NOTICE:
1073			case E_USER_NOTICE:
1074				error_type_str = "Notice";
1075				break;
1076			case E_STRICT:
1077				error_type_str = "Strict Standards";
1078				break;
1079			case E_DEPRECATED:
1080			case E_USER_DEPRECATED:
1081				error_type_str = "Deprecated";
1082				break;
1083			default:
1084				error_type_str = "Unknown error";
1085				break;
1086		}
1087
1088		if (!module_initialized || PG(log_errors)) {
1089			char *log_buffer;
1090#ifdef PHP_WIN32
1091			if (type == E_CORE_ERROR || type == E_CORE_WARNING) {
1092				syslog(LOG_ALERT, "PHP %s: %s (%s)", error_type_str, buffer, GetCommandLine());
1093			}
1094#endif
1095			spprintf(&log_buffer, 0, "PHP %s:  %s in %s on line %d", error_type_str, buffer, error_filename, error_lineno);
1096			php_log_err(log_buffer);
1097			efree(log_buffer);
1098		}
1099
1100		if (PG(display_errors) && ((module_initialized && !PG(during_request_startup)) || (PG(display_startup_errors)))) {
1101			if (PG(xmlrpc_errors)) {
1102				php_printf("<?xml version=\"1.0\"?><methodResponse><fault><value><struct><member><name>faultCode</name><value><int>%pd</int></value></member><member><name>faultString</name><value><string>%s:%s in %s on line %d</string></value></member></struct></value></fault></methodResponse>", PG(xmlrpc_error_number), error_type_str, buffer, error_filename, error_lineno);
1103			} else {
1104				char *prepend_string = INI_STR("error_prepend_string");
1105				char *append_string = INI_STR("error_append_string");
1106
1107				if (PG(html_errors)) {
1108					if (type == E_ERROR || type == E_PARSE) {
1109						zend_string *buf = php_escape_html_entities((unsigned char*)buffer, buffer_len, 0, ENT_COMPAT, NULL);
1110						php_printf("%s<br />\n<b>%s</b>:  %s in <b>%s</b> on line <b>%d</b><br />\n%s", STR_PRINT(prepend_string), error_type_str, ZSTR_VAL(buf), error_filename, error_lineno, STR_PRINT(append_string));
1111						zend_string_free(buf);
1112					} else {
1113						php_printf("%s<br />\n<b>%s</b>:  %s in <b>%s</b> on line <b>%d</b><br />\n%s", STR_PRINT(prepend_string), error_type_str, buffer, error_filename, error_lineno, STR_PRINT(append_string));
1114					}
1115				} else {
1116					/* Write CLI/CGI errors to stderr if display_errors = "stderr" */
1117					if ((!strcmp(sapi_module.name, "cli") || !strcmp(sapi_module.name, "cgi")) &&
1118						PG(display_errors) == PHP_DISPLAY_ERRORS_STDERR
1119					) {
1120#ifdef PHP_WIN32
1121						fprintf(stderr, "%s: %s in %s on line %u\n", error_type_str, buffer, error_filename, error_lineno);
1122						fflush(stderr);
1123#else
1124						fprintf(stderr, "%s: %s in %s on line %u\n", error_type_str, buffer, error_filename, error_lineno);
1125#endif
1126					} else {
1127						php_printf("%s\n%s: %s in %s on line %d\n%s", STR_PRINT(prepend_string), error_type_str, buffer, error_filename, error_lineno, STR_PRINT(append_string));
1128					}
1129				}
1130			}
1131		}
1132#if ZEND_DEBUG
1133		if (PG(report_zend_debug)) {
1134			zend_bool trigger_break;
1135
1136			switch (type) {
1137				case E_ERROR:
1138				case E_CORE_ERROR:
1139				case E_COMPILE_ERROR:
1140				case E_USER_ERROR:
1141					trigger_break=1;
1142					break;
1143				default:
1144					trigger_break=0;
1145					break;
1146			}
1147			zend_output_debug_string(trigger_break, "%s(%d) : %s - %s", error_filename, error_lineno, error_type_str, buffer);
1148		}
1149#endif
1150	}
1151
1152	/* Bail out if we can't recover */
1153	switch (type) {
1154		case E_CORE_ERROR:
1155			if(!module_initialized) {
1156				/* bad error in module startup - no way we can live with this */
1157				exit(-2);
1158			}
1159		/* no break - intentionally */
1160		case E_ERROR:
1161		case E_RECOVERABLE_ERROR:
1162		case E_PARSE:
1163		case E_COMPILE_ERROR:
1164		case E_USER_ERROR:
1165			EG(exit_status) = 255;
1166			if (module_initialized) {
1167				if (!PG(display_errors) &&
1168				    !SG(headers_sent) &&
1169					SG(sapi_headers).http_response_code == 200
1170				) {
1171					sapi_header_line ctr = {0};
1172
1173					ctr.line = "HTTP/1.0 500 Internal Server Error";
1174					ctr.line_len = sizeof("HTTP/1.0 500 Internal Server Error") - 1;
1175					sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
1176				}
1177				/* the parser would return 1 (failure), we can bail out nicely */
1178				if (type == E_PARSE) {
1179					CG(parse_error) = 0;
1180				} else {
1181					/* restore memory limit */
1182					zend_set_memory_limit(PG(memory_limit));
1183					efree(buffer);
1184					zend_objects_store_mark_destructed(&EG(objects_store));
1185					zend_bailout();
1186					return;
1187				}
1188			}
1189			break;
1190	}
1191
1192	/* Log if necessary */
1193	if (!display) {
1194		efree(buffer);
1195		return;
1196	}
1197
1198	if (PG(track_errors) && module_initialized && EG(valid_symbol_table)) {
1199		zval tmp;
1200
1201		ZVAL_STRINGL(&tmp, buffer, buffer_len);
1202		if (EG(current_execute_data)) {
1203			if (zend_set_local_var_str("php_errormsg", sizeof("php_errormsg")-1, &tmp, 0) == FAILURE) {
1204				zval_ptr_dtor(&tmp);
1205			}
1206		} else {
1207			zend_hash_str_update_ind(&EG(symbol_table), "php_errormsg", sizeof("php_errormsg")-1, &tmp);
1208		}
1209	}
1210
1211	efree(buffer);
1212}
1213/* }}} */
1214
1215/* {{{ php_get_current_user
1216 */
1217PHPAPI char *php_get_current_user(void)
1218{
1219	zend_stat_t *pstat;
1220
1221	if (SG(request_info).current_user) {
1222		return SG(request_info).current_user;
1223	}
1224
1225	/* FIXME: I need to have this somehow handled if
1226	USE_SAPI is defined, because cgi will also be
1227	interfaced in USE_SAPI */
1228
1229	pstat = sapi_get_stat();
1230
1231	if (!pstat) {
1232		return "";
1233	} else {
1234#ifdef PHP_WIN32
1235		char name[256];
1236		DWORD len = sizeof(name)-1;
1237
1238		if (!GetUserName(name, &len)) {
1239			return "";
1240		}
1241		name[len] = '\0';
1242		SG(request_info).current_user_length = len;
1243		SG(request_info).current_user = estrndup(name, len);
1244		return SG(request_info).current_user;
1245#else
1246		struct passwd *pwd;
1247#if defined(ZTS) && defined(HAVE_GETPWUID_R) && defined(_SC_GETPW_R_SIZE_MAX)
1248		struct passwd _pw;
1249		struct passwd *retpwptr = NULL;
1250		int pwbuflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1251		char *pwbuf;
1252
1253		if (pwbuflen < 1) {
1254			return "";
1255		}
1256		pwbuf = emalloc(pwbuflen);
1257		if (getpwuid_r(pstat->st_uid, &_pw, pwbuf, pwbuflen, &retpwptr) != 0) {
1258			efree(pwbuf);
1259			return "";
1260		}
1261		if (retpwptr == NULL) {
1262			efree(pwbuf);
1263			return "";
1264		}
1265		pwd = &_pw;
1266#else
1267		if ((pwd=getpwuid(pstat->st_uid))==NULL) {
1268			return "";
1269		}
1270#endif
1271		SG(request_info).current_user_length = strlen(pwd->pw_name);
1272		SG(request_info).current_user = estrndup(pwd->pw_name, SG(request_info).current_user_length);
1273#if defined(ZTS) && defined(HAVE_GETPWUID_R) && defined(_SC_GETPW_R_SIZE_MAX)
1274		efree(pwbuf);
1275#endif
1276		return SG(request_info).current_user;
1277#endif
1278	}
1279}
1280/* }}} */
1281
1282/* {{{ proto bool set_time_limit(int seconds)
1283   Sets the maximum time a script can run */
1284PHP_FUNCTION(set_time_limit)
1285{
1286	zend_long new_timeout;
1287	char *new_timeout_str;
1288	int new_timeout_strlen;
1289	zend_string *key;
1290
1291	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &new_timeout) == FAILURE) {
1292		return;
1293	}
1294
1295	new_timeout_strlen = (int)zend_spprintf(&new_timeout_str, 0, ZEND_LONG_FMT, new_timeout);
1296
1297	key = zend_string_init("max_execution_time", sizeof("max_execution_time")-1, 0);
1298	if (zend_alter_ini_entry_chars_ex(key, new_timeout_str, new_timeout_strlen, PHP_INI_USER, PHP_INI_STAGE_RUNTIME, 0) == SUCCESS) {
1299		RETVAL_TRUE;
1300	} else {
1301		RETVAL_FALSE;
1302	}
1303	zend_string_release(key);
1304	efree(new_timeout_str);
1305}
1306/* }}} */
1307
1308/* {{{ php_fopen_wrapper_for_zend
1309 */
1310static FILE *php_fopen_wrapper_for_zend(const char *filename, zend_string **opened_path)
1311{
1312	return php_stream_open_wrapper_as_file((char *)filename, "rb", USE_PATH|IGNORE_URL_WIN|REPORT_ERRORS|STREAM_OPEN_FOR_INCLUDE, opened_path);
1313}
1314/* }}} */
1315
1316static void php_zend_stream_closer(void *handle) /* {{{ */
1317{
1318	php_stream_close((php_stream*)handle);
1319}
1320/* }}} */
1321
1322static void php_zend_stream_mmap_closer(void *handle) /* {{{ */
1323{
1324	php_stream_mmap_unmap((php_stream*)handle);
1325	php_zend_stream_closer(handle);
1326}
1327/* }}} */
1328
1329static size_t php_zend_stream_fsizer(void *handle) /* {{{ */
1330{
1331	php_stream_statbuf  ssb;
1332	if (php_stream_stat((php_stream*)handle, &ssb) == 0) {
1333		return ssb.sb.st_size;
1334	}
1335	return 0;
1336}
1337/* }}} */
1338
1339static int php_stream_open_for_zend(const char *filename, zend_file_handle *handle) /* {{{ */
1340{
1341	return php_stream_open_for_zend_ex(filename, handle, USE_PATH|REPORT_ERRORS|STREAM_OPEN_FOR_INCLUDE);
1342}
1343/* }}} */
1344
1345PHPAPI int php_stream_open_for_zend_ex(const char *filename, zend_file_handle *handle, int mode) /* {{{ */
1346{
1347	char *p;
1348	size_t len, mapped_len;
1349	php_stream *stream = php_stream_open_wrapper((char *)filename, "rb", mode, &handle->opened_path);
1350
1351	if (stream) {
1352#if HAVE_MMAP || defined(PHP_WIN32)
1353		size_t page_size = REAL_PAGE_SIZE;
1354#endif
1355
1356		handle->filename = (char*)filename;
1357		handle->free_filename = 0;
1358		handle->handle.stream.handle  = stream;
1359		handle->handle.stream.reader  = (zend_stream_reader_t)_php_stream_read;
1360		handle->handle.stream.fsizer  = php_zend_stream_fsizer;
1361		handle->handle.stream.isatty  = 0;
1362		/* can we mmap immediately? */
1363		memset(&handle->handle.stream.mmap, 0, sizeof(handle->handle.stream.mmap));
1364		len = php_zend_stream_fsizer(stream);
1365		if (len != 0
1366#if HAVE_MMAP || defined(PHP_WIN32)
1367		&& ((len - 1) % page_size) <= page_size - ZEND_MMAP_AHEAD
1368#endif
1369		&& php_stream_mmap_possible(stream)
1370		&& (p = php_stream_mmap_range(stream, 0, len, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped_len)) != NULL) {
1371			handle->handle.stream.closer   = php_zend_stream_mmap_closer;
1372			handle->handle.stream.mmap.buf = p;
1373			handle->handle.stream.mmap.len = mapped_len;
1374			handle->type = ZEND_HANDLE_MAPPED;
1375		} else {
1376			handle->handle.stream.closer = php_zend_stream_closer;
1377			handle->type = ZEND_HANDLE_STREAM;
1378		}
1379		/* suppress warning if this stream is not explicitly closed */
1380		php_stream_auto_cleanup(stream);
1381
1382		return SUCCESS;
1383	}
1384	return FAILURE;
1385}
1386/* }}} */
1387
1388static zend_string *php_resolve_path_for_zend(const char *filename, int filename_len) /* {{{ */
1389{
1390	return php_resolve_path(filename, filename_len, PG(include_path));
1391}
1392/* }}} */
1393
1394/* {{{ php_get_configuration_directive_for_zend
1395 */
1396static zval *php_get_configuration_directive_for_zend(zend_string *name)
1397{
1398	return cfg_get_entry_ex(name);
1399}
1400/* }}} */
1401
1402/* {{{ php_free_request_globals
1403 */
1404static void php_free_request_globals(void)
1405{
1406	if (PG(last_error_message)) {
1407		free(PG(last_error_message));
1408		PG(last_error_message) = NULL;
1409	}
1410	if (PG(last_error_file)) {
1411		free(PG(last_error_file));
1412		PG(last_error_file) = NULL;
1413	}
1414	if (PG(php_sys_temp_dir)) {
1415		efree(PG(php_sys_temp_dir));
1416		PG(php_sys_temp_dir) = NULL;
1417	}
1418}
1419/* }}} */
1420
1421/* {{{ php_message_handler_for_zend
1422 */
1423static ZEND_COLD void php_message_handler_for_zend(zend_long message, const void *data)
1424{
1425	switch (message) {
1426		case ZMSG_FAILED_INCLUDE_FOPEN:
1427			php_error_docref("function.include", E_WARNING, "Failed opening '%s' for inclusion (include_path='%s')", php_strip_url_passwd((char *) data), STR_PRINT(PG(include_path)));
1428			break;
1429		case ZMSG_FAILED_REQUIRE_FOPEN:
1430			php_error_docref("function.require", E_COMPILE_ERROR, "Failed opening required '%s' (include_path='%s')", php_strip_url_passwd((char *) data), STR_PRINT(PG(include_path)));
1431			break;
1432		case ZMSG_FAILED_HIGHLIGHT_FOPEN:
1433			php_error_docref(NULL, E_WARNING, "Failed opening '%s' for highlighting", php_strip_url_passwd((char *) data));
1434			break;
1435		case ZMSG_MEMORY_LEAK_DETECTED:
1436		case ZMSG_MEMORY_LEAK_REPEATED:
1437#if ZEND_DEBUG
1438			if (EG(error_reporting) & E_WARNING) {
1439				char memory_leak_buf[1024];
1440
1441				if (message==ZMSG_MEMORY_LEAK_DETECTED) {
1442					zend_leak_info *t = (zend_leak_info *) data;
1443
1444					snprintf(memory_leak_buf, 512, "%s(%d) :  Freeing 0x%.8lX (%zu bytes), script=%s\n", t->filename, t->lineno, (zend_uintptr_t)t->addr, t->size, SAFE_FILENAME(SG(request_info).path_translated));
1445					if (t->orig_filename) {
1446						char relay_buf[512];
1447
1448						snprintf(relay_buf, 512, "%s(%d) : Actual location (location was relayed)\n", t->orig_filename, t->orig_lineno);
1449						strlcat(memory_leak_buf, relay_buf, sizeof(memory_leak_buf));
1450					}
1451				} else {
1452					unsigned long leak_count = (zend_uintptr_t) data;
1453
1454					snprintf(memory_leak_buf, 512, "Last leak repeated %ld time%s\n", leak_count, (leak_count>1?"s":""));
1455				}
1456#	if defined(PHP_WIN32)
1457				OutputDebugString(memory_leak_buf);
1458#	else
1459				fprintf(stderr, "%s", memory_leak_buf);
1460#	endif
1461			}
1462#endif
1463			break;
1464		case ZMSG_MEMORY_LEAKS_GRAND_TOTAL:
1465#if ZEND_DEBUG
1466			if (EG(error_reporting) & E_WARNING) {
1467				char memory_leak_buf[512];
1468
1469				snprintf(memory_leak_buf, 512, "=== Total %d memory leaks detected ===\n", *((uint32_t *) data));
1470#	if defined(PHP_WIN32)
1471				OutputDebugString(memory_leak_buf);
1472#	else
1473				fprintf(stderr, "%s", memory_leak_buf);
1474#	endif
1475			}
1476#endif
1477			break;
1478		case ZMSG_LOG_SCRIPT_NAME: {
1479				struct tm *ta, tmbuf;
1480				time_t curtime;
1481				char *datetime_str, asctimebuf[52];
1482				char memory_leak_buf[4096];
1483
1484				time(&curtime);
1485				ta = php_localtime_r(&curtime, &tmbuf);
1486				datetime_str = php_asctime_r(ta, asctimebuf);
1487				if (datetime_str) {
1488					datetime_str[strlen(datetime_str)-1]=0;	/* get rid of the trailing newline */
1489					snprintf(memory_leak_buf, sizeof(memory_leak_buf), "[%s]  Script:  '%s'\n", datetime_str, SAFE_FILENAME(SG(request_info).path_translated));
1490				} else {
1491					snprintf(memory_leak_buf, sizeof(memory_leak_buf), "[null]  Script:  '%s'\n", SAFE_FILENAME(SG(request_info).path_translated));
1492				}
1493#	if defined(PHP_WIN32)
1494				OutputDebugString(memory_leak_buf);
1495#	else
1496				fprintf(stderr, "%s", memory_leak_buf);
1497#	endif
1498			}
1499			break;
1500	}
1501}
1502/* }}} */
1503
1504
1505void php_on_timeout(int seconds)
1506{
1507	PG(connection_status) |= PHP_CONNECTION_TIMEOUT;
1508	zend_set_timeout(EG(timeout_seconds), 1);
1509	if(PG(exit_on_timeout)) sapi_terminate_process();
1510}
1511
1512#if PHP_SIGCHILD
1513/* {{{ sigchld_handler
1514 */
1515static void sigchld_handler(int apar)
1516{
1517	int errno_save = errno;
1518
1519	while (waitpid(-1, NULL, WNOHANG) > 0);
1520	signal(SIGCHLD, sigchld_handler);
1521
1522	errno = errno_save;
1523}
1524/* }}} */
1525#endif
1526
1527/* {{{ php_start_sapi()
1528 */
1529static int php_start_sapi(void)
1530{
1531	int retval = SUCCESS;
1532
1533	if(!SG(sapi_started)) {
1534		zend_try {
1535			PG(during_request_startup) = 1;
1536
1537			/* initialize global variables */
1538			PG(modules_activated) = 0;
1539			PG(header_is_being_sent) = 0;
1540			PG(connection_status) = PHP_CONNECTION_NORMAL;
1541
1542			zend_activate();
1543			zend_set_timeout(EG(timeout_seconds), 1);
1544			zend_activate_modules();
1545			PG(modules_activated)=1;
1546		} zend_catch {
1547			retval = FAILURE;
1548		} zend_end_try();
1549
1550		SG(sapi_started) = 1;
1551	}
1552	return retval;
1553}
1554
1555/* }}} */
1556
1557/* {{{ php_request_startup
1558 */
1559#ifndef APACHE_HOOKS
1560int php_request_startup(void)
1561{
1562	int retval = SUCCESS;
1563
1564#ifdef HAVE_DTRACE
1565	DTRACE_REQUEST_STARTUP(SAFE_FILENAME(SG(request_info).path_translated), SAFE_FILENAME(SG(request_info).request_uri), (char *)SAFE_FILENAME(SG(request_info).request_method));
1566#endif /* HAVE_DTRACE */
1567
1568#ifdef PHP_WIN32
1569	PG(com_initialized) = 0;
1570#endif
1571
1572#if PHP_SIGCHILD
1573	signal(SIGCHLD, sigchld_handler);
1574#endif
1575
1576	zend_try {
1577		PG(in_error_log) = 0;
1578		PG(during_request_startup) = 1;
1579
1580		php_output_activate();
1581
1582		/* initialize global variables */
1583		PG(modules_activated) = 0;
1584		PG(header_is_being_sent) = 0;
1585		PG(connection_status) = PHP_CONNECTION_NORMAL;
1586		PG(in_user_include) = 0;
1587
1588		zend_activate();
1589		sapi_activate();
1590
1591#ifdef ZEND_SIGNALS
1592		zend_signal_activate();
1593#endif
1594
1595		if (PG(max_input_time) == -1) {
1596			zend_set_timeout(EG(timeout_seconds), 1);
1597		} else {
1598			zend_set_timeout(PG(max_input_time), 1);
1599		}
1600
1601		/* Disable realpath cache if an open_basedir is set */
1602		if (PG(open_basedir) && *PG(open_basedir)) {
1603			CWDG(realpath_cache_size_limit) = 0;
1604		}
1605
1606		if (PG(expose_php)) {
1607			sapi_add_header(SAPI_PHP_VERSION_HEADER, sizeof(SAPI_PHP_VERSION_HEADER)-1, 1);
1608		}
1609
1610		if (PG(output_handler) && PG(output_handler)[0]) {
1611			zval oh;
1612
1613			ZVAL_STRING(&oh, PG(output_handler));
1614			php_output_start_user(&oh, 0, PHP_OUTPUT_HANDLER_STDFLAGS);
1615			zval_ptr_dtor(&oh);
1616		} else if (PG(output_buffering)) {
1617			php_output_start_user(NULL, PG(output_buffering) > 1 ? PG(output_buffering) : 0, PHP_OUTPUT_HANDLER_STDFLAGS);
1618		} else if (PG(implicit_flush)) {
1619			php_output_set_implicit_flush(1);
1620		}
1621
1622		/* We turn this off in php_execute_script() */
1623		/* PG(during_request_startup) = 0; */
1624
1625		php_hash_environment();
1626		zend_activate_modules();
1627		PG(modules_activated)=1;
1628	} zend_catch {
1629		retval = FAILURE;
1630	} zend_end_try();
1631
1632	SG(sapi_started) = 1;
1633
1634	return retval;
1635}
1636# else
1637int php_request_startup(void)
1638{
1639	int retval = SUCCESS;
1640
1641#if PHP_SIGCHILD
1642	signal(SIGCHLD, sigchld_handler);
1643#endif
1644
1645	if (php_start_sapi() == FAILURE) {
1646		return FAILURE;
1647	}
1648
1649	php_output_activate();
1650	sapi_activate();
1651	php_hash_environment();
1652
1653	zend_try {
1654		PG(during_request_startup) = 1;
1655		if (PG(expose_php)) {
1656			sapi_add_header(SAPI_PHP_VERSION_HEADER, sizeof(SAPI_PHP_VERSION_HEADER)-1, 1);
1657		}
1658	} zend_catch {
1659		retval = FAILURE;
1660	} zend_end_try();
1661
1662	return retval;
1663}
1664# endif
1665/* }}} */
1666
1667/* {{{ php_request_startup_for_hook
1668 */
1669int php_request_startup_for_hook(void)
1670{
1671	int retval = SUCCESS;
1672
1673#if PHP_SIGCHLD
1674	signal(SIGCHLD, sigchld_handler);
1675#endif
1676
1677	if (php_start_sapi() == FAILURE) {
1678		return FAILURE;
1679	}
1680
1681	php_output_activate();
1682	sapi_activate_headers_only();
1683	php_hash_environment();
1684
1685	return retval;
1686}
1687/* }}} */
1688
1689/* {{{ php_request_shutdown_for_exec
1690 */
1691void php_request_shutdown_for_exec(void *dummy)
1692{
1693
1694	/* used to close fd's in the 3..255 range here, but it's problematic
1695	 */
1696	shutdown_memory_manager(1, 1);
1697	zend_interned_strings_restore();
1698}
1699/* }}} */
1700
1701/* {{{ php_request_shutdown_for_hook
1702 */
1703void php_request_shutdown_for_hook(void *dummy)
1704{
1705
1706	if (PG(modules_activated)) zend_try {
1707		php_call_shutdown_functions();
1708	} zend_end_try();
1709
1710	if (PG(modules_activated)) {
1711		zend_deactivate_modules();
1712		php_free_shutdown_functions();
1713	}
1714
1715	zend_try {
1716		zend_unset_timeout();
1717	} zend_end_try();
1718
1719	zend_try {
1720		int i;
1721
1722		for (i = 0; i < NUM_TRACK_VARS; i++) {
1723			zval_ptr_dtor(&PG(http_globals)[i]);
1724		}
1725	} zend_end_try();
1726
1727	zend_deactivate();
1728
1729	zend_try {
1730		sapi_deactivate();
1731	} zend_end_try();
1732
1733	zend_try {
1734		php_shutdown_stream_hashes();
1735	} zend_end_try();
1736
1737	zend_try {
1738		shutdown_memory_manager(CG(unclean_shutdown), 0);
1739	} zend_end_try();
1740
1741	zend_interned_strings_restore();
1742
1743#ifdef ZEND_SIGNALS
1744	zend_try {
1745		zend_signal_deactivate();
1746	} zend_end_try();
1747#endif
1748}
1749
1750/* }}} */
1751
1752/* {{{ php_request_shutdown
1753 */
1754void php_request_shutdown(void *dummy)
1755{
1756	zend_bool report_memleaks;
1757
1758	report_memleaks = PG(report_memleaks);
1759
1760	/* EG(current_execute_data) points into nirvana and therefore cannot be safely accessed
1761	 * inside zend_executor callback functions.
1762	 */
1763	EG(current_execute_data) = NULL;
1764
1765	php_deactivate_ticks();
1766
1767	/* 1. Call all possible shutdown functions registered with register_shutdown_function() */
1768	if (PG(modules_activated)) zend_try {
1769		php_call_shutdown_functions();
1770	} zend_end_try();
1771
1772	/* 2. Call all possible __destruct() functions */
1773	zend_try {
1774		zend_call_destructors();
1775	} zend_end_try();
1776
1777	/* 3. Flush all output buffers */
1778	zend_try {
1779		zend_bool send_buffer = SG(request_info).headers_only ? 0 : 1;
1780
1781		if (CG(unclean_shutdown) && PG(last_error_type) == E_ERROR &&
1782			(size_t)PG(memory_limit) < zend_memory_usage(1)
1783		) {
1784			send_buffer = 0;
1785		}
1786
1787		if (!send_buffer) {
1788			php_output_discard_all();
1789		} else {
1790			php_output_end_all();
1791		}
1792	} zend_end_try();
1793
1794	/* 4. Reset max_execution_time (no longer executing php code after response sent) */
1795	zend_try {
1796		zend_unset_timeout();
1797	} zend_end_try();
1798
1799	/* 5. Call all extensions RSHUTDOWN functions */
1800	if (PG(modules_activated)) {
1801		zend_deactivate_modules();
1802		php_free_shutdown_functions();
1803	}
1804
1805	/* 6. Shutdown output layer (send the set HTTP headers, cleanup output handlers, etc.) */
1806	zend_try {
1807		php_output_deactivate();
1808	} zend_end_try();
1809
1810	/* 7. Destroy super-globals */
1811	zend_try {
1812		int i;
1813
1814		for (i=0; i<NUM_TRACK_VARS; i++) {
1815			zval_ptr_dtor(&PG(http_globals)[i]);
1816		}
1817	} zend_end_try();
1818
1819	/* 8. free request-bound globals */
1820	php_free_request_globals();
1821
1822	/* 9. Shutdown scanner/executor/compiler and restore ini entries */
1823	zend_deactivate();
1824
1825	/* 10. Call all extensions post-RSHUTDOWN functions */
1826	zend_try {
1827		zend_post_deactivate_modules();
1828	} zend_end_try();
1829
1830	/* 11. SAPI related shutdown (free stuff) */
1831	zend_try {
1832		sapi_deactivate();
1833	} zend_end_try();
1834
1835	/* 12. free virtual CWD memory */
1836	virtual_cwd_deactivate();
1837
1838	/* 13. Destroy stream hashes */
1839	zend_try {
1840		php_shutdown_stream_hashes();
1841	} zend_end_try();
1842
1843	/* 14. Free Willy (here be crashes) */
1844	zend_interned_strings_restore();
1845	zend_try {
1846		shutdown_memory_manager(CG(unclean_shutdown) || !report_memleaks, 0);
1847	} zend_end_try();
1848
1849	/* 15. Reset max_execution_time */
1850	zend_try {
1851		zend_unset_timeout();
1852	} zend_end_try();
1853
1854#ifdef PHP_WIN32
1855	if (PG(com_initialized)) {
1856		CoUninitialize();
1857		PG(com_initialized) = 0;
1858	}
1859#endif
1860
1861#ifdef HAVE_DTRACE
1862	DTRACE_REQUEST_SHUTDOWN(SAFE_FILENAME(SG(request_info).path_translated), SAFE_FILENAME(SG(request_info).request_uri), (char *)SAFE_FILENAME(SG(request_info).request_method));
1863#endif /* HAVE_DTRACE */
1864}
1865/* }}} */
1866
1867/* {{{ php_com_initialize
1868 */
1869PHPAPI void php_com_initialize(void)
1870{
1871#ifdef PHP_WIN32
1872	if (!PG(com_initialized)) {
1873		if (CoInitialize(NULL) == S_OK) {
1874			PG(com_initialized) = 1;
1875		}
1876	}
1877#endif
1878}
1879/* }}} */
1880
1881/* {{{ php_output_wrapper
1882 */
1883static size_t php_output_wrapper(const char *str, size_t str_length)
1884{
1885	return php_output_write(str, str_length);
1886}
1887/* }}} */
1888
1889#ifdef ZTS
1890/* {{{ core_globals_ctor
1891 */
1892static void core_globals_ctor(php_core_globals *core_globals)
1893{
1894	memset(core_globals, 0, sizeof(*core_globals));
1895}
1896/* }}} */
1897#endif
1898
1899/* {{{ core_globals_dtor
1900 */
1901static void core_globals_dtor(php_core_globals *core_globals)
1902{
1903	if (core_globals->last_error_message) {
1904		free(core_globals->last_error_message);
1905	}
1906	if (core_globals->last_error_file) {
1907		free(core_globals->last_error_file);
1908	}
1909	if (core_globals->disable_functions) {
1910		free(core_globals->disable_functions);
1911	}
1912	if (core_globals->disable_classes) {
1913		free(core_globals->disable_classes);
1914	}
1915	if (core_globals->php_binary) {
1916		free(core_globals->php_binary);
1917	}
1918
1919	php_shutdown_ticks();
1920}
1921/* }}} */
1922
1923PHP_MINFO_FUNCTION(php_core) { /* {{{ */
1924	php_info_print_table_start();
1925	php_info_print_table_row(2, "PHP Version", PHP_VERSION);
1926	php_info_print_table_end();
1927	DISPLAY_INI_ENTRIES();
1928}
1929/* }}} */
1930
1931/* {{{ php_register_extensions
1932 */
1933int php_register_extensions(zend_module_entry **ptr, int count)
1934{
1935	zend_module_entry **end = ptr + count;
1936
1937	while (ptr < end) {
1938		if (*ptr) {
1939			if (zend_register_internal_module(*ptr)==NULL) {
1940				return FAILURE;
1941			}
1942		}
1943		ptr++;
1944	}
1945	return SUCCESS;
1946}
1947
1948/* A very long time ago php_module_startup() was refactored in a way
1949 * which broke calling it with more than one additional module.
1950 * This alternative to php_register_extensions() works around that
1951 * by walking the shallower structure.
1952 *
1953 * See algo: https://bugs.php.net/bug.php?id=63159
1954 */
1955static int php_register_extensions_bc(zend_module_entry *ptr, int count)
1956{
1957	while (count--) {
1958		if (zend_register_internal_module(ptr++) == NULL) {
1959			return FAILURE;
1960 		}
1961	}
1962	return SUCCESS;
1963}
1964/* }}} */
1965
1966#ifdef PHP_WIN32
1967static _invalid_parameter_handler old_invalid_parameter_handler;
1968
1969void dummy_invalid_parameter_handler(
1970		const wchar_t *expression,
1971		const wchar_t *function,
1972		const wchar_t *file,
1973		unsigned int   line,
1974		uintptr_t      pEwserved)
1975{
1976	static int called = 0;
1977	char buf[1024];
1978	int len;
1979
1980	if (!called) {
1981			if(PG(windows_show_crt_warning)) {
1982			called = 1;
1983			if (function) {
1984				if (file) {
1985					len = _snprintf(buf, sizeof(buf)-1, "Invalid parameter detected in CRT function '%ws' (%ws:%u)", function, file, line);
1986				} else {
1987					len = _snprintf(buf, sizeof(buf)-1, "Invalid parameter detected in CRT function '%ws'", function);
1988				}
1989			} else {
1990				len = _snprintf(buf, sizeof(buf)-1, "Invalid CRT parameter detected (function not known)");
1991			}
1992			zend_error(E_WARNING, "%s", buf);
1993			called = 0;
1994		}
1995	}
1996}
1997#endif
1998
1999/* {{{ php_module_startup
2000 */
2001int php_module_startup(sapi_module_struct *sf, zend_module_entry *additional_modules, uint num_additional_modules)
2002{
2003	zend_utility_functions zuf;
2004	zend_utility_values zuv;
2005	int retval = SUCCESS, module_number=0;	/* for REGISTER_INI_ENTRIES() */
2006	char *php_os;
2007	zend_module_entry *module;
2008
2009#if defined(PHP_WIN32) || (defined(NETWARE) && defined(USE_WINSOCK))
2010	WORD wVersionRequested = MAKEWORD(2, 0);
2011	WSADATA wsaData;
2012#endif
2013#ifdef PHP_WIN32
2014	php_os = "WINNT";
2015
2016	old_invalid_parameter_handler =
2017		_set_invalid_parameter_handler(dummy_invalid_parameter_handler);
2018	if (old_invalid_parameter_handler != NULL) {
2019		_set_invalid_parameter_handler(old_invalid_parameter_handler);
2020	}
2021
2022	/* Disable the message box for assertions.*/
2023	_CrtSetReportMode(_CRT_ASSERT, 0);
2024#else
2025	php_os = PHP_OS;
2026#endif
2027
2028#ifdef ZTS
2029	(void)ts_resource(0);
2030#endif
2031
2032#ifdef PHP_WIN32
2033	php_win32_init_rng_lock();
2034#endif
2035
2036	module_shutdown = 0;
2037	module_startup = 1;
2038	sapi_initialize_empty_request();
2039	sapi_activate();
2040
2041	if (module_initialized) {
2042		return SUCCESS;
2043	}
2044
2045	sapi_module = *sf;
2046
2047	php_output_startup();
2048
2049#ifdef ZTS
2050	ts_allocate_id(&core_globals_id, sizeof(php_core_globals), (ts_allocate_ctor) core_globals_ctor, (ts_allocate_dtor) core_globals_dtor);
2051	php_startup_ticks();
2052#ifdef PHP_WIN32
2053	ts_allocate_id(&php_win32_core_globals_id, sizeof(php_win32_core_globals), (ts_allocate_ctor) php_win32_core_globals_ctor, (ts_allocate_dtor) php_win32_core_globals_dtor);
2054#endif
2055#else
2056	php_startup_ticks();
2057#endif
2058	gc_globals_ctor();
2059
2060	zuf.error_function = php_error_cb;
2061	zuf.printf_function = php_printf;
2062	zuf.write_function = php_output_wrapper;
2063	zuf.fopen_function = php_fopen_wrapper_for_zend;
2064	zuf.message_handler = php_message_handler_for_zend;
2065	zuf.block_interruptions = sapi_module.block_interruptions;
2066	zuf.unblock_interruptions = sapi_module.unblock_interruptions;
2067	zuf.get_configuration_directive = php_get_configuration_directive_for_zend;
2068	zuf.ticks_function = php_run_ticks;
2069	zuf.on_timeout = php_on_timeout;
2070	zuf.stream_open_function = php_stream_open_for_zend;
2071	zuf.vspprintf_function = vspprintf;
2072	zuf.vstrpprintf_function = vstrpprintf;
2073	zuf.getenv_function = sapi_getenv;
2074	zuf.resolve_path_function = php_resolve_path_for_zend;
2075	zend_startup(&zuf, NULL);
2076
2077#if HAVE_SETLOCALE
2078	setlocale(LC_CTYPE, "");
2079	zend_update_current_locale();
2080#endif
2081
2082#if HAVE_TZSET
2083	tzset();
2084#endif
2085
2086#if defined(PHP_WIN32) || (defined(NETWARE) && defined(USE_WINSOCK))
2087	/* start up winsock services */
2088	if (WSAStartup(wVersionRequested, &wsaData) != 0) {
2089		php_printf("\nwinsock.dll unusable. %d\n", WSAGetLastError());
2090		return FAILURE;
2091	}
2092#endif
2093
2094	le_index_ptr = zend_register_list_destructors_ex(NULL, NULL, "index pointer", 0);
2095
2096	/* Register constants */
2097	REGISTER_MAIN_STRINGL_CONSTANT("PHP_VERSION", PHP_VERSION, sizeof(PHP_VERSION)-1, CONST_PERSISTENT | CONST_CS);
2098	REGISTER_MAIN_LONG_CONSTANT("PHP_MAJOR_VERSION", PHP_MAJOR_VERSION, CONST_PERSISTENT | CONST_CS);
2099	REGISTER_MAIN_LONG_CONSTANT("PHP_MINOR_VERSION", PHP_MINOR_VERSION, CONST_PERSISTENT | CONST_CS);
2100	REGISTER_MAIN_LONG_CONSTANT("PHP_RELEASE_VERSION", PHP_RELEASE_VERSION, CONST_PERSISTENT | CONST_CS);
2101	REGISTER_MAIN_STRINGL_CONSTANT("PHP_EXTRA_VERSION", PHP_EXTRA_VERSION, sizeof(PHP_EXTRA_VERSION) - 1, CONST_PERSISTENT | CONST_CS);
2102	REGISTER_MAIN_LONG_CONSTANT("PHP_VERSION_ID", PHP_VERSION_ID, CONST_PERSISTENT | CONST_CS);
2103#ifdef ZTS
2104	REGISTER_MAIN_LONG_CONSTANT("PHP_ZTS", 1, CONST_PERSISTENT | CONST_CS);
2105#else
2106	REGISTER_MAIN_LONG_CONSTANT("PHP_ZTS", 0, CONST_PERSISTENT | CONST_CS);
2107#endif
2108	REGISTER_MAIN_LONG_CONSTANT("PHP_DEBUG", PHP_DEBUG, CONST_PERSISTENT | CONST_CS);
2109	REGISTER_MAIN_STRINGL_CONSTANT("PHP_OS", php_os, strlen(php_os), CONST_PERSISTENT | CONST_CS);
2110	REGISTER_MAIN_STRINGL_CONSTANT("PHP_SAPI", sapi_module.name, strlen(sapi_module.name), CONST_PERSISTENT | CONST_CS);
2111	REGISTER_MAIN_STRINGL_CONSTANT("DEFAULT_INCLUDE_PATH", PHP_INCLUDE_PATH, sizeof(PHP_INCLUDE_PATH)-1, CONST_PERSISTENT | CONST_CS);
2112	REGISTER_MAIN_STRINGL_CONSTANT("PEAR_INSTALL_DIR", PEAR_INSTALLDIR, sizeof(PEAR_INSTALLDIR)-1, CONST_PERSISTENT | CONST_CS);
2113	REGISTER_MAIN_STRINGL_CONSTANT("PEAR_EXTENSION_DIR", PHP_EXTENSION_DIR, sizeof(PHP_EXTENSION_DIR)-1, CONST_PERSISTENT | CONST_CS);
2114	REGISTER_MAIN_STRINGL_CONSTANT("PHP_EXTENSION_DIR", PHP_EXTENSION_DIR, sizeof(PHP_EXTENSION_DIR)-1, CONST_PERSISTENT | CONST_CS);
2115	REGISTER_MAIN_STRINGL_CONSTANT("PHP_PREFIX", PHP_PREFIX, sizeof(PHP_PREFIX)-1, CONST_PERSISTENT | CONST_CS);
2116	REGISTER_MAIN_STRINGL_CONSTANT("PHP_BINDIR", PHP_BINDIR, sizeof(PHP_BINDIR)-1, CONST_PERSISTENT | CONST_CS);
2117#ifndef PHP_WIN32
2118	REGISTER_MAIN_STRINGL_CONSTANT("PHP_MANDIR", PHP_MANDIR, sizeof(PHP_MANDIR)-1, CONST_PERSISTENT | CONST_CS);
2119#endif
2120	REGISTER_MAIN_STRINGL_CONSTANT("PHP_LIBDIR", PHP_LIBDIR, sizeof(PHP_LIBDIR)-1, CONST_PERSISTENT | CONST_CS);
2121	REGISTER_MAIN_STRINGL_CONSTANT("PHP_DATADIR", PHP_DATADIR, sizeof(PHP_DATADIR)-1, CONST_PERSISTENT | CONST_CS);
2122	REGISTER_MAIN_STRINGL_CONSTANT("PHP_SYSCONFDIR", PHP_SYSCONFDIR, sizeof(PHP_SYSCONFDIR)-1, CONST_PERSISTENT | CONST_CS);
2123	REGISTER_MAIN_STRINGL_CONSTANT("PHP_LOCALSTATEDIR", PHP_LOCALSTATEDIR, sizeof(PHP_LOCALSTATEDIR)-1, CONST_PERSISTENT | CONST_CS);
2124	REGISTER_MAIN_STRINGL_CONSTANT("PHP_CONFIG_FILE_PATH", PHP_CONFIG_FILE_PATH, strlen(PHP_CONFIG_FILE_PATH), CONST_PERSISTENT | CONST_CS);
2125	REGISTER_MAIN_STRINGL_CONSTANT("PHP_CONFIG_FILE_SCAN_DIR", PHP_CONFIG_FILE_SCAN_DIR, sizeof(PHP_CONFIG_FILE_SCAN_DIR)-1, CONST_PERSISTENT | CONST_CS);
2126	REGISTER_MAIN_STRINGL_CONSTANT("PHP_SHLIB_SUFFIX", PHP_SHLIB_SUFFIX, sizeof(PHP_SHLIB_SUFFIX)-1, CONST_PERSISTENT | CONST_CS);
2127	REGISTER_MAIN_STRINGL_CONSTANT("PHP_EOL", PHP_EOL, sizeof(PHP_EOL)-1, CONST_PERSISTENT | CONST_CS);
2128	REGISTER_MAIN_LONG_CONSTANT("PHP_MAXPATHLEN", MAXPATHLEN, CONST_PERSISTENT | CONST_CS);
2129	REGISTER_MAIN_LONG_CONSTANT("PHP_INT_MAX", ZEND_LONG_MAX, CONST_PERSISTENT | CONST_CS);
2130	REGISTER_MAIN_LONG_CONSTANT("PHP_INT_MIN", ZEND_LONG_MIN, CONST_PERSISTENT | CONST_CS);
2131	REGISTER_MAIN_LONG_CONSTANT("PHP_INT_SIZE", SIZEOF_ZEND_LONG, CONST_PERSISTENT | CONST_CS);
2132
2133#ifdef PHP_WIN32
2134	REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_MAJOR",      EG(windows_version_info).dwMajorVersion, CONST_PERSISTENT | CONST_CS);
2135	REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_MINOR",      EG(windows_version_info).dwMinorVersion, CONST_PERSISTENT | CONST_CS);
2136	REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_BUILD",      EG(windows_version_info).dwBuildNumber, CONST_PERSISTENT | CONST_CS);
2137	REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_PLATFORM",   EG(windows_version_info).dwPlatformId, CONST_PERSISTENT | CONST_CS);
2138	REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_SP_MAJOR",   EG(windows_version_info).wServicePackMajor, CONST_PERSISTENT | CONST_CS);
2139	REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_SP_MINOR",   EG(windows_version_info).wServicePackMinor, CONST_PERSISTENT | CONST_CS);
2140	REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_SUITEMASK",  EG(windows_version_info).wSuiteMask, CONST_PERSISTENT | CONST_CS);
2141	REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_PRODUCTTYPE", EG(windows_version_info).wProductType, CONST_PERSISTENT | CONST_CS);
2142	REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_NT_DOMAIN_CONTROLLER", VER_NT_DOMAIN_CONTROLLER, CONST_PERSISTENT | CONST_CS);
2143	REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_NT_SERVER", VER_NT_SERVER, CONST_PERSISTENT | CONST_CS);
2144	REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_NT_WORKSTATION", VER_NT_WORKSTATION, CONST_PERSISTENT | CONST_CS);
2145#endif
2146
2147	php_binary_init();
2148	if (PG(php_binary)) {
2149		REGISTER_MAIN_STRINGL_CONSTANT("PHP_BINARY", PG(php_binary), strlen(PG(php_binary)), CONST_PERSISTENT | CONST_CS);
2150	} else {
2151		REGISTER_MAIN_STRINGL_CONSTANT("PHP_BINARY", "", 0, CONST_PERSISTENT | CONST_CS);
2152	}
2153
2154	php_output_register_constants();
2155	php_rfc1867_register_constants();
2156
2157	/* this will read in php.ini, set up the configuration parameters,
2158	   load zend extensions and register php function extensions
2159	   to be loaded later */
2160	if (php_init_config() == FAILURE) {
2161		return FAILURE;
2162	}
2163
2164	/* Register PHP core ini entries */
2165	REGISTER_INI_ENTRIES();
2166
2167	/* Register Zend ini entries */
2168	zend_register_standard_ini_entries();
2169
2170	/* Disable realpath cache if an open_basedir is set */
2171	if (PG(open_basedir) && *PG(open_basedir)) {
2172		CWDG(realpath_cache_size_limit) = 0;
2173	}
2174
2175	/* initialize stream wrappers registry
2176	 * (this uses configuration parameters from php.ini)
2177	 */
2178	if (php_init_stream_wrappers(module_number) == FAILURE)	{
2179		php_printf("PHP:  Unable to initialize stream url wrappers.\n");
2180		return FAILURE;
2181	}
2182
2183	zuv.html_errors = 1;
2184	zuv.import_use_extension = ".php";
2185	zuv.import_use_extension_length = (uint)strlen(zuv.import_use_extension);
2186	php_startup_auto_globals();
2187	zend_set_utility_values(&zuv);
2188	php_startup_sapi_content_types();
2189
2190	/* startup extensions statically compiled in */
2191	if (php_register_internal_extensions_func() == FAILURE) {
2192		php_printf("Unable to start builtin modules\n");
2193		return FAILURE;
2194	}
2195
2196	/* start additional PHP extensions */
2197	php_register_extensions_bc(additional_modules, num_additional_modules);
2198
2199	/* load and startup extensions compiled as shared objects (aka DLLs)
2200	   as requested by php.ini entries
2201	   these are loaded after initialization of internal extensions
2202	   as extensions *might* rely on things from ext/standard
2203	   which is always an internal extension and to be initialized
2204	   ahead of all other internals
2205	 */
2206	php_ini_register_extensions();
2207	zend_startup_modules();
2208
2209	/* start Zend extensions */
2210	zend_startup_extensions();
2211
2212	zend_collect_module_handlers();
2213
2214	/* register additional functions */
2215	if (sapi_module.additional_functions) {
2216		if ((module = zend_hash_str_find_ptr(&module_registry, "standard", sizeof("standard")-1)) != NULL) {
2217			EG(current_module) = module;
2218			zend_register_functions(NULL, sapi_module.additional_functions, NULL, MODULE_PERSISTENT);
2219			EG(current_module) = NULL;
2220		}
2221	}
2222
2223	/* disable certain classes and functions as requested by php.ini */
2224	php_disable_functions();
2225	php_disable_classes();
2226
2227	/* make core report what it should */
2228	if ((module = zend_hash_str_find_ptr(&module_registry, "core", sizeof("core")-1)) != NULL) {
2229		module->version = PHP_VERSION;
2230		module->info_func = PHP_MINFO(php_core);
2231	}
2232
2233	zend_post_startup();
2234
2235	module_initialized = 1;
2236
2237	/* Check for deprecated directives */
2238	/* NOTE: If you add anything here, remember to add it to Makefile.global! */
2239	{
2240		struct {
2241			const long error_level;
2242			const char *phrase;
2243			const char *directives[17]; /* Remember to change this if the number of directives change */
2244		} directives[2] = {
2245			{
2246				E_DEPRECATED,
2247				"Directive '%s' is deprecated in PHP 5.3 and greater",
2248				{
2249					NULL
2250				}
2251			},
2252			{
2253				E_CORE_ERROR,
2254				"Directive '%s' is no longer available in PHP",
2255				{
2256					"allow_call_time_pass_reference",
2257					"asp_tags",
2258					"define_syslog_variables",
2259					"highlight.bg",
2260					"magic_quotes_gpc",
2261					"magic_quotes_runtime",
2262					"magic_quotes_sybase",
2263					"register_globals",
2264					"register_long_arrays",
2265					"safe_mode",
2266					"safe_mode_gid",
2267					"safe_mode_include_dir",
2268					"safe_mode_exec_dir",
2269					"safe_mode_allowed_env_vars",
2270					"safe_mode_protected_env_vars",
2271					"zend.ze1_compatibility_mode",
2272					NULL
2273				}
2274			}
2275		};
2276
2277		unsigned int i;
2278
2279		zend_try {
2280			/* 2 = Count of deprecation structs */
2281			for (i = 0; i < 2; i++) {
2282				const char **p = directives[i].directives;
2283
2284				while(*p) {
2285					zend_long value;
2286
2287					if (cfg_get_long((char*)*p, &value) == SUCCESS && value) {
2288						zend_error(directives[i].error_level, directives[i].phrase, *p);
2289					}
2290
2291					++p;
2292				}
2293			}
2294		} zend_catch {
2295			retval = FAILURE;
2296		} zend_end_try();
2297	}
2298
2299	sapi_deactivate();
2300	module_startup = 0;
2301
2302	shutdown_memory_manager(1, 0);
2303	zend_interned_strings_snapshot();
2304 	virtual_cwd_activate();
2305
2306	/* we're done */
2307	return retval;
2308}
2309/* }}} */
2310
2311void php_module_shutdown_for_exec(void)
2312{
2313	/* used to close fd's in the range 3.255 here, but it's problematic */
2314}
2315
2316/* {{{ php_module_shutdown_wrapper
2317 */
2318int php_module_shutdown_wrapper(sapi_module_struct *sapi_globals)
2319{
2320	php_module_shutdown();
2321	return SUCCESS;
2322}
2323/* }}} */
2324
2325/* {{{ php_module_shutdown
2326 */
2327void php_module_shutdown(void)
2328{
2329	int module_number=0;	/* for UNREGISTER_INI_ENTRIES() */
2330
2331	module_shutdown = 1;
2332
2333	if (!module_initialized) {
2334		return;
2335	}
2336
2337#ifdef ZTS
2338	ts_free_worker_threads();
2339#endif
2340
2341#if defined(PHP_WIN32) || (defined(NETWARE) && defined(USE_WINSOCK))
2342	/*close winsock */
2343	WSACleanup();
2344#endif
2345
2346#ifdef PHP_WIN32
2347	php_win32_free_rng_lock();
2348#endif
2349
2350	sapi_flush();
2351
2352	zend_shutdown();
2353
2354	/* Destroys filter & transport registries too */
2355	php_shutdown_stream_wrappers(module_number);
2356
2357	UNREGISTER_INI_ENTRIES();
2358
2359	/* close down the ini config */
2360	php_shutdown_config();
2361
2362#ifndef ZTS
2363	zend_ini_shutdown();
2364	shutdown_memory_manager(CG(unclean_shutdown), 1);
2365#else
2366	zend_ini_global_shutdown();
2367#endif
2368
2369	php_output_shutdown();
2370
2371	module_initialized = 0;
2372
2373#ifndef ZTS
2374	core_globals_dtor(&core_globals);
2375	gc_globals_dtor();
2376#else
2377	ts_free_id(core_globals_id);
2378#endif
2379
2380#ifdef PHP_WIN32
2381	if (old_invalid_parameter_handler == NULL) {
2382		_set_invalid_parameter_handler(old_invalid_parameter_handler);
2383	}
2384#endif
2385}
2386/* }}} */
2387
2388/* {{{ php_execute_script
2389 */
2390PHPAPI int php_execute_script(zend_file_handle *primary_file)
2391{
2392	zend_file_handle *prepend_file_p, *append_file_p;
2393	zend_file_handle prepend_file = {{0}, NULL, NULL, 0, 0}, append_file = {{0}, NULL, NULL, 0, 0};
2394#if HAVE_BROKEN_GETCWD
2395	volatile int old_cwd_fd = -1;
2396#else
2397	char *old_cwd;
2398	ALLOCA_FLAG(use_heap)
2399#endif
2400	int retval = 0;
2401
2402	EG(exit_status) = 0;
2403#ifndef HAVE_BROKEN_GETCWD
2404# define OLD_CWD_SIZE 4096
2405	old_cwd = do_alloca(OLD_CWD_SIZE, use_heap);
2406	old_cwd[0] = '\0';
2407#endif
2408
2409	zend_try {
2410		char realfile[MAXPATHLEN];
2411
2412#ifdef PHP_WIN32
2413		if(primary_file->filename) {
2414			UpdateIniFromRegistry((char*)primary_file->filename);
2415		}
2416#endif
2417
2418		PG(during_request_startup) = 0;
2419
2420		if (primary_file->filename && !(SG(options) & SAPI_OPTION_NO_CHDIR)) {
2421#if HAVE_BROKEN_GETCWD
2422			/* this looks nasty to me */
2423			old_cwd_fd = open(".", 0);
2424#else
2425			php_ignore_value(VCWD_GETCWD(old_cwd, OLD_CWD_SIZE-1));
2426#endif
2427			VCWD_CHDIR_FILE(primary_file->filename);
2428		}
2429
2430 		/* Only lookup the real file path and add it to the included_files list if already opened
2431		 *   otherwise it will get opened and added to the included_files list in zend_execute_scripts
2432		 */
2433 		if (primary_file->filename &&
2434 		    (primary_file->filename[0] != '-' || primary_file->filename[1] != 0) &&
2435 			primary_file->opened_path == NULL &&
2436 			primary_file->type != ZEND_HANDLE_FILENAME
2437		) {
2438			if (expand_filepath(primary_file->filename, realfile)) {
2439				primary_file->opened_path = zend_string_init(realfile, strlen(realfile), 0);
2440				zend_hash_add_empty_element(&EG(included_files), primary_file->opened_path);
2441			}
2442		}
2443
2444		if (PG(auto_prepend_file) && PG(auto_prepend_file)[0]) {
2445			prepend_file.filename = PG(auto_prepend_file);
2446			prepend_file.opened_path = NULL;
2447			prepend_file.free_filename = 0;
2448			prepend_file.type = ZEND_HANDLE_FILENAME;
2449			prepend_file_p = &prepend_file;
2450		} else {
2451			prepend_file_p = NULL;
2452		}
2453
2454		if (PG(auto_append_file) && PG(auto_append_file)[0]) {
2455			append_file.filename = PG(auto_append_file);
2456			append_file.opened_path = NULL;
2457			append_file.free_filename = 0;
2458			append_file.type = ZEND_HANDLE_FILENAME;
2459			append_file_p = &append_file;
2460		} else {
2461			append_file_p = NULL;
2462		}
2463		if (PG(max_input_time) != -1) {
2464#ifdef PHP_WIN32
2465			zend_unset_timeout();
2466#endif
2467			zend_set_timeout(INI_INT("max_execution_time"), 0);
2468		}
2469
2470		/*
2471		   If cli primary file has shabang line and there is a prepend file,
2472		   the `start_lineno` will be used by prepend file but not primary file,
2473		   save it and restore after prepend file been executed.
2474		 */
2475		if (CG(start_lineno) && prepend_file_p) {
2476			int orig_start_lineno = CG(start_lineno);
2477
2478			CG(start_lineno) = 0;
2479			if (zend_execute_scripts(ZEND_REQUIRE, NULL, 1, prepend_file_p) == SUCCESS) {
2480				CG(start_lineno) = orig_start_lineno;
2481				retval = (zend_execute_scripts(ZEND_REQUIRE, NULL, 2, primary_file, append_file_p) == SUCCESS);
2482			}
2483		} else {
2484			retval = (zend_execute_scripts(ZEND_REQUIRE, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS);
2485		}
2486	} zend_end_try();
2487
2488	if (EG(exception)) {
2489		zend_try {
2490			zend_exception_error(EG(exception), E_ERROR);
2491		} zend_end_try();
2492	}
2493
2494#if HAVE_BROKEN_GETCWD
2495	if (old_cwd_fd != -1) {
2496		fchdir(old_cwd_fd);
2497		close(old_cwd_fd);
2498	}
2499#else
2500	if (old_cwd[0] != '\0') {
2501		php_ignore_value(VCWD_CHDIR(old_cwd));
2502	}
2503	free_alloca(old_cwd, use_heap);
2504#endif
2505	return retval;
2506}
2507/* }}} */
2508
2509/* {{{ php_execute_simple_script
2510 */
2511PHPAPI int php_execute_simple_script(zend_file_handle *primary_file, zval *ret)
2512{
2513	char *old_cwd;
2514	ALLOCA_FLAG(use_heap)
2515
2516	EG(exit_status) = 0;
2517#define OLD_CWD_SIZE 4096
2518	old_cwd = do_alloca(OLD_CWD_SIZE, use_heap);
2519	old_cwd[0] = '\0';
2520
2521	zend_try {
2522#ifdef PHP_WIN32
2523		if(primary_file->filename) {
2524			UpdateIniFromRegistry((char*)primary_file->filename);
2525		}
2526#endif
2527
2528		PG(during_request_startup) = 0;
2529
2530		if (primary_file->filename && !(SG(options) & SAPI_OPTION_NO_CHDIR)) {
2531			php_ignore_value(VCWD_GETCWD(old_cwd, OLD_CWD_SIZE-1));
2532			VCWD_CHDIR_FILE(primary_file->filename);
2533		}
2534		zend_execute_scripts(ZEND_REQUIRE, ret, 1, primary_file);
2535	} zend_end_try();
2536
2537	if (old_cwd[0] != '\0') {
2538		php_ignore_value(VCWD_CHDIR(old_cwd));
2539	}
2540
2541	free_alloca(old_cwd, use_heap);
2542	return EG(exit_status);
2543}
2544/* }}} */
2545
2546/* {{{ php_handle_aborted_connection
2547 */
2548PHPAPI void php_handle_aborted_connection(void)
2549{
2550
2551	PG(connection_status) = PHP_CONNECTION_ABORTED;
2552	php_output_set_status(PHP_OUTPUT_DISABLED);
2553
2554	if (!PG(ignore_user_abort)) {
2555		zend_bailout();
2556	}
2557}
2558/* }}} */
2559
2560/* {{{ php_handle_auth_data
2561 */
2562PHPAPI int php_handle_auth_data(const char *auth)
2563{
2564	int ret = -1;
2565
2566	if (auth && auth[0] != '\0' && strncmp(auth, "Basic ", 6) == 0) {
2567		char *pass;
2568		zend_string *user;
2569
2570		user = php_base64_decode((const unsigned char*)auth + 6, strlen(auth) - 6);
2571		if (user) {
2572			pass = strchr(ZSTR_VAL(user), ':');
2573			if (pass) {
2574				*pass++ = '\0';
2575				SG(request_info).auth_user = estrndup(ZSTR_VAL(user), ZSTR_LEN(user));
2576				SG(request_info).auth_password = estrdup(pass);
2577				ret = 0;
2578			}
2579			zend_string_free(user);
2580		}
2581	}
2582
2583	if (ret == -1) {
2584		SG(request_info).auth_user = SG(request_info).auth_password = NULL;
2585	} else {
2586		SG(request_info).auth_digest = NULL;
2587	}
2588
2589	if (ret == -1 && auth && auth[0] != '\0' && strncmp(auth, "Digest ", 7) == 0) {
2590		SG(request_info).auth_digest = estrdup(auth + 7);
2591		ret = 0;
2592	}
2593
2594	if (ret == -1) {
2595		SG(request_info).auth_digest = NULL;
2596	}
2597
2598	return ret;
2599}
2600/* }}} */
2601
2602/* {{{ php_lint_script
2603 */
2604PHPAPI int php_lint_script(zend_file_handle *file)
2605{
2606	zend_op_array *op_array;
2607	int retval = FAILURE;
2608
2609	zend_try {
2610		op_array = zend_compile_file(file, ZEND_INCLUDE);
2611		zend_destroy_file_handle(file);
2612
2613		if (op_array) {
2614			destroy_op_array(op_array);
2615			efree(op_array);
2616			retval = SUCCESS;
2617		}
2618	} zend_end_try();
2619	if (EG(exception)) {
2620		zend_exception_error(EG(exception), E_ERROR);
2621	}
2622
2623	return retval;
2624}
2625/* }}} */
2626
2627/*
2628 * Local variables:
2629 * tab-width: 4
2630 * c-basic-offset: 4
2631 * End:
2632 * vim600: sw=4 ts=4 fdm=marker
2633 * vim<600: sw=4 ts=4
2634 */
2635