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