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