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