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