1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 5                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2014 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.php.net/license/3_01.txt                                  |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca>                       |
16   |          Stig Bakken <ssb@php.net>                                   |
17   |          Zeev Suraski <zeev@zend.com>                                |
18   | FastCGI: Ben Mansell <php@slimyhorror.com>                           |
19   |          Shane Caraveo <shane@caraveo.com>                           |
20   |          Dmitry Stogov <dmitry@zend.com>                             |
21   +----------------------------------------------------------------------+
22*/
23
24/* $Id$ */
25
26#include "php.h"
27#include "php_globals.h"
28#include "php_variables.h"
29#include "zend_modules.h"
30
31#include "SAPI.h"
32
33#include <stdio.h>
34#include "php.h"
35
36#ifdef PHP_WIN32
37# include "win32/time.h"
38# include "win32/signal.h"
39# include <process.h>
40#endif
41
42#if HAVE_SYS_TIME_H
43# include <sys/time.h>
44#endif
45
46#if HAVE_UNISTD_H
47# include <unistd.h>
48#endif
49
50#if HAVE_SIGNAL_H
51# include <signal.h>
52#endif
53
54#if HAVE_SETLOCALE
55# include <locale.h>
56#endif
57
58#if HAVE_SYS_TYPES_H
59# include <sys/types.h>
60#endif
61
62#if HAVE_SYS_WAIT_H
63# include <sys/wait.h>
64#endif
65
66#include "zend.h"
67#include "zend_extensions.h"
68#include "php_ini.h"
69#include "php_globals.h"
70#include "php_main.h"
71#include "fopen_wrappers.h"
72#include "ext/standard/php_standard.h"
73#include "ext/standard/url.h"
74
75#ifdef PHP_WIN32
76# include <io.h>
77# include <fcntl.h>
78# include "win32/php_registry.h"
79#endif
80
81#ifdef __riscos__
82# include <unixlib/local.h>
83int __riscosify_control = __RISCOSIFY_STRICT_UNIX_SPECS;
84#endif
85
86#include "zend_compile.h"
87#include "zend_execute.h"
88#include "zend_highlight.h"
89#include "zend_indent.h"
90
91#include "php_getopt.h"
92
93#include "fastcgi.h"
94
95#ifndef PHP_WIN32
96/* XXX this will need to change later when threaded fastcgi is implemented.  shane */
97struct sigaction act, old_term, old_quit, old_int;
98#endif
99
100static void (*php_php_import_environment_variables)(zval *array_ptr TSRMLS_DC);
101
102#ifndef PHP_WIN32
103/* these globals used for forking children on unix systems */
104/**
105 * Number of child processes that will get created to service requests
106 */
107static int children = 0;
108
109
110/**
111 * Set to non-zero if we are the parent process
112 */
113static int parent = 1;
114
115/* Did parent received exit signals SIG_TERM/SIG_INT/SIG_QUIT */
116static int exit_signal = 0;
117
118/* Is Parent waiting for children to exit */
119static int parent_waiting = 0;
120
121/**
122 * Process group
123 */
124static pid_t pgroup;
125#endif
126
127#define PHP_MODE_STANDARD   1
128#define PHP_MODE_HIGHLIGHT  2
129#define PHP_MODE_INDENT     3
130#define PHP_MODE_LINT       4
131#define PHP_MODE_STRIP      5
132
133static char *php_optarg = NULL;
134static int php_optind = 1;
135static zend_module_entry cgi_module_entry;
136
137static const opt_struct OPTIONS[] = {
138    {'a', 0, "interactive"},
139    {'b', 1, "bindpath"},
140    {'C', 0, "no-chdir"},
141    {'c', 1, "php-ini"},
142    {'d', 1, "define"},
143    {'e', 0, "profile-info"},
144    {'f', 1, "file"},
145    {'h', 0, "help"},
146    {'i', 0, "info"},
147    {'l', 0, "syntax-check"},
148    {'m', 0, "modules"},
149    {'n', 0, "no-php-ini"},
150    {'q', 0, "no-header"},
151    {'s', 0, "syntax-highlight"},
152    {'s', 0, "syntax-highlighting"},
153    {'w', 0, "strip"},
154    {'?', 0, "usage"},/* help alias (both '?' and 'usage') */
155    {'v', 0, "version"},
156    {'z', 1, "zend-extension"},
157    {'T', 1, "timing"},
158    {'-', 0, NULL} /* end of args */
159};
160
161typedef struct _php_cgi_globals_struct {
162    zend_bool rfc2616_headers;
163    zend_bool nph;
164    zend_bool check_shebang_line;
165    zend_bool fix_pathinfo;
166    zend_bool force_redirect;
167    zend_bool discard_path;
168    zend_bool fcgi_logging;
169    char *redirect_status_env;
170#ifdef PHP_WIN32
171    zend_bool impersonate;
172#endif
173    HashTable user_config_cache;
174} php_cgi_globals_struct;
175
176/* {{{ user_config_cache
177 *
178 * Key for each cache entry is dirname(PATH_TRANSLATED).
179 *
180 * NOTE: Each cache entry config_hash contains the combination from all user ini files found in
181 *       the path starting from doc_root throught to dirname(PATH_TRANSLATED).  There is no point
182 *       storing per-file entries as it would not be possible to detect added / deleted entries
183 *       between separate files.
184 */
185typedef struct _user_config_cache_entry {
186    time_t expires;
187    HashTable *user_config;
188} user_config_cache_entry;
189
190static void user_config_cache_entry_dtor(user_config_cache_entry *entry)
191{
192    zend_hash_destroy(entry->user_config);
193    free(entry->user_config);
194}
195/* }}} */
196
197#ifdef ZTS
198static int php_cgi_globals_id;
199#define CGIG(v) TSRMG(php_cgi_globals_id, php_cgi_globals_struct *, v)
200#else
201static php_cgi_globals_struct php_cgi_globals;
202#define CGIG(v) (php_cgi_globals.v)
203#endif
204
205#ifdef PHP_WIN32
206#define TRANSLATE_SLASHES(path) \
207    { \
208        char *tmp = path; \
209        while (*tmp) { \
210            if (*tmp == '\\') *tmp = '/'; \
211            tmp++; \
212        } \
213    }
214#else
215#define TRANSLATE_SLASHES(path)
216#endif
217
218static int print_module_info(zend_module_entry *module, void *arg TSRMLS_DC)
219{
220    php_printf("%s\n", module->name);
221    return 0;
222}
223
224static int module_name_cmp(const void *a, const void *b TSRMLS_DC)
225{
226    Bucket *f = *((Bucket **) a);
227    Bucket *s = *((Bucket **) b);
228
229    return strcasecmp(  ((zend_module_entry *)f->pData)->name,
230                        ((zend_module_entry *)s->pData)->name);
231}
232
233static void print_modules(TSRMLS_D)
234{
235    HashTable sorted_registry;
236    zend_module_entry tmp;
237
238    zend_hash_init(&sorted_registry, 50, NULL, NULL, 1);
239    zend_hash_copy(&sorted_registry, &module_registry, NULL, &tmp, sizeof(zend_module_entry));
240    zend_hash_sort(&sorted_registry, zend_qsort, module_name_cmp, 0 TSRMLS_CC);
241    zend_hash_apply_with_argument(&sorted_registry, (apply_func_arg_t) print_module_info, NULL TSRMLS_CC);
242    zend_hash_destroy(&sorted_registry);
243}
244
245static int print_extension_info(zend_extension *ext, void *arg TSRMLS_DC)
246{
247    php_printf("%s\n", ext->name);
248    return 0;
249}
250
251static int extension_name_cmp(const zend_llist_element **f, const zend_llist_element **s TSRMLS_DC)
252{
253    return strcmp(  ((zend_extension *)(*f)->data)->name,
254                    ((zend_extension *)(*s)->data)->name);
255}
256
257static void print_extensions(TSRMLS_D)
258{
259    zend_llist sorted_exts;
260
261    zend_llist_copy(&sorted_exts, &zend_extensions);
262    sorted_exts.dtor = NULL;
263    zend_llist_sort(&sorted_exts, extension_name_cmp TSRMLS_CC);
264    zend_llist_apply_with_argument(&sorted_exts, (llist_apply_with_arg_func_t) print_extension_info, NULL TSRMLS_CC);
265    zend_llist_destroy(&sorted_exts);
266}
267
268#ifndef STDOUT_FILENO
269#define STDOUT_FILENO 1
270#endif
271
272static inline size_t sapi_cgi_single_write(const char *str, uint str_length TSRMLS_DC)
273{
274#ifdef PHP_WRITE_STDOUT
275    long ret;
276
277    ret = write(STDOUT_FILENO, str, str_length);
278    if (ret <= 0) return 0;
279    return ret;
280#else
281    size_t ret;
282
283    ret = fwrite(str, 1, MIN(str_length, 16384), stdout);
284    return ret;
285#endif
286}
287
288static int sapi_cgi_ub_write(const char *str, uint str_length TSRMLS_DC)
289{
290    const char *ptr = str;
291    uint remaining = str_length;
292    size_t ret;
293
294    while (remaining > 0) {
295        ret = sapi_cgi_single_write(ptr, remaining TSRMLS_CC);
296        if (!ret) {
297            php_handle_aborted_connection();
298            return str_length - remaining;
299        }
300        ptr += ret;
301        remaining -= ret;
302    }
303
304    return str_length;
305}
306
307static int sapi_fcgi_ub_write(const char *str, uint str_length TSRMLS_DC)
308{
309    const char *ptr = str;
310    uint remaining = str_length;
311    fcgi_request *request = (fcgi_request*) SG(server_context);
312
313    while (remaining > 0) {
314        long ret = fcgi_write(request, FCGI_STDOUT, ptr, remaining);
315
316        if (ret <= 0) {
317            php_handle_aborted_connection();
318            return str_length - remaining;
319        }
320        ptr += ret;
321        remaining -= ret;
322    }
323
324    return str_length;
325}
326
327static void sapi_cgi_flush(void *server_context)
328{
329    if (fflush(stdout) == EOF) {
330        php_handle_aborted_connection();
331    }
332}
333
334static void sapi_fcgi_flush(void *server_context)
335{
336    fcgi_request *request = (fcgi_request*) server_context;
337
338    if (
339#ifndef PHP_WIN32
340        !parent &&
341#endif
342        request && !fcgi_flush(request, 0)) {
343
344        php_handle_aborted_connection();
345    }
346}
347
348#define SAPI_CGI_MAX_HEADER_LENGTH 1024
349
350typedef struct _http_error {
351  int code;
352  const char* msg;
353} http_error;
354
355static const http_error http_error_codes[] = {
356    {100, "Continue"},
357    {101, "Switching Protocols"},
358    {200, "OK"},
359    {201, "Created"},
360    {202, "Accepted"},
361    {203, "Non-Authoritative Information"},
362    {204, "No Content"},
363    {205, "Reset Content"},
364    {206, "Partial Content"},
365    {300, "Multiple Choices"},
366    {301, "Moved Permanently"},
367    {302, "Moved Temporarily"},
368    {303, "See Other"},
369    {304, "Not Modified"},
370    {305, "Use Proxy"},
371    {400, "Bad Request"},
372    {401, "Unauthorized"},
373    {402, "Payment Required"},
374    {403, "Forbidden"},
375    {404, "Not Found"},
376    {405, "Method Not Allowed"},
377    {406, "Not Acceptable"},
378    {407, "Proxy Authentication Required"},
379    {408, "Request Time-out"},
380    {409, "Conflict"},
381    {410, "Gone"},
382    {411, "Length Required"},
383    {412, "Precondition Failed"},
384    {413, "Request Entity Too Large"},
385    {414, "Request-URI Too Large"},
386    {415, "Unsupported Media Type"},
387    {428, "Precondition Required"},
388    {429, "Too Many Requests"},
389    {431, "Request Header Fields Too Large"},
390    {500, "Internal Server Error"},
391    {501, "Not Implemented"},
392    {502, "Bad Gateway"},
393    {503, "Service Unavailable"},
394    {504, "Gateway Time-out"},
395    {505, "HTTP Version not supported"},
396    {511, "Network Authentication Required"},
397    {0,   NULL}
398};
399
400static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC)
401{
402    char buf[SAPI_CGI_MAX_HEADER_LENGTH];
403    sapi_header_struct *h;
404    zend_llist_position pos;
405    zend_bool ignore_status = 0;
406    int response_status = SG(sapi_headers).http_response_code;
407
408    if (SG(request_info).no_headers == 1) {
409        return  SAPI_HEADER_SENT_SUCCESSFULLY;
410    }
411
412    if (CGIG(nph) || SG(sapi_headers).http_response_code != 200)
413    {
414        int len;
415        zend_bool has_status = 0;
416
417        if (CGIG(rfc2616_headers) && SG(sapi_headers).http_status_line) {
418            char *s;
419            len = slprintf(buf, SAPI_CGI_MAX_HEADER_LENGTH, "%s\r\n", SG(sapi_headers).http_status_line);
420            if ((s = strchr(SG(sapi_headers).http_status_line, ' '))) {
421                response_status = atoi((s + 1));
422            }
423
424            if (len > SAPI_CGI_MAX_HEADER_LENGTH) {
425                len = SAPI_CGI_MAX_HEADER_LENGTH;
426            }
427
428        } else {
429            char *s;
430
431            if (SG(sapi_headers).http_status_line &&
432                (s = strchr(SG(sapi_headers).http_status_line, ' ')) != 0 &&
433                (s - SG(sapi_headers).http_status_line) >= 5 &&
434                strncasecmp(SG(sapi_headers).http_status_line, "HTTP/", 5) == 0
435            ) {
436                len = slprintf(buf, sizeof(buf), "Status:%s\r\n", s);
437                response_status = atoi((s + 1));
438            } else {
439                h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
440                while (h) {
441                    if (h->header_len > sizeof("Status:")-1 &&
442                        strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
443                    ) {
444                        has_status = 1;
445                        break;
446                    }
447                    h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
448                }
449                if (!has_status) {
450                    http_error *err = (http_error*)http_error_codes;
451
452                    while (err->code != 0) {
453                        if (err->code == SG(sapi_headers).http_response_code) {
454                            break;
455                        }
456                        err++;
457                    }
458                    if (err->msg) {
459                        len = slprintf(buf, sizeof(buf), "Status: %d %s\r\n", SG(sapi_headers).http_response_code, err->msg);
460                    } else {
461                        len = slprintf(buf, sizeof(buf), "Status: %d\r\n", SG(sapi_headers).http_response_code);
462                    }
463                }
464            }
465        }
466
467        if (!has_status) {
468            PHPWRITE_H(buf, len);
469            ignore_status = 1;
470        }
471    }
472
473    h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
474    while (h) {
475        /* prevent CRLFCRLF */
476        if (h->header_len) {
477            if (h->header_len > sizeof("Status:")-1 &&
478                strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
479            ) {
480                if (!ignore_status) {
481                    ignore_status = 1;
482                    PHPWRITE_H(h->header, h->header_len);
483                    PHPWRITE_H("\r\n", 2);
484                }
485            } else if (response_status == 304 && h->header_len > sizeof("Content-Type:")-1 &&
486                strncasecmp(h->header, "Content-Type:", sizeof("Content-Type:")-1) == 0
487            ) {
488                h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
489                continue;
490            } else {
491                PHPWRITE_H(h->header, h->header_len);
492                PHPWRITE_H("\r\n", 2);
493            }
494        }
495        h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
496    }
497    PHPWRITE_H("\r\n", 2);
498
499    return SAPI_HEADER_SENT_SUCCESSFULLY;
500}
501
502#ifndef STDIN_FILENO
503# define STDIN_FILENO 0
504#endif
505
506static int sapi_cgi_read_post(char *buffer, uint count_bytes TSRMLS_DC)
507{
508    uint read_bytes = 0;
509    int tmp_read_bytes;
510
511    count_bytes = MIN(count_bytes, (uint) SG(request_info).content_length - SG(read_post_bytes));
512    while (read_bytes < count_bytes) {
513        tmp_read_bytes = read(STDIN_FILENO, buffer + read_bytes, count_bytes - read_bytes);
514        if (tmp_read_bytes <= 0) {
515            break;
516        }
517        read_bytes += tmp_read_bytes;
518    }
519    return read_bytes;
520}
521
522static int sapi_fcgi_read_post(char *buffer, uint count_bytes TSRMLS_DC)
523{
524    uint read_bytes = 0;
525    int tmp_read_bytes;
526    fcgi_request *request = (fcgi_request*) SG(server_context);
527
528    count_bytes = MIN(count_bytes, (uint) SG(request_info).content_length - SG(read_post_bytes));
529    while (read_bytes < count_bytes) {
530        tmp_read_bytes = fcgi_read(request, buffer + read_bytes, count_bytes - read_bytes);
531        if (tmp_read_bytes <= 0) {
532            break;
533        }
534        read_bytes += tmp_read_bytes;
535    }
536    return read_bytes;
537}
538
539static char *sapi_cgi_getenv(char *name, size_t name_len TSRMLS_DC)
540{
541    return getenv(name);
542}
543
544static char *sapi_fcgi_getenv(char *name, size_t name_len TSRMLS_DC)
545{
546    /* when php is started by mod_fastcgi, no regular environment
547     * is provided to PHP.  It is always sent to PHP at the start
548     * of a request.  So we have to do our own lookup to get env
549     * vars.  This could probably be faster somehow.  */
550    fcgi_request *request = (fcgi_request*) SG(server_context);
551    char *ret = fcgi_getenv(request, name, name_len);
552
553    if (ret) return ret;
554    /*  if cgi, or fastcgi and not found in fcgi env
555        check the regular environment */
556    return getenv(name);
557}
558
559static char *_sapi_cgi_putenv(char *name, int name_len, char *value)
560{
561#if !HAVE_SETENV || !HAVE_UNSETENV
562    int len;
563    char *buf;
564#endif
565
566#if HAVE_SETENV
567    if (value) {
568        setenv(name, value, 1);
569    }
570#endif
571#if HAVE_UNSETENV
572    if (!value) {
573        unsetenv(name);
574    }
575#endif
576
577#if !HAVE_SETENV || !HAVE_UNSETENV
578    /*  if cgi, or fastcgi and not found in fcgi env
579        check the regular environment
580        this leaks, but it's only cgi anyway, we'll fix
581        it for 5.0
582    */
583    len = name_len + (value ? strlen(value) : 0) + sizeof("=") + 2;
584    buf = (char *) malloc(len);
585    if (buf == NULL) {
586        return getenv(name);
587    }
588#endif
589#if !HAVE_SETENV
590    if (value) {
591        len = slprintf(buf, len - 1, "%s=%s", name, value);
592        putenv(buf);
593    }
594#endif
595#if !HAVE_UNSETENV
596    if (!value) {
597        len = slprintf(buf, len - 1, "%s=", name);
598        putenv(buf);
599    }
600#endif
601    return getenv(name);
602}
603
604static char *sapi_cgi_read_cookies(TSRMLS_D)
605{
606    return getenv("HTTP_COOKIE");
607}
608
609static char *sapi_fcgi_read_cookies(TSRMLS_D)
610{
611    fcgi_request *request = (fcgi_request*) SG(server_context);
612
613    return FCGI_GETENV(request, "HTTP_COOKIE");
614}
615
616static void cgi_php_load_env_var(char *var, unsigned int var_len, char *val, unsigned int val_len, void *arg TSRMLS_DC)
617{
618    zval *array_ptr = (zval*)arg;
619    int filter_arg = (array_ptr == PG(http_globals)[TRACK_VARS_ENV])?PARSE_ENV:PARSE_SERVER;
620    unsigned int new_val_len;
621
622    if (sapi_module.input_filter(filter_arg, var, &val, strlen(val), &new_val_len TSRMLS_CC)) {
623        php_register_variable_safe(var, val, new_val_len, array_ptr TSRMLS_CC);
624    }
625}
626
627static void cgi_php_import_environment_variables(zval *array_ptr TSRMLS_DC)
628{
629    if (PG(http_globals)[TRACK_VARS_ENV] &&
630        array_ptr != PG(http_globals)[TRACK_VARS_ENV] &&
631        Z_TYPE_P(PG(http_globals)[TRACK_VARS_ENV]) == IS_ARRAY &&
632        zend_hash_num_elements(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_ENV])) > 0
633    ) {
634        zval_dtor(array_ptr);
635        *array_ptr = *PG(http_globals)[TRACK_VARS_ENV];
636        INIT_PZVAL(array_ptr);
637        zval_copy_ctor(array_ptr);
638        return;
639    } else if (PG(http_globals)[TRACK_VARS_SERVER] &&
640        array_ptr != PG(http_globals)[TRACK_VARS_SERVER] &&
641        Z_TYPE_P(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY &&
642        zend_hash_num_elements(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER])) > 0
643    ) {
644        zval_dtor(array_ptr);
645        *array_ptr = *PG(http_globals)[TRACK_VARS_SERVER];
646        INIT_PZVAL(array_ptr);
647        zval_copy_ctor(array_ptr);
648        return;
649    }
650
651    /* call php's original import as a catch-all */
652    php_php_import_environment_variables(array_ptr TSRMLS_CC);
653
654    if (fcgi_is_fastcgi()) {
655        fcgi_request *request = (fcgi_request*) SG(server_context);
656        fcgi_loadenv(request, cgi_php_load_env_var, array_ptr TSRMLS_CC);
657    }
658}
659
660static void sapi_cgi_register_variables(zval *track_vars_array TSRMLS_DC)
661{
662    unsigned int php_self_len;
663    char *php_self;
664
665    /* In CGI mode, we consider the environment to be a part of the server
666     * variables
667     */
668    php_import_environment_variables(track_vars_array TSRMLS_CC);
669
670    if (CGIG(fix_pathinfo)) {
671        char *script_name = SG(request_info).request_uri;
672        char *path_info;
673        int free_php_self;
674        ALLOCA_FLAG(use_heap)
675
676        if (fcgi_is_fastcgi()) {
677            fcgi_request *request = (fcgi_request*) SG(server_context);
678
679            path_info = FCGI_GETENV(request, "PATH_INFO");
680        } else {
681            path_info = getenv("PATH_INFO");
682        }
683
684        if (path_info) {
685            unsigned int path_info_len = strlen(path_info);
686
687            if (script_name) {
688                unsigned int script_name_len = strlen(script_name);
689
690                php_self_len = script_name_len + path_info_len;
691                php_self = do_alloca(php_self_len + 1, use_heap);
692                memcpy(php_self, script_name, script_name_len + 1);
693                memcpy(php_self + script_name_len, path_info, path_info_len + 1);
694                free_php_self = 1;
695            }  else {
696                php_self = path_info;
697                php_self_len = path_info_len;
698                free_php_self = 0;
699            }
700        } else if (script_name) {
701            php_self = script_name;
702            php_self_len = strlen(script_name);
703            free_php_self = 0;
704        } else {
705            php_self = "";
706            php_self_len = 0;
707            free_php_self = 0;
708        }
709
710        /* Build the special-case PHP_SELF variable for the CGI version */
711        if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len TSRMLS_CC)) {
712            php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array TSRMLS_CC);
713        }
714        if (free_php_self) {
715            free_alloca(php_self, use_heap);
716        }
717    } else {
718        php_self = SG(request_info).request_uri ? SG(request_info).request_uri : "";
719        php_self_len = strlen(php_self);
720        if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len TSRMLS_CC)) {
721            php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array TSRMLS_CC);
722        }
723    }
724}
725
726static void sapi_cgi_log_message(char *message TSRMLS_DC)
727{
728    if (fcgi_is_fastcgi() && CGIG(fcgi_logging)) {
729        fcgi_request *request;
730
731        request = (fcgi_request*) SG(server_context);
732        if (request) {
733            int len = strlen(message);
734            char *buf = malloc(len+2);
735
736            memcpy(buf, message, len);
737            memcpy(buf + len, "\n", sizeof("\n"));
738            fcgi_write(request, FCGI_STDERR, buf, len+1);
739            free(buf);
740        } else {
741            fprintf(stderr, "%s\n", message);
742        }
743        /* ignore return code */
744    } else {
745        fprintf(stderr, "%s\n", message);
746    }
747}
748
749/* {{{ php_cgi_ini_activate_user_config
750 */
751static void php_cgi_ini_activate_user_config(char *path, int path_len, const char *doc_root, int doc_root_len, int start TSRMLS_DC)
752{
753    char *ptr;
754    user_config_cache_entry *new_entry, *entry;
755    time_t request_time = sapi_get_request_time(TSRMLS_C);
756
757    /* Find cached config entry: If not found, create one */
758    if (zend_hash_find(&CGIG(user_config_cache), path, path_len + 1, (void **) &entry) == FAILURE) {
759        new_entry = pemalloc(sizeof(user_config_cache_entry), 1);
760        new_entry->expires = 0;
761        new_entry->user_config = (HashTable *) pemalloc(sizeof(HashTable), 1);
762        zend_hash_init(new_entry->user_config, 0, NULL, (dtor_func_t) config_zval_dtor, 1);
763        zend_hash_update(&CGIG(user_config_cache), path, path_len + 1, new_entry, sizeof(user_config_cache_entry), (void **) &entry);
764        free(new_entry);
765    }
766
767    /* Check whether cache entry has expired and rescan if it is */
768    if (request_time > entry->expires) {
769        char *real_path = NULL;
770        int real_path_len;
771        char *s1, *s2;
772        int s_len;
773
774        /* Clear the expired config */
775        zend_hash_clean(entry->user_config);
776
777        if (!IS_ABSOLUTE_PATH(path, path_len)) {
778            real_path = tsrm_realpath(path, NULL TSRMLS_CC);
779            if (real_path == NULL) {
780                return;
781            }
782            real_path_len = strlen(real_path);
783            path = real_path;
784            path_len = real_path_len;
785        }
786
787        if (path_len > doc_root_len) {
788            s1 = (char *) doc_root;
789            s2 = path;
790            s_len = doc_root_len;
791        } else {
792            s1 = path;
793            s2 = (char *) doc_root;
794            s_len = path_len;
795        }
796
797        /* we have to test if path is part of DOCUMENT_ROOT.
798          if it is inside the docroot, we scan the tree up to the docroot
799            to find more user.ini, if not we only scan the current path.
800          */
801#ifdef PHP_WIN32
802        if (strnicmp(s1, s2, s_len) == 0) {
803#else
804        if (strncmp(s1, s2, s_len) == 0) {
805#endif
806            ptr = s2 + start;  /* start is the point where doc_root ends! */
807            while ((ptr = strchr(ptr, DEFAULT_SLASH)) != NULL) {
808                *ptr = 0;
809                php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config TSRMLS_CC);
810                *ptr = '/';
811                ptr++;
812            }
813        } else {
814            php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config TSRMLS_CC);
815        }
816
817        if (real_path) {
818            free(real_path);
819        }
820        entry->expires = request_time + PG(user_ini_cache_ttl);
821    }
822
823    /* Activate ini entries with values from the user config hash */
824    php_ini_activate_config(entry->user_config, PHP_INI_PERDIR, PHP_INI_STAGE_HTACCESS TSRMLS_CC);
825}
826/* }}} */
827
828static int sapi_cgi_activate(TSRMLS_D)
829{
830    char *path, *doc_root, *server_name;
831    uint path_len, doc_root_len, server_name_len;
832
833    /* PATH_TRANSLATED should be defined at this stage but better safe than sorry :) */
834    if (!SG(request_info).path_translated) {
835        return FAILURE;
836    }
837
838    if (php_ini_has_per_host_config()) {
839        /* Activate per-host-system-configuration defined in php.ini and stored into configuration_hash during startup */
840        if (fcgi_is_fastcgi()) {
841            fcgi_request *request = (fcgi_request*) SG(server_context);
842
843            server_name = FCGI_GETENV(request, "SERVER_NAME");
844        } else {
845            server_name = getenv("SERVER_NAME");
846        }
847        /* SERVER_NAME should also be defined at this stage..but better check it anyway */
848        if (server_name) {
849            server_name_len = strlen(server_name);
850            server_name = estrndup(server_name, server_name_len);
851            zend_str_tolower(server_name, server_name_len);
852            php_ini_activate_per_host_config(server_name, server_name_len + 1 TSRMLS_CC);
853            efree(server_name);
854        }
855    }
856
857    if (php_ini_has_per_dir_config() ||
858        (PG(user_ini_filename) && *PG(user_ini_filename))
859    ) {
860        /* Prepare search path */
861        path_len = strlen(SG(request_info).path_translated);
862
863        /* Make sure we have trailing slash! */
864        if (!IS_SLASH(SG(request_info).path_translated[path_len])) {
865            path = emalloc(path_len + 2);
866            memcpy(path, SG(request_info).path_translated, path_len + 1);
867            path_len = zend_dirname(path, path_len);
868            path[path_len++] = DEFAULT_SLASH;
869        } else {
870            path = estrndup(SG(request_info).path_translated, path_len);
871            path_len = zend_dirname(path, path_len);
872        }
873        path[path_len] = 0;
874
875        /* Activate per-dir-system-configuration defined in php.ini and stored into configuration_hash during startup */
876        php_ini_activate_per_dir_config(path, path_len TSRMLS_CC); /* Note: for global settings sake we check from root to path */
877
878        /* Load and activate user ini files in path starting from DOCUMENT_ROOT */
879        if (PG(user_ini_filename) && *PG(user_ini_filename)) {
880            if (fcgi_is_fastcgi()) {
881                fcgi_request *request = (fcgi_request*) SG(server_context);
882
883                doc_root = FCGI_GETENV(request, "DOCUMENT_ROOT");
884            } else {
885                doc_root = getenv("DOCUMENT_ROOT");
886            }
887            /* DOCUMENT_ROOT should also be defined at this stage..but better check it anyway */
888            if (doc_root) {
889                doc_root_len = strlen(doc_root);
890                if (doc_root_len > 0 && IS_SLASH(doc_root[doc_root_len - 1])) {
891                    --doc_root_len;
892                }
893#ifdef PHP_WIN32
894                /* paths on windows should be case-insensitive */
895                doc_root = estrndup(doc_root, doc_root_len);
896                zend_str_tolower(doc_root, doc_root_len);
897#endif
898                php_cgi_ini_activate_user_config(path, path_len, doc_root, doc_root_len, doc_root_len - 1 TSRMLS_CC);
899
900#ifdef PHP_WIN32
901                efree(doc_root);
902#endif
903            }
904        }
905
906        efree(path);
907    }
908
909    return SUCCESS;
910}
911
912static int sapi_cgi_deactivate(TSRMLS_D)
913{
914    /* flush only when SAPI was started. The reasons are:
915        1. SAPI Deactivate is called from two places: module init and request shutdown
916        2. When the first call occurs and the request is not set up, flush fails on FastCGI.
917    */
918    if (SG(sapi_started)) {
919        if (fcgi_is_fastcgi()) {
920            if (
921#ifndef PHP_WIN32
922                !parent &&
923#endif
924                !fcgi_finish_request((fcgi_request*)SG(server_context), 0)) {
925                php_handle_aborted_connection();
926            }
927        } else {
928            sapi_cgi_flush(SG(server_context));
929        }
930    }
931    return SUCCESS;
932}
933
934static int php_cgi_startup(sapi_module_struct *sapi_module)
935{
936    if (php_module_startup(sapi_module, &cgi_module_entry, 1) == FAILURE) {
937        return FAILURE;
938    }
939    return SUCCESS;
940}
941
942/* {{{ sapi_module_struct cgi_sapi_module
943 */
944static sapi_module_struct cgi_sapi_module = {
945    "cgi-fcgi",                     /* name */
946    "CGI/FastCGI",                  /* pretty name */
947
948    php_cgi_startup,                /* startup */
949    php_module_shutdown_wrapper,    /* shutdown */
950
951    sapi_cgi_activate,              /* activate */
952    sapi_cgi_deactivate,            /* deactivate */
953
954    sapi_cgi_ub_write,              /* unbuffered write */
955    sapi_cgi_flush,                 /* flush */
956    NULL,                           /* get uid */
957    sapi_cgi_getenv,                /* getenv */
958
959    php_error,                      /* error handler */
960
961    NULL,                           /* header handler */
962    sapi_cgi_send_headers,          /* send headers handler */
963    NULL,                           /* send header handler */
964
965    sapi_cgi_read_post,             /* read POST data */
966    sapi_cgi_read_cookies,          /* read Cookies */
967
968    sapi_cgi_register_variables,    /* register server variables */
969    sapi_cgi_log_message,           /* Log message */
970    NULL,                           /* Get request time */
971    NULL,                           /* Child terminate */
972
973    STANDARD_SAPI_MODULE_PROPERTIES
974};
975/* }}} */
976
977/* {{{ arginfo ext/standard/dl.c */
978ZEND_BEGIN_ARG_INFO(arginfo_dl, 0)
979    ZEND_ARG_INFO(0, extension_filename)
980ZEND_END_ARG_INFO()
981/* }}} */
982
983static const zend_function_entry additional_functions[] = {
984    ZEND_FE(dl, arginfo_dl)
985    {NULL, NULL, NULL}
986};
987
988/* {{{ php_cgi_usage
989 */
990static void php_cgi_usage(char *argv0)
991{
992    char *prog;
993
994    prog = strrchr(argv0, '/');
995    if (prog) {
996        prog++;
997    } else {
998        prog = "php";
999    }
1000
1001    php_printf( "Usage: %s [-q] [-h] [-s] [-v] [-i] [-f <file>]\n"
1002                "       %s <file> [args...]\n"
1003                "  -a               Run interactively\n"
1004                "  -b <address:port>|<port> Bind Path for external FASTCGI Server mode\n"
1005                "  -C               Do not chdir to the script's directory\n"
1006                "  -c <path>|<file> Look for php.ini file in this directory\n"
1007                "  -n               No php.ini file will be used\n"
1008                "  -d foo[=bar]     Define INI entry foo with value 'bar'\n"
1009                "  -e               Generate extended information for debugger/profiler\n"
1010                "  -f <file>        Parse <file>.  Implies `-q'\n"
1011                "  -h               This help\n"
1012                "  -i               PHP information\n"
1013                "  -l               Syntax check only (lint)\n"
1014                "  -m               Show compiled in modules\n"
1015                "  -q               Quiet-mode.  Suppress HTTP Header output.\n"
1016                "  -s               Display colour syntax highlighted source.\n"
1017                "  -v               Version number\n"
1018                "  -w               Display source with stripped comments and whitespace.\n"
1019                "  -z <file>        Load Zend extension <file>.\n"
1020                "  -T <count>       Measure execution time of script repeated <count> times.\n",
1021                prog, prog);
1022}
1023/* }}} */
1024
1025/* {{{ is_valid_path
1026 *
1027 * some server configurations allow '..' to slip through in the
1028 * translated path.   We'll just refuse to handle such a path.
1029 */
1030static int is_valid_path(const char *path)
1031{
1032    const char *p = path;
1033
1034    if (UNEXPECTED(!p)) {
1035        return 0;
1036    }
1037    if (UNEXPECTED(*p == '.') && *(p+1) == '.' && (!*(p+2) || IS_SLASH(*(p+2)))) {
1038        return 0;
1039    }
1040    while (*p) {
1041        if (IS_SLASH(*p)) {
1042            p++;
1043            if (UNEXPECTED(*p == '.')) {
1044                p++;
1045                if (UNEXPECTED(*p == '.')) {
1046                    p++;
1047                    if (UNEXPECTED(!*p) || UNEXPECTED(IS_SLASH(*p))) {
1048                        return 0;
1049                    }
1050                }
1051            }
1052        }
1053        p++;
1054    }
1055    return 1;
1056}
1057/* }}} */
1058
1059#define CGI_GETENV(name) \
1060    ((request) ? \
1061        FCGI_GETENV(request, name) : \
1062        getenv(name))
1063
1064#define CGI_PUTENV(name, value) \
1065    ((request) ? \
1066        FCGI_PUTENV(request, name, value) : \
1067        _sapi_cgi_putenv(name, sizeof(name)-1, value))
1068
1069/* {{{ init_request_info
1070
1071  initializes request_info structure
1072
1073  specificly in this section we handle proper translations
1074  for:
1075
1076  PATH_INFO
1077    derived from the portion of the URI path following
1078    the script name but preceding any query data
1079    may be empty
1080
1081  PATH_TRANSLATED
1082    derived by taking any path-info component of the
1083    request URI and performing any virtual-to-physical
1084    translation appropriate to map it onto the server's
1085    document repository structure
1086
1087    empty if PATH_INFO is empty
1088
1089    The env var PATH_TRANSLATED **IS DIFFERENT** than the
1090    request_info.path_translated variable, the latter should
1091    match SCRIPT_FILENAME instead.
1092
1093  SCRIPT_NAME
1094    set to a URL path that could identify the CGI script
1095    rather than the interpreter.  PHP_SELF is set to this
1096
1097  REQUEST_URI
1098    uri section following the domain:port part of a URI
1099
1100  SCRIPT_FILENAME
1101    The virtual-to-physical translation of SCRIPT_NAME (as per
1102    PATH_TRANSLATED)
1103
1104  These settings are documented at
1105  http://cgi-spec.golux.com/
1106
1107
1108  Based on the following URL request:
1109
1110  http://localhost/info.php/test?a=b
1111
1112  should produce, which btw is the same as if
1113  we were running under mod_cgi on apache (ie. not
1114  using ScriptAlias directives):
1115
1116  PATH_INFO=/test
1117  PATH_TRANSLATED=/docroot/test
1118  SCRIPT_NAME=/info.php
1119  REQUEST_URI=/info.php/test?a=b
1120  SCRIPT_FILENAME=/docroot/info.php
1121  QUERY_STRING=a=b
1122
1123  but what we get is (cgi/mod_fastcgi under apache):
1124
1125  PATH_INFO=/info.php/test
1126  PATH_TRANSLATED=/docroot/info.php/test
1127  SCRIPT_NAME=/php/php-cgi  (from the Action setting I suppose)
1128  REQUEST_URI=/info.php/test?a=b
1129  SCRIPT_FILENAME=/path/to/php/bin/php-cgi  (Action setting translated)
1130  QUERY_STRING=a=b
1131
1132  Comments in the code below refer to using the above URL in a request
1133
1134 */
1135static void init_request_info(fcgi_request *request TSRMLS_DC)
1136{
1137    char *env_script_filename = CGI_GETENV("SCRIPT_FILENAME");
1138    char *env_path_translated = CGI_GETENV("PATH_TRANSLATED");
1139    char *script_path_translated = env_script_filename;
1140
1141    /* some broken servers do not have script_filename or argv0
1142     * an example, IIS configured in some ways.  then they do more
1143     * broken stuff and set path_translated to the cgi script location */
1144    if (!script_path_translated && env_path_translated) {
1145        script_path_translated = env_path_translated;
1146    }
1147
1148    /* initialize the defaults */
1149    SG(request_info).path_translated = NULL;
1150    SG(request_info).request_method = NULL;
1151    SG(request_info).proto_num = 1000;
1152    SG(request_info).query_string = NULL;
1153    SG(request_info).request_uri = NULL;
1154    SG(request_info).content_type = NULL;
1155    SG(request_info).content_length = 0;
1156    SG(sapi_headers).http_response_code = 200;
1157
1158    /* script_path_translated being set is a good indication that
1159     * we are running in a cgi environment, since it is always
1160     * null otherwise.  otherwise, the filename
1161     * of the script will be retreived later via argc/argv */
1162    if (script_path_translated) {
1163        const char *auth;
1164        char *content_length = CGI_GETENV("CONTENT_LENGTH");
1165        char *content_type = CGI_GETENV("CONTENT_TYPE");
1166        char *env_path_info = CGI_GETENV("PATH_INFO");
1167        char *env_script_name = CGI_GETENV("SCRIPT_NAME");
1168
1169#ifdef PHP_WIN32
1170        /* Hack for buggy IIS that sets incorrect PATH_INFO */
1171        char *env_server_software = CGI_GETENV("SERVER_SOFTWARE");
1172
1173        if (env_server_software &&
1174            env_script_name &&
1175            env_path_info &&
1176            strncmp(env_server_software, "Microsoft-IIS", sizeof("Microsoft-IIS")-1) == 0 &&
1177            strncmp(env_path_info, env_script_name, strlen(env_script_name)) == 0
1178        ) {
1179            env_path_info = CGI_PUTENV("ORIG_PATH_INFO", env_path_info);
1180            env_path_info += strlen(env_script_name);
1181            if (*env_path_info == 0) {
1182                env_path_info = NULL;
1183            }
1184            env_path_info = CGI_PUTENV("PATH_INFO", env_path_info);
1185        }
1186#endif
1187
1188        if (CGIG(fix_pathinfo)) {
1189            struct stat st;
1190            char *real_path = NULL;
1191            char *env_redirect_url = CGI_GETENV("REDIRECT_URL");
1192            char *env_document_root = CGI_GETENV("DOCUMENT_ROOT");
1193            char *orig_path_translated = env_path_translated;
1194            char *orig_path_info = env_path_info;
1195            char *orig_script_name = env_script_name;
1196            char *orig_script_filename = env_script_filename;
1197            int script_path_translated_len;
1198
1199            if (!env_document_root && PG(doc_root)) {
1200                env_document_root = CGI_PUTENV("DOCUMENT_ROOT", PG(doc_root));
1201                /* fix docroot */
1202                TRANSLATE_SLASHES(env_document_root);
1203            }
1204
1205            if (env_path_translated != NULL && env_redirect_url != NULL &&
1206                env_path_translated != script_path_translated &&
1207                strcmp(env_path_translated, script_path_translated) != 0) {
1208                /*
1209                 * pretty much apache specific.  If we have a redirect_url
1210                 * then our script_filename and script_name point to the
1211                 * php executable
1212                 */
1213                script_path_translated = env_path_translated;
1214                /* we correct SCRIPT_NAME now in case we don't have PATH_INFO */
1215                env_script_name = env_redirect_url;
1216            }
1217
1218#ifdef __riscos__
1219            /* Convert path to unix format*/
1220            __riscosify_control |= __RISCOSIFY_DONT_CHECK_DIR;
1221            script_path_translated = __unixify(script_path_translated, 0, NULL, 1, 0);
1222#endif
1223
1224            /*
1225             * if the file doesn't exist, try to extract PATH_INFO out
1226             * of it by stat'ing back through the '/'
1227             * this fixes url's like /info.php/test
1228             */
1229            if (script_path_translated &&
1230                (script_path_translated_len = strlen(script_path_translated)) > 0 &&
1231                (script_path_translated[script_path_translated_len-1] == '/' ||
1232#ifdef PHP_WIN32
1233                script_path_translated[script_path_translated_len-1] == '\\' ||
1234#endif
1235                (real_path = tsrm_realpath(script_path_translated, NULL TSRMLS_CC)) == NULL)
1236            ) {
1237                char *pt = estrndup(script_path_translated, script_path_translated_len);
1238                int len = script_path_translated_len;
1239                char *ptr;
1240
1241                while ((ptr = strrchr(pt, '/')) || (ptr = strrchr(pt, '\\'))) {
1242                    *ptr = 0;
1243                    if (stat(pt, &st) == 0 && S_ISREG(st.st_mode)) {
1244                        /*
1245                         * okay, we found the base script!
1246                         * work out how many chars we had to strip off;
1247                         * then we can modify PATH_INFO
1248                         * accordingly
1249                         *
1250                         * we now have the makings of
1251                         * PATH_INFO=/test
1252                         * SCRIPT_FILENAME=/docroot/info.php
1253                         *
1254                         * we now need to figure out what docroot is.
1255                         * if DOCUMENT_ROOT is set, this is easy, otherwise,
1256                         * we have to play the game of hide and seek to figure
1257                         * out what SCRIPT_NAME should be
1258                         */
1259                        int slen = len - strlen(pt);
1260                        int pilen = env_path_info ? strlen(env_path_info) : 0;
1261                        char *path_info = env_path_info ? env_path_info + pilen - slen : NULL;
1262
1263                        if (orig_path_info != path_info) {
1264                            if (orig_path_info) {
1265                                char old;
1266
1267                                CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
1268                                old = path_info[0];
1269                                path_info[0] = 0;
1270                                if (!orig_script_name ||
1271                                    strcmp(orig_script_name, env_path_info) != 0) {
1272                                    if (orig_script_name) {
1273                                        CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1274                                    }
1275                                    SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_path_info);
1276                                } else {
1277                                    SG(request_info).request_uri = orig_script_name;
1278                                }
1279                                path_info[0] = old;
1280                            }
1281                            env_path_info = CGI_PUTENV("PATH_INFO", path_info);
1282                        }
1283                        if (!orig_script_filename ||
1284                            strcmp(orig_script_filename, pt) != 0) {
1285                            if (orig_script_filename) {
1286                                CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1287                            }
1288                            script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", pt);
1289                        }
1290                        TRANSLATE_SLASHES(pt);
1291
1292                        /* figure out docroot
1293                         * SCRIPT_FILENAME minus SCRIPT_NAME
1294                         */
1295                        if (env_document_root) {
1296                            int l = strlen(env_document_root);
1297                            int path_translated_len = 0;
1298                            char *path_translated = NULL;
1299
1300                            if (l && env_document_root[l - 1] == '/') {
1301                                --l;
1302                            }
1303
1304                            /* we have docroot, so we should have:
1305                             * DOCUMENT_ROOT=/docroot
1306                             * SCRIPT_FILENAME=/docroot/info.php
1307                             */
1308
1309                            /* PATH_TRANSLATED = DOCUMENT_ROOT + PATH_INFO */
1310                            path_translated_len = l + (env_path_info ? strlen(env_path_info) : 0);
1311                            path_translated = (char *) emalloc(path_translated_len + 1);
1312                            memcpy(path_translated, env_document_root, l);
1313                            if (env_path_info) {
1314                                memcpy(path_translated + l, env_path_info, (path_translated_len - l));
1315                            }
1316                            path_translated[path_translated_len] = '\0';
1317                            if (orig_path_translated) {
1318                                CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1319                            }
1320                            env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
1321                            efree(path_translated);
1322                        } else if ( env_script_name &&
1323                                    strstr(pt, env_script_name)
1324                        ) {
1325                            /* PATH_TRANSLATED = PATH_TRANSLATED - SCRIPT_NAME + PATH_INFO */
1326                            int ptlen = strlen(pt) - strlen(env_script_name);
1327                            int path_translated_len = ptlen + (env_path_info ? strlen(env_path_info) : 0);
1328                            char *path_translated = NULL;
1329
1330                            path_translated = (char *) emalloc(path_translated_len + 1);
1331                            memcpy(path_translated, pt, ptlen);
1332                            if (env_path_info) {
1333                                memcpy(path_translated + ptlen, env_path_info, path_translated_len - ptlen);
1334                            }
1335                            path_translated[path_translated_len] = '\0';
1336                            if (orig_path_translated) {
1337                                CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1338                            }
1339                            env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
1340                            efree(path_translated);
1341                        }
1342                        break;
1343                    }
1344                }
1345                if (!ptr) {
1346                    /*
1347                     * if we stripped out all the '/' and still didn't find
1348                     * a valid path... we will fail, badly. of course we would
1349                     * have failed anyway... we output 'no input file' now.
1350                     */
1351                    if (orig_script_filename) {
1352                        CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1353                    }
1354                    script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", NULL);
1355                    SG(sapi_headers).http_response_code = 404;
1356                }
1357                if (!SG(request_info).request_uri) {
1358                    if (!orig_script_name ||
1359                        strcmp(orig_script_name, env_script_name) != 0) {
1360                        if (orig_script_name) {
1361                            CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1362                        }
1363                        SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
1364                    } else {
1365                        SG(request_info).request_uri = orig_script_name;
1366                    }
1367                }
1368                if (pt) {
1369                    efree(pt);
1370                }
1371            } else {
1372                /* make sure path_info/translated are empty */
1373                if (!orig_script_filename ||
1374                    (script_path_translated != orig_script_filename &&
1375                    strcmp(script_path_translated, orig_script_filename) != 0)) {
1376                    if (orig_script_filename) {
1377                        CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1378                    }
1379                    script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", script_path_translated);
1380                }
1381                if (env_redirect_url) {
1382                    if (orig_path_info) {
1383                        CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
1384                        CGI_PUTENV("PATH_INFO", NULL);
1385                    }
1386                    if (orig_path_translated) {
1387                        CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1388                        CGI_PUTENV("PATH_TRANSLATED", NULL);
1389                    }
1390                }
1391                if (env_script_name != orig_script_name) {
1392                    if (orig_script_name) {
1393                        CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1394                    }
1395                    SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
1396                } else {
1397                    SG(request_info).request_uri = env_script_name;
1398                }
1399                free(real_path);
1400            }
1401        } else {
1402            /* pre 4.3 behaviour, shouldn't be used but provides BC */
1403            if (env_path_info) {
1404                SG(request_info).request_uri = env_path_info;
1405            } else {
1406                SG(request_info).request_uri = env_script_name;
1407            }
1408            if (!CGIG(discard_path) && env_path_translated) {
1409                script_path_translated = env_path_translated;
1410            }
1411        }
1412
1413        if (is_valid_path(script_path_translated)) {
1414            SG(request_info).path_translated = estrdup(script_path_translated);
1415        }
1416
1417        SG(request_info).request_method = CGI_GETENV("REQUEST_METHOD");
1418        /* FIXME - Work out proto_num here */
1419        SG(request_info).query_string = CGI_GETENV("QUERY_STRING");
1420        SG(request_info).content_type = (content_type ? content_type : "" );
1421        SG(request_info).content_length = (content_length ? atol(content_length) : 0);
1422
1423        /* The CGI RFC allows servers to pass on unvalidated Authorization data */
1424        auth = CGI_GETENV("HTTP_AUTHORIZATION");
1425        php_handle_auth_data(auth TSRMLS_CC);
1426    }
1427}
1428/* }}} */
1429
1430#ifndef PHP_WIN32
1431/**
1432 * Clean up child processes upon exit
1433 */
1434void fastcgi_cleanup(int signal)
1435{
1436#ifdef DEBUG_FASTCGI
1437    fprintf(stderr, "FastCGI shutdown, pid %d\n", getpid());
1438#endif
1439
1440    sigaction(SIGTERM, &old_term, 0);
1441
1442    /* Kill all the processes in our process group */
1443    kill(-pgroup, SIGTERM);
1444
1445    if (parent && parent_waiting) {
1446        exit_signal = 1;
1447    } else {
1448        exit(0);
1449    }
1450}
1451#endif
1452
1453PHP_INI_BEGIN()
1454    STD_PHP_INI_ENTRY("cgi.rfc2616_headers",     "0",  PHP_INI_ALL,    OnUpdateBool,   rfc2616_headers, php_cgi_globals_struct, php_cgi_globals)
1455    STD_PHP_INI_ENTRY("cgi.nph",                 "0",  PHP_INI_ALL,    OnUpdateBool,   nph, php_cgi_globals_struct, php_cgi_globals)
1456    STD_PHP_INI_ENTRY("cgi.check_shebang_line",  "1",  PHP_INI_SYSTEM, OnUpdateBool,   check_shebang_line, php_cgi_globals_struct, php_cgi_globals)
1457    STD_PHP_INI_ENTRY("cgi.force_redirect",      "1",  PHP_INI_SYSTEM, OnUpdateBool,   force_redirect, php_cgi_globals_struct, php_cgi_globals)
1458    STD_PHP_INI_ENTRY("cgi.redirect_status_env", NULL, PHP_INI_SYSTEM, OnUpdateString, redirect_status_env, php_cgi_globals_struct, php_cgi_globals)
1459    STD_PHP_INI_ENTRY("cgi.fix_pathinfo",        "1",  PHP_INI_SYSTEM, OnUpdateBool,   fix_pathinfo, php_cgi_globals_struct, php_cgi_globals)
1460    STD_PHP_INI_ENTRY("cgi.discard_path",        "0",  PHP_INI_SYSTEM, OnUpdateBool,   discard_path, php_cgi_globals_struct, php_cgi_globals)
1461    STD_PHP_INI_ENTRY("fastcgi.logging",         "1",  PHP_INI_SYSTEM, OnUpdateBool,   fcgi_logging, php_cgi_globals_struct, php_cgi_globals)
1462#ifdef PHP_WIN32
1463    STD_PHP_INI_ENTRY("fastcgi.impersonate",     "0",  PHP_INI_SYSTEM, OnUpdateBool,   impersonate, php_cgi_globals_struct, php_cgi_globals)
1464#endif
1465PHP_INI_END()
1466
1467/* {{{ php_cgi_globals_ctor
1468 */
1469static void php_cgi_globals_ctor(php_cgi_globals_struct *php_cgi_globals TSRMLS_DC)
1470{
1471    php_cgi_globals->rfc2616_headers = 0;
1472    php_cgi_globals->nph = 0;
1473    php_cgi_globals->check_shebang_line = 1;
1474    php_cgi_globals->force_redirect = 1;
1475    php_cgi_globals->redirect_status_env = NULL;
1476    php_cgi_globals->fix_pathinfo = 1;
1477    php_cgi_globals->discard_path = 0;
1478    php_cgi_globals->fcgi_logging = 1;
1479#ifdef PHP_WIN32
1480    php_cgi_globals->impersonate = 0;
1481#endif
1482    zend_hash_init(&php_cgi_globals->user_config_cache, 0, NULL, (dtor_func_t) user_config_cache_entry_dtor, 1);
1483}
1484/* }}} */
1485
1486/* {{{ PHP_MINIT_FUNCTION
1487 */
1488static PHP_MINIT_FUNCTION(cgi)
1489{
1490#ifdef ZTS
1491    ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
1492#else
1493    php_cgi_globals_ctor(&php_cgi_globals TSRMLS_CC);
1494#endif
1495    REGISTER_INI_ENTRIES();
1496    return SUCCESS;
1497}
1498/* }}} */
1499
1500/* {{{ PHP_MSHUTDOWN_FUNCTION
1501 */
1502static PHP_MSHUTDOWN_FUNCTION(cgi)
1503{
1504    zend_hash_destroy(&CGIG(user_config_cache));
1505
1506    UNREGISTER_INI_ENTRIES();
1507    return SUCCESS;
1508}
1509/* }}} */
1510
1511/* {{{ PHP_MINFO_FUNCTION
1512 */
1513static PHP_MINFO_FUNCTION(cgi)
1514{
1515    DISPLAY_INI_ENTRIES();
1516}
1517/* }}} */
1518
1519PHP_FUNCTION(apache_child_terminate) /* {{{ */
1520{
1521    if (ZEND_NUM_ARGS() > 0) {
1522        WRONG_PARAM_COUNT;
1523    }
1524    if (fcgi_is_fastcgi()) {
1525        fcgi_terminate();
1526    }
1527}
1528/* }}} */
1529
1530static void add_request_header(char *var, unsigned int var_len, char *val, unsigned int val_len, void *arg TSRMLS_DC) /* {{{ */
1531{
1532    zval *return_value = (zval*)arg;
1533    char *str = NULL;
1534    char *p;
1535    ALLOCA_FLAG(use_heap)
1536
1537    if (var_len > 5 &&
1538        var[0] == 'H' &&
1539        var[1] == 'T' &&
1540        var[2] == 'T' &&
1541        var[3] == 'P' &&
1542        var[4] == '_') {
1543
1544        var_len -= 5;
1545        p = var + 5;
1546        var = str = do_alloca(var_len + 1, use_heap);
1547        *str++ = *p++;
1548        while (*p) {
1549            if (*p == '_') {
1550                *str++ = '-';
1551                p++;
1552                if (*p) {
1553                    *str++ = *p++;
1554                }
1555            } else if (*p >= 'A' && *p <= 'Z') {
1556                *str++ = (*p++ - 'A' + 'a');
1557            } else {
1558                *str++ = *p++;
1559            }
1560        }
1561        *str = 0;
1562    } else if (var_len == sizeof("CONTENT_TYPE")-1 &&
1563               memcmp(var, "CONTENT_TYPE", sizeof("CONTENT_TYPE")-1) == 0) {
1564        var = "Content-Type";
1565    } else if (var_len == sizeof("CONTENT_LENGTH")-1 &&
1566               memcmp(var, "CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1) == 0) {
1567        var = "Content-Length";
1568    } else {
1569        return;
1570    }
1571    add_assoc_stringl_ex(return_value, var, var_len+1, val, val_len, 1);
1572    if (str) {
1573        free_alloca(var, use_heap);
1574    }
1575}
1576/* }}} */
1577
1578PHP_FUNCTION(apache_request_headers) /* {{{ */
1579{
1580    if (ZEND_NUM_ARGS() > 0) {
1581        WRONG_PARAM_COUNT;
1582    }
1583    array_init(return_value);
1584    if (fcgi_is_fastcgi()) {
1585        fcgi_request *request = (fcgi_request*) SG(server_context);
1586
1587        fcgi_loadenv(request, add_request_header, return_value TSRMLS_CC);
1588    } else {
1589        char buf[128];
1590        char **env, *p, *q, *var, *val, *t = buf;
1591        size_t alloc_size = sizeof(buf);
1592        unsigned long var_len;
1593
1594        for (env = environ; env != NULL && *env != NULL; env++) {
1595            val = strchr(*env, '=');
1596            if (!val) {             /* malformed entry? */
1597                continue;
1598            }
1599            var_len = val - *env;
1600            if (var_len >= alloc_size) {
1601                alloc_size = var_len + 64;
1602                t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
1603            }
1604            var = *env;
1605            if (var_len > 5 &&
1606                var[0] == 'H' &&
1607                var[1] == 'T' &&
1608                var[2] == 'T' &&
1609                var[3] == 'P' &&
1610                var[4] == '_') {
1611
1612                var_len -= 5;
1613
1614                if (var_len >= alloc_size) {
1615                    alloc_size = var_len + 64;
1616                    t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
1617                }
1618                p = var + 5;
1619
1620                var = q = t;
1621                /* First char keep uppercase */
1622                *q++ = *p++;
1623                while (*p) {
1624                    if (*p == '=') {
1625                        /* End of name */
1626                        break;
1627                    } else if (*p == '_') {
1628                        *q++ = '-';
1629                        p++;
1630                        /* First char after - keep uppercase */
1631                        if (*p && *p!='=') {
1632                            *q++ = *p++;
1633                        }
1634                    } else if (*p >= 'A' && *p <= 'Z') {
1635                        /* lowercase */
1636                        *q++ = (*p++ - 'A' + 'a');
1637                    } else {
1638                        *q++ = *p++;
1639                    }
1640                }
1641                *q = 0;
1642            } else if (var_len == sizeof("CONTENT_TYPE")-1 &&
1643                       memcmp(var, "CONTENT_TYPE", sizeof("CONTENT_TYPE")-1) == 0) {
1644                var = "Content-Type";
1645            } else if (var_len == sizeof("CONTENT_LENGTH")-1 &&
1646                       memcmp(var, "CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1) == 0) {
1647                var = "Content-Length";
1648            } else {
1649                continue;
1650            }
1651            val++;
1652            add_assoc_string_ex(return_value, var, var_len+1, val, 1);
1653        }
1654        if (t != buf && t != NULL) {
1655            efree(t);
1656        }
1657    }
1658}
1659/* }}} */
1660
1661static void add_response_header(sapi_header_struct *h, zval *return_value TSRMLS_DC) /* {{{ */
1662{
1663    char *s, *p;
1664    int  len;
1665    ALLOCA_FLAG(use_heap)
1666
1667    if (h->header_len > 0) {
1668        p = strchr(h->header, ':');
1669        len = p - h->header;
1670        if (p && (len > 0)) {
1671            while (len > 0 && (h->header[len-1] == ' ' || h->header[len-1] == '\t')) {
1672                len--;
1673            }
1674            if (len) {
1675                s = do_alloca(len + 1, use_heap);
1676                memcpy(s, h->header, len);
1677                s[len] = 0;
1678                do {
1679                    p++;
1680                } while (*p == ' ' || *p == '\t');
1681                add_assoc_stringl_ex(return_value, s, len+1, p, h->header_len - (p - h->header), 1);
1682                free_alloca(s, use_heap);
1683            }
1684        }
1685    }
1686}
1687/* }}} */
1688
1689PHP_FUNCTION(apache_response_headers) /* {{{ */
1690{
1691    if (zend_parse_parameters_none() == FAILURE) {
1692        return;
1693    }
1694
1695    if (!&SG(sapi_headers).headers) {
1696        RETURN_FALSE;
1697    }
1698    array_init(return_value);
1699    zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t)add_response_header, return_value TSRMLS_CC);
1700}
1701/* }}} */
1702
1703ZEND_BEGIN_ARG_INFO(arginfo_no_args, 0)
1704ZEND_END_ARG_INFO()
1705
1706const zend_function_entry cgi_functions[] = {
1707    PHP_FE(apache_child_terminate, arginfo_no_args)
1708    PHP_FE(apache_request_headers, arginfo_no_args)
1709    PHP_FE(apache_response_headers, arginfo_no_args)
1710    PHP_FALIAS(getallheaders, apache_request_headers, arginfo_no_args)
1711    {NULL, NULL, NULL}
1712};
1713
1714static zend_module_entry cgi_module_entry = {
1715    STANDARD_MODULE_HEADER,
1716    "cgi-fcgi",
1717    cgi_functions,
1718    PHP_MINIT(cgi),
1719    PHP_MSHUTDOWN(cgi),
1720    NULL,
1721    NULL,
1722    PHP_MINFO(cgi),
1723    NO_VERSION_YET,
1724    STANDARD_MODULE_PROPERTIES
1725};
1726
1727/* {{{ main
1728 */
1729int main(int argc, char *argv[])
1730{
1731    int free_query_string = 0;
1732    int exit_status = SUCCESS;
1733    int cgi = 0, c, i, len;
1734    zend_file_handle file_handle;
1735    char *s;
1736
1737    /* temporary locals */
1738    int behavior = PHP_MODE_STANDARD;
1739    int no_headers = 0;
1740    int orig_optind = php_optind;
1741    char *orig_optarg = php_optarg;
1742    char *script_file = NULL;
1743    int ini_entries_len = 0;
1744    /* end of temporary locals */
1745
1746#ifdef ZTS
1747    void ***tsrm_ls;
1748#endif
1749
1750    int max_requests = 500;
1751    int requests = 0;
1752    int fastcgi;
1753    char *bindpath = NULL;
1754    int fcgi_fd = 0;
1755    fcgi_request *request = NULL;
1756    int repeats = 1;
1757    int benchmark = 0;
1758#if HAVE_GETTIMEOFDAY
1759    struct timeval start, end;
1760#else
1761    time_t start, end;
1762#endif
1763#ifndef PHP_WIN32
1764    int status = 0;
1765#endif
1766    char *query_string;
1767    char *decoded_query_string;
1768    int skip_getopt = 0;
1769
1770#if 0 && defined(PHP_DEBUG)
1771    /* IIS is always making things more difficult.  This allows
1772     * us to stop PHP and attach a debugger before much gets started */
1773    {
1774        char szMessage [256];
1775        wsprintf (szMessage, "Please attach a debugger to the process 0x%X [%d] (%s) and click OK", GetCurrentProcessId(), GetCurrentProcessId(), argv[0]);
1776        MessageBox(NULL, szMessage, "CGI Debug Time!", MB_OK|MB_SERVICE_NOTIFICATION);
1777    }
1778#endif
1779
1780#ifdef HAVE_SIGNAL_H
1781#if defined(SIGPIPE) && defined(SIG_IGN)
1782    signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
1783                                that sockets created via fsockopen()
1784                                don't kill PHP if the remote site
1785                                closes it.  in apache|apxs mode apache
1786                                does that for us!  thies@thieso.net
1787                                20000419 */
1788#endif
1789#endif
1790
1791#ifdef ZTS
1792    tsrm_startup(1, 1, 0, NULL);
1793    tsrm_ls = ts_resource(0);
1794#endif
1795
1796    sapi_startup(&cgi_sapi_module);
1797    fastcgi = fcgi_is_fastcgi();
1798    cgi_sapi_module.php_ini_path_override = NULL;
1799
1800#ifdef PHP_WIN32
1801    _fmode = _O_BINARY; /* sets default for file streams to binary */
1802    setmode(_fileno(stdin),  O_BINARY); /* make the stdio mode be binary */
1803    setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */
1804    setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */
1805#endif
1806
1807    if (!fastcgi) {
1808        /* Make sure we detect we are a cgi - a bit redundancy here,
1809         * but the default case is that we have to check only the first one. */
1810        if (getenv("SERVER_SOFTWARE") ||
1811            getenv("SERVER_NAME") ||
1812            getenv("GATEWAY_INTERFACE") ||
1813            getenv("REQUEST_METHOD")
1814        ) {
1815            cgi = 1;
1816        }
1817    }
1818
1819    if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) {
1820        /* we've got query string that has no = - apache CGI will pass it to command line */
1821        unsigned char *p;
1822        decoded_query_string = strdup(query_string);
1823        php_url_decode(decoded_query_string, strlen(decoded_query_string));
1824        for (p = decoded_query_string; *p &&  *p <= ' '; p++) {
1825            /* skip all leading spaces */
1826        }
1827        if(*p == '-') {
1828            skip_getopt = 1;
1829        }
1830        free(decoded_query_string);
1831    }
1832
1833    while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
1834        switch (c) {
1835            case 'c':
1836                if (cgi_sapi_module.php_ini_path_override) {
1837                    free(cgi_sapi_module.php_ini_path_override);
1838                }
1839                cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
1840                break;
1841            case 'n':
1842                cgi_sapi_module.php_ini_ignore = 1;
1843                break;
1844            case 'd': {
1845                /* define ini entries on command line */
1846                int len = strlen(php_optarg);
1847                char *val;
1848
1849                if ((val = strchr(php_optarg, '='))) {
1850                    val++;
1851                    if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
1852                        cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
1853                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
1854                        ini_entries_len += (val - php_optarg);
1855                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1);
1856                        ini_entries_len++;
1857                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
1858                        ini_entries_len += len - (val - php_optarg);
1859                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
1860                        ini_entries_len += sizeof("\n\0\"") - 2;
1861                    } else {
1862                        cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
1863                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
1864                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
1865                        ini_entries_len += len + sizeof("\n\0") - 2;
1866                    }
1867                } else {
1868                    cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
1869                    memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
1870                    memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
1871                    ini_entries_len += len + sizeof("=1\n\0") - 2;
1872                }
1873                break;
1874            }
1875            /* if we're started on command line, check to see if
1876             * we are being started as an 'external' fastcgi
1877             * server by accepting a bindpath parameter. */
1878            case 'b':
1879                if (!fastcgi) {
1880                    bindpath = strdup(php_optarg);
1881                }
1882                break;
1883            case 's': /* generate highlighted HTML from source */
1884                behavior = PHP_MODE_HIGHLIGHT;
1885                break;
1886        }
1887    }
1888    php_optind = orig_optind;
1889    php_optarg = orig_optarg;
1890
1891    if (fastcgi || bindpath) {
1892        /* Override SAPI callbacks */
1893        cgi_sapi_module.ub_write     = sapi_fcgi_ub_write;
1894        cgi_sapi_module.flush        = sapi_fcgi_flush;
1895        cgi_sapi_module.read_post    = sapi_fcgi_read_post;
1896        cgi_sapi_module.getenv       = sapi_fcgi_getenv;
1897        cgi_sapi_module.read_cookies = sapi_fcgi_read_cookies;
1898    }
1899
1900#ifdef ZTS
1901    SG(request_info).path_translated = NULL;
1902#endif
1903
1904    cgi_sapi_module.executable_location = argv[0];
1905    if (!cgi && !fastcgi && !bindpath) {
1906        cgi_sapi_module.additional_functions = additional_functions;
1907    }
1908
1909    /* startup after we get the above ini override se we get things right */
1910    if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
1911#ifdef ZTS
1912        tsrm_shutdown();
1913#endif
1914        return FAILURE;
1915    }
1916
1917    /* check force_cgi after startup, so we have proper output */
1918    if (cgi && CGIG(force_redirect)) {
1919        /* Apache will generate REDIRECT_STATUS,
1920         * Netscape and redirect.so will generate HTTP_REDIRECT_STATUS.
1921         * redirect.so and installation instructions available from
1922         * http://www.koehntopp.de/php.
1923         *   -- kk@netuse.de
1924         */
1925        if (!getenv("REDIRECT_STATUS") &&
1926            !getenv ("HTTP_REDIRECT_STATUS") &&
1927            /* this is to allow a different env var to be configured
1928             * in case some server does something different than above */
1929            (!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env)))
1930        ) {
1931            zend_try {
1932                SG(sapi_headers).http_response_code = 400;
1933                PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
1934<p>This PHP CGI binary was compiled with force-cgi-redirect enabled.  This\n\
1935means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
1936set, e.g. via an Apache Action directive.</p>\n\
1937<p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
1938manual page for CGI security</a>.</p>\n\
1939<p>For more information about changing this behaviour or re-enabling this webserver,\n\
1940consult the installation file that came with this distribution, or visit \n\
1941<a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
1942            } zend_catch {
1943            } zend_end_try();
1944#if defined(ZTS) && !defined(PHP_DEBUG)
1945            /* XXX we're crashing here in msvc6 debug builds at
1946             * php_message_handler_for_zend:839 because
1947             * SG(request_info).path_translated is an invalid pointer.
1948             * It still happens even though I set it to null, so something
1949             * weird is going on.
1950             */
1951            tsrm_shutdown();
1952#endif
1953            return FAILURE;
1954        }
1955    }
1956
1957    if (bindpath) {
1958        int backlog = 128;
1959        if (getenv("PHP_FCGI_BACKLOG")) {
1960            backlog = atoi(getenv("PHP_FCGI_BACKLOG"));
1961        }
1962        fcgi_fd = fcgi_listen(bindpath, backlog);
1963        if (fcgi_fd < 0) {
1964            fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath);
1965#ifdef ZTS
1966            tsrm_shutdown();
1967#endif
1968            return FAILURE;
1969        }
1970        fastcgi = fcgi_is_fastcgi();
1971    }
1972    if (fastcgi) {
1973        /* How many times to run PHP scripts before dying */
1974        if (getenv("PHP_FCGI_MAX_REQUESTS")) {
1975            max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS"));
1976            if (max_requests < 0) {
1977                fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n");
1978                return FAILURE;
1979            }
1980        }
1981
1982        /* make php call us to get _ENV vars */
1983        php_php_import_environment_variables = php_import_environment_variables;
1984        php_import_environment_variables = cgi_php_import_environment_variables;
1985
1986        /* library is already initialized, now init our request */
1987        request = fcgi_init_request(fcgi_fd);
1988
1989#ifndef PHP_WIN32
1990    /* Pre-fork, if required */
1991    if (getenv("PHP_FCGI_CHILDREN")) {
1992        char * children_str = getenv("PHP_FCGI_CHILDREN");
1993        children = atoi(children_str);
1994        if (children < 0) {
1995            fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n");
1996            return FAILURE;
1997        }
1998        fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str));
1999        /* This is the number of concurrent requests, equals FCGI_MAX_CONNS */
2000        fcgi_set_mgmt_var("FCGI_MAX_REQS",  sizeof("FCGI_MAX_REQS")-1,  children_str, strlen(children_str));
2001    } else {
2002        fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1);
2003        fcgi_set_mgmt_var("FCGI_MAX_REQS",  sizeof("FCGI_MAX_REQS")-1,  "1", sizeof("1")-1);
2004    }
2005
2006    if (children) {
2007        int running = 0;
2008        pid_t pid;
2009
2010        /* Create a process group for ourself & children */
2011        setsid();
2012        pgroup = getpgrp();
2013#ifdef DEBUG_FASTCGI
2014        fprintf(stderr, "Process group %d\n", pgroup);
2015#endif
2016
2017        /* Set up handler to kill children upon exit */
2018        act.sa_flags = 0;
2019        act.sa_handler = fastcgi_cleanup;
2020        if (sigaction(SIGTERM, &act, &old_term) ||
2021            sigaction(SIGINT,  &act, &old_int)  ||
2022            sigaction(SIGQUIT, &act, &old_quit)
2023        ) {
2024            perror("Can't set signals");
2025            exit(1);
2026        }
2027
2028        if (fcgi_in_shutdown()) {
2029            goto parent_out;
2030        }
2031
2032        while (parent) {
2033            do {
2034#ifdef DEBUG_FASTCGI
2035                fprintf(stderr, "Forking, %d running\n", running);
2036#endif
2037                pid = fork();
2038                switch (pid) {
2039                case 0:
2040                    /* One of the children.
2041                     * Make sure we don't go round the
2042                     * fork loop any more
2043                     */
2044                    parent = 0;
2045
2046                    /* don't catch our signals */
2047                    sigaction(SIGTERM, &old_term, 0);
2048                    sigaction(SIGQUIT, &old_quit, 0);
2049                    sigaction(SIGINT,  &old_int,  0);
2050                    break;
2051                case -1:
2052                    perror("php (pre-forking)");
2053                    exit(1);
2054                    break;
2055                default:
2056                    /* Fine */
2057                    running++;
2058                    break;
2059                }
2060            } while (parent && (running < children));
2061
2062            if (parent) {
2063#ifdef DEBUG_FASTCGI
2064                fprintf(stderr, "Wait for kids, pid %d\n", getpid());
2065#endif
2066                parent_waiting = 1;
2067                while (1) {
2068                    if (wait(&status) >= 0) {
2069                        running--;
2070                        break;
2071                    } else if (exit_signal) {
2072                        break;
2073                    }
2074                }
2075                if (exit_signal) {
2076#if 0
2077                    while (running > 0) {
2078                        while (wait(&status) < 0) {
2079                        }
2080                        running--;
2081                    }
2082#endif
2083                    goto parent_out;
2084                }
2085            }
2086        }
2087    } else {
2088        parent = 0;
2089    }
2090
2091#endif /* WIN32 */
2092    }
2093
2094    zend_first_try {
2095        while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) {
2096            switch (c) {
2097                case 'T':
2098                    benchmark = 1;
2099                    repeats = atoi(php_optarg);
2100#ifdef HAVE_GETTIMEOFDAY
2101                    gettimeofday(&start, NULL);
2102#else
2103                    time(&start);
2104#endif
2105                    break;
2106                case 'h':
2107                case '?':
2108                    if (request) {
2109                        fcgi_destroy_request(request);
2110                    }
2111                    fcgi_shutdown();
2112                    no_headers = 1;
2113                    SG(headers_sent) = 1;
2114                    php_cgi_usage(argv[0]);
2115                    php_output_end_all(TSRMLS_C);
2116                    exit_status = 0;
2117                    goto out;
2118            }
2119        }
2120        php_optind = orig_optind;
2121        php_optarg = orig_optarg;
2122
2123        /* start of FAST CGI loop */
2124        /* Initialise FastCGI request structure */
2125#ifdef PHP_WIN32
2126        /* attempt to set security impersonation for fastcgi
2127         * will only happen on NT based OS, others will ignore it. */
2128        if (fastcgi && CGIG(impersonate)) {
2129            fcgi_impersonate();
2130        }
2131#endif
2132        while (!fastcgi || fcgi_accept_request(request) >= 0) {
2133            SG(server_context) = fastcgi ? (void *) request : (void *) 1;
2134            init_request_info(request TSRMLS_CC);
2135            CG(interactive) = 0;
2136
2137            if (!cgi && !fastcgi) {
2138                while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
2139                    switch (c) {
2140
2141                        case 'a':   /* interactive mode */
2142                            printf("Interactive mode enabled\n\n");
2143                            CG(interactive) = 1;
2144                            break;
2145
2146                        case 'C': /* don't chdir to the script directory */
2147                            SG(options) |= SAPI_OPTION_NO_CHDIR;
2148                            break;
2149
2150                        case 'e': /* enable extended info output */
2151                            CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
2152                            break;
2153
2154                        case 'f': /* parse file */
2155                            if (script_file) {
2156                                efree(script_file);
2157                            }
2158                            script_file = estrdup(php_optarg);
2159                            no_headers = 1;
2160                            break;
2161
2162                        case 'i': /* php info & quit */
2163                            if (script_file) {
2164                                efree(script_file);
2165                            }
2166                            if (php_request_startup(TSRMLS_C) == FAILURE) {
2167                                SG(server_context) = NULL;
2168                                php_module_shutdown(TSRMLS_C);
2169                                return FAILURE;
2170                            }
2171                            if (no_headers) {
2172                                SG(headers_sent) = 1;
2173                                SG(request_info).no_headers = 1;
2174                            }
2175                            php_print_info(0xFFFFFFFF TSRMLS_CC);
2176                            php_request_shutdown((void *) 0);
2177                            fcgi_shutdown();
2178                            exit_status = 0;
2179                            goto out;
2180
2181                        case 'l': /* syntax check mode */
2182                            no_headers = 1;
2183                            behavior = PHP_MODE_LINT;
2184                            break;
2185
2186                        case 'm': /* list compiled in modules */
2187                            if (script_file) {
2188                                efree(script_file);
2189                            }
2190                            SG(headers_sent) = 1;
2191                            php_printf("[PHP Modules]\n");
2192                            print_modules(TSRMLS_C);
2193                            php_printf("\n[Zend Modules]\n");
2194                            print_extensions(TSRMLS_C);
2195                            php_printf("\n");
2196                            php_output_end_all(TSRMLS_C);
2197                            fcgi_shutdown();
2198                            exit_status = 0;
2199                            goto out;
2200
2201#if 0 /* not yet operational, see also below ... */
2202                        case '': /* generate indented source mode*/
2203                            behavior=PHP_MODE_INDENT;
2204                            break;
2205#endif
2206
2207                        case 'q': /* do not generate HTTP headers */
2208                            no_headers = 1;
2209                            break;
2210
2211                        case 'v': /* show php version & quit */
2212                            if (script_file) {
2213                                efree(script_file);
2214                            }
2215                            no_headers = 1;
2216                            if (php_request_startup(TSRMLS_C) == FAILURE) {
2217                                SG(server_context) = NULL;
2218                                php_module_shutdown(TSRMLS_C);
2219                                return FAILURE;
2220                            }
2221                            if (no_headers) {
2222                                SG(headers_sent) = 1;
2223                                SG(request_info).no_headers = 1;
2224                            }
2225#if ZEND_DEBUG
2226                            php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2014 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
2227#else
2228                            php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2014 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
2229#endif
2230                            php_request_shutdown((void *) 0);
2231                            fcgi_shutdown();
2232                            exit_status = 0;
2233                            goto out;
2234
2235                        case 'w':
2236                            behavior = PHP_MODE_STRIP;
2237                            break;
2238
2239                        case 'z': /* load extension file */
2240                            zend_load_extension(php_optarg);
2241                            break;
2242
2243                        default:
2244                            break;
2245                    }
2246                }
2247
2248                if (script_file) {
2249                    /* override path_translated if -f on command line */
2250                    STR_FREE(SG(request_info).path_translated);
2251                    SG(request_info).path_translated = script_file;
2252                    /* before registering argv to module exchange the *new* argv[0] */
2253                    /* we can achieve this without allocating more memory */
2254                    SG(request_info).argc = argc - (php_optind - 1);
2255                    SG(request_info).argv = &argv[php_optind - 1];
2256                    SG(request_info).argv[0] = script_file;
2257                } else if (argc > php_optind) {
2258                    /* file is on command line, but not in -f opt */
2259                    STR_FREE(SG(request_info).path_translated);
2260                    SG(request_info).path_translated = estrdup(argv[php_optind]);
2261                    /* arguments after the file are considered script args */
2262                    SG(request_info).argc = argc - php_optind;
2263                    SG(request_info).argv = &argv[php_optind];
2264                }
2265
2266                if (no_headers) {
2267                    SG(headers_sent) = 1;
2268                    SG(request_info).no_headers = 1;
2269                }
2270
2271                /* all remaining arguments are part of the query string
2272                 * this section of code concatenates all remaining arguments
2273                 * into a single string, seperating args with a &
2274                 * this allows command lines like:
2275                 *
2276                 *  test.php v1=test v2=hello+world!
2277                 *  test.php "v1=test&v2=hello world!"
2278                 *  test.php v1=test "v2=hello world!"
2279                */
2280                if (!SG(request_info).query_string && argc > php_optind) {
2281                    int slen = strlen(PG(arg_separator).input);
2282                    len = 0;
2283                    for (i = php_optind; i < argc; i++) {
2284                        if (i < (argc - 1)) {
2285                            len += strlen(argv[i]) + slen;
2286                        } else {
2287                            len += strlen(argv[i]);
2288                        }
2289                    }
2290
2291                    len += 2;
2292                    s = malloc(len);
2293                    *s = '\0';          /* we are pretending it came from the environment  */
2294                    for (i = php_optind; i < argc; i++) {
2295                        strlcat(s, argv[i], len);
2296                        if (i < (argc - 1)) {
2297                            strlcat(s, PG(arg_separator).input, len);
2298                        }
2299                    }
2300                    SG(request_info).query_string = s;
2301                    free_query_string = 1;
2302                }
2303            } /* end !cgi && !fastcgi */
2304
2305            /*
2306                we never take stdin if we're (f)cgi, always
2307                rely on the web server giving us the info
2308                we need in the environment.
2309            */
2310            if (SG(request_info).path_translated || cgi || fastcgi) {
2311                file_handle.type = ZEND_HANDLE_FILENAME;
2312                file_handle.filename = SG(request_info).path_translated;
2313                file_handle.handle.fp = NULL;
2314            } else {
2315                file_handle.filename = "-";
2316                file_handle.type = ZEND_HANDLE_FP;
2317                file_handle.handle.fp = stdin;
2318            }
2319
2320            file_handle.opened_path = NULL;
2321            file_handle.free_filename = 0;
2322
2323            /* request startup only after we've done all we can to
2324             * get path_translated */
2325            if (php_request_startup(TSRMLS_C) == FAILURE) {
2326                if (fastcgi) {
2327                    fcgi_finish_request(request, 1);
2328                }
2329                SG(server_context) = NULL;
2330                php_module_shutdown(TSRMLS_C);
2331                return FAILURE;
2332            }
2333            if (no_headers) {
2334                SG(headers_sent) = 1;
2335                SG(request_info).no_headers = 1;
2336            }
2337
2338            /*
2339                at this point path_translated will be set if:
2340                1. we are running from shell and got filename was there
2341                2. we are running as cgi or fastcgi
2342            */
2343            if (cgi || fastcgi || SG(request_info).path_translated) {
2344                if (php_fopen_primary_script(&file_handle TSRMLS_CC) == FAILURE) {
2345                    zend_try {
2346                        if (errno == EACCES) {
2347                            SG(sapi_headers).http_response_code = 403;
2348                            PUTS("Access denied.\n");
2349                        } else {
2350                            SG(sapi_headers).http_response_code = 404;
2351                            PUTS("No input file specified.\n");
2352                        }
2353                    } zend_catch {
2354                    } zend_end_try();
2355                    /* we want to serve more requests if this is fastcgi
2356                     * so cleanup and continue, request shutdown is
2357                     * handled later */
2358                    if (fastcgi) {
2359                        goto fastcgi_request_done;
2360                    }
2361
2362                    STR_FREE(SG(request_info).path_translated);
2363
2364                    if (free_query_string && SG(request_info).query_string) {
2365                        free(SG(request_info).query_string);
2366                        SG(request_info).query_string = NULL;
2367                    }
2368
2369                    php_request_shutdown((void *) 0);
2370                    SG(server_context) = NULL;
2371                    php_module_shutdown(TSRMLS_C);
2372                    sapi_shutdown();
2373#ifdef ZTS
2374                    tsrm_shutdown();
2375#endif
2376                    return FAILURE;
2377                }
2378            }
2379
2380            if (CGIG(check_shebang_line)) {
2381                /* #!php support */
2382                switch (file_handle.type) {
2383                    case ZEND_HANDLE_FD:
2384                        if (file_handle.handle.fd < 0) {
2385                            break;
2386                        }
2387                        file_handle.type = ZEND_HANDLE_FP;
2388                        file_handle.handle.fp = fdopen(file_handle.handle.fd, "rb");
2389                        /* break missing intentionally */
2390                    case ZEND_HANDLE_FP:
2391                        if (!file_handle.handle.fp ||
2392                            (file_handle.handle.fp == stdin)) {
2393                            break;
2394                        }
2395                        c = fgetc(file_handle.handle.fp);
2396                        if (c == '#') {
2397                            while (c != '\n' && c != '\r' && c != EOF) {
2398                                c = fgetc(file_handle.handle.fp);   /* skip to end of line */
2399                            }
2400                            /* handle situations where line is terminated by \r\n */
2401                            if (c == '\r') {
2402                                if (fgetc(file_handle.handle.fp) != '\n') {
2403                                    long pos = ftell(file_handle.handle.fp);
2404                                    fseek(file_handle.handle.fp, pos - 1, SEEK_SET);
2405                                }
2406                            }
2407                            CG(start_lineno) = 2;
2408                        } else {
2409                            rewind(file_handle.handle.fp);
2410                        }
2411                        break;
2412                    case ZEND_HANDLE_STREAM:
2413                        c = php_stream_getc((php_stream*)file_handle.handle.stream.handle);
2414                        if (c == '#') {
2415                            while (c != '\n' && c != '\r' && c != EOF) {
2416                                c = php_stream_getc((php_stream*)file_handle.handle.stream.handle); /* skip to end of line */
2417                            }
2418                            /* handle situations where line is terminated by \r\n */
2419                            if (c == '\r') {
2420                                if (php_stream_getc((php_stream*)file_handle.handle.stream.handle) != '\n') {
2421                                    long pos = php_stream_tell((php_stream*)file_handle.handle.stream.handle);
2422                                    php_stream_seek((php_stream*)file_handle.handle.stream.handle, pos - 1, SEEK_SET);
2423                                }
2424                            }
2425                            CG(start_lineno) = 2;
2426                        } else {
2427                            php_stream_rewind((php_stream*)file_handle.handle.stream.handle);
2428                        }
2429                        break;
2430                    case ZEND_HANDLE_MAPPED:
2431                        if (file_handle.handle.stream.mmap.buf[0] == '#') {
2432                            int i = 1;
2433
2434                            c = file_handle.handle.stream.mmap.buf[i++];
2435                            while (c != '\n' && c != '\r' && c != EOF) {
2436                                c = file_handle.handle.stream.mmap.buf[i++];
2437                            }
2438                            if (c == '\r') {
2439                                if (file_handle.handle.stream.mmap.buf[i] == '\n') {
2440                                    i++;
2441                                }
2442                            }
2443                            file_handle.handle.stream.mmap.buf += i;
2444                            file_handle.handle.stream.mmap.len -= i;
2445                        }
2446                        break;
2447                    default:
2448                        break;
2449                }
2450            }
2451
2452            switch (behavior) {
2453                case PHP_MODE_STANDARD:
2454                    php_execute_script(&file_handle TSRMLS_CC);
2455                    break;
2456                case PHP_MODE_LINT:
2457                    PG(during_request_startup) = 0;
2458                    exit_status = php_lint_script(&file_handle TSRMLS_CC);
2459                    if (exit_status == SUCCESS) {
2460                        zend_printf("No syntax errors detected in %s\n", file_handle.filename);
2461                    } else {
2462                        zend_printf("Errors parsing %s\n", file_handle.filename);
2463                    }
2464                    break;
2465                case PHP_MODE_STRIP:
2466                    if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) {
2467                        zend_strip(TSRMLS_C);
2468                        zend_file_handle_dtor(&file_handle TSRMLS_CC);
2469                        php_output_teardown();
2470                    }
2471                    return SUCCESS;
2472                    break;
2473                case PHP_MODE_HIGHLIGHT:
2474                    {
2475                        zend_syntax_highlighter_ini syntax_highlighter_ini;
2476
2477                        if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) {
2478                            php_get_highlight_struct(&syntax_highlighter_ini);
2479                            zend_highlight(&syntax_highlighter_ini TSRMLS_CC);
2480                            if (fastcgi) {
2481                                goto fastcgi_request_done;
2482                            }
2483                            zend_file_handle_dtor(&file_handle TSRMLS_CC);
2484                            php_output_teardown();
2485                        }
2486                        return SUCCESS;
2487                    }
2488                    break;
2489#if 0
2490                /* Zeev might want to do something with this one day */
2491                case PHP_MODE_INDENT:
2492                    open_file_for_scanning(&file_handle TSRMLS_CC);
2493                    zend_indent();
2494                    zend_file_handle_dtor(&file_handle TSRMLS_CC);
2495                    php_output_teardown();
2496                    return SUCCESS;
2497                    break;
2498#endif
2499            }
2500
2501fastcgi_request_done:
2502            {
2503                STR_FREE(SG(request_info).path_translated);
2504
2505                php_request_shutdown((void *) 0);
2506
2507                if (exit_status == 0) {
2508                    exit_status = EG(exit_status);
2509                }
2510
2511                if (free_query_string && SG(request_info).query_string) {
2512                    free(SG(request_info).query_string);
2513                    SG(request_info).query_string = NULL;
2514                }
2515            }
2516
2517            if (!fastcgi) {
2518                if (benchmark) {
2519                    repeats--;
2520                    if (repeats > 0) {
2521                        script_file = NULL;
2522                        php_optind = orig_optind;
2523                        php_optarg = orig_optarg;
2524                        continue;
2525                    }
2526                }
2527                break;
2528            }
2529
2530            /* only fastcgi will get here */
2531            requests++;
2532            if (max_requests && (requests == max_requests)) {
2533                fcgi_finish_request(request, 1);
2534                if (bindpath) {
2535                    free(bindpath);
2536                }
2537                if (max_requests != 1) {
2538                    /* no need to return exit_status of the last request */
2539                    exit_status = 0;
2540                }
2541                break;
2542            }
2543            /* end of fastcgi loop */
2544        }
2545        if (request) {
2546            fcgi_destroy_request(request);
2547        }
2548        fcgi_shutdown();
2549
2550        if (cgi_sapi_module.php_ini_path_override) {
2551            free(cgi_sapi_module.php_ini_path_override);
2552        }
2553        if (cgi_sapi_module.ini_entries) {
2554            free(cgi_sapi_module.ini_entries);
2555        }
2556    } zend_catch {
2557        exit_status = 255;
2558    } zend_end_try();
2559
2560out:
2561    if (benchmark) {
2562        int sec;
2563#ifdef HAVE_GETTIMEOFDAY
2564        int usec;
2565
2566        gettimeofday(&end, NULL);
2567        sec = (int)(end.tv_sec - start.tv_sec);
2568        if (end.tv_usec >= start.tv_usec) {
2569            usec = (int)(end.tv_usec - start.tv_usec);
2570        } else {
2571            sec -= 1;
2572            usec = (int)(end.tv_usec + 1000000 - start.tv_usec);
2573        }
2574        fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec);
2575#else
2576        time(&end);
2577        sec = (int)(end - start);
2578        fprintf(stderr, "\nElapsed time: %d sec\n", sec);
2579#endif
2580    }
2581
2582#ifndef PHP_WIN32
2583parent_out:
2584#endif
2585
2586    SG(server_context) = NULL;
2587    php_module_shutdown(TSRMLS_C);
2588    sapi_shutdown();
2589
2590#ifdef ZTS
2591    tsrm_shutdown();
2592#endif
2593
2594#if defined(PHP_WIN32) && ZEND_DEBUG && 0
2595    _CrtDumpMemoryLeaks();
2596#endif
2597
2598    return exit_status;
2599}
2600/* }}} */
2601
2602/*
2603 * Local variables:
2604 * tab-width: 4
2605 * c-basic-offset: 4
2606 * End:
2607 * vim600: sw=4 ts=4 fdm=marker
2608 * vim<600: sw=4 ts=4
2609 */
2610