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