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