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