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