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    ((request->has_env) ? \
1040        FCGI_GETENV(request, name) : \
1041        getenv(name))
1042
1043#define CGI_PUTENV(name, value) \
1044    ((request->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    char *env_script_filename = CGI_GETENV("SCRIPT_FILENAME");
1117    char *env_path_translated = CGI_GETENV("PATH_TRANSLATED");
1118    char *script_path_translated = env_script_filename;
1119
1120    /* some broken servers do not have script_filename or argv0
1121     * an example, IIS configured in some ways.  then they do more
1122     * broken stuff and set path_translated to the cgi script location */
1123    if (!script_path_translated && env_path_translated) {
1124        script_path_translated = env_path_translated;
1125    }
1126
1127    /* initialize the defaults */
1128    SG(request_info).path_translated = NULL;
1129    SG(request_info).request_method = NULL;
1130    SG(request_info).proto_num = 1000;
1131    SG(request_info).query_string = NULL;
1132    SG(request_info).request_uri = NULL;
1133    SG(request_info).content_type = NULL;
1134    SG(request_info).content_length = 0;
1135    SG(sapi_headers).http_response_code = 200;
1136
1137    /* script_path_translated being set is a good indication that
1138     * we are running in a cgi environment, since it is always
1139     * null otherwise.  otherwise, the filename
1140     * of the script will be retreived later via argc/argv */
1141    if (script_path_translated) {
1142        const char *auth;
1143        char *content_length = CGI_GETENV("CONTENT_LENGTH");
1144        char *content_type = CGI_GETENV("CONTENT_TYPE");
1145        char *env_path_info = CGI_GETENV("PATH_INFO");
1146        char *env_script_name = CGI_GETENV("SCRIPT_NAME");
1147
1148#ifdef PHP_WIN32
1149        /* Hack for buggy IIS that sets incorrect PATH_INFO */
1150        char *env_server_software = CGI_GETENV("SERVER_SOFTWARE");
1151
1152        if (env_server_software &&
1153            env_script_name &&
1154            env_path_info &&
1155            strncmp(env_server_software, "Microsoft-IIS", sizeof("Microsoft-IIS")-1) == 0 &&
1156            strncmp(env_path_info, env_script_name, strlen(env_script_name)) == 0
1157        ) {
1158            env_path_info = CGI_PUTENV("ORIG_PATH_INFO", env_path_info);
1159            env_path_info += strlen(env_script_name);
1160            if (*env_path_info == 0) {
1161                env_path_info = NULL;
1162            }
1163            env_path_info = CGI_PUTENV("PATH_INFO", env_path_info);
1164        }
1165#endif
1166
1167        if (CGIG(fix_pathinfo)) {
1168            zend_stat_t st;
1169            char *real_path = NULL;
1170            char *env_redirect_url = CGI_GETENV("REDIRECT_URL");
1171            char *env_document_root = CGI_GETENV("DOCUMENT_ROOT");
1172            char *orig_path_translated = env_path_translated;
1173            char *orig_path_info = env_path_info;
1174            char *orig_script_name = env_script_name;
1175            char *orig_script_filename = env_script_filename;
1176            size_t script_path_translated_len;
1177
1178            if (!env_document_root && PG(doc_root)) {
1179                env_document_root = CGI_PUTENV("DOCUMENT_ROOT", PG(doc_root));
1180                /* fix docroot */
1181                TRANSLATE_SLASHES(env_document_root);
1182            }
1183
1184            if (env_path_translated != NULL && env_redirect_url != NULL &&
1185                env_path_translated != script_path_translated &&
1186                strcmp(env_path_translated, script_path_translated) != 0) {
1187                /*
1188                 * pretty much apache specific.  If we have a redirect_url
1189                 * then our script_filename and script_name point to the
1190                 * php executable
1191                 */
1192                script_path_translated = env_path_translated;
1193                /* we correct SCRIPT_NAME now in case we don't have PATH_INFO */
1194                env_script_name = env_redirect_url;
1195            }
1196
1197#ifdef __riscos__
1198            /* Convert path to unix format*/
1199            __riscosify_control |= __RISCOSIFY_DONT_CHECK_DIR;
1200            script_path_translated = __unixify(script_path_translated, 0, NULL, 1, 0);
1201#endif
1202
1203            /*
1204             * if the file doesn't exist, try to extract PATH_INFO out
1205             * of it by stat'ing back through the '/'
1206             * this fixes url's like /info.php/test
1207             */
1208            if (script_path_translated &&
1209                (script_path_translated_len = strlen(script_path_translated)) > 0 &&
1210                (script_path_translated[script_path_translated_len-1] == '/' ||
1211#ifdef PHP_WIN32
1212                script_path_translated[script_path_translated_len-1] == '\\' ||
1213#endif
1214                (real_path = tsrm_realpath(script_path_translated, NULL)) == NULL)
1215            ) {
1216                char *pt = estrndup(script_path_translated, script_path_translated_len);
1217                size_t len = script_path_translated_len;
1218                char *ptr;
1219
1220                while ((ptr = strrchr(pt, '/')) || (ptr = strrchr(pt, '\\'))) {
1221                    *ptr = 0;
1222                    if (zend_stat(pt, &st) == 0 && S_ISREG(st.st_mode)) {
1223                        /*
1224                         * okay, we found the base script!
1225                         * work out how many chars we had to strip off;
1226                         * then we can modify PATH_INFO
1227                         * accordingly
1228                         *
1229                         * we now have the makings of
1230                         * PATH_INFO=/test
1231                         * SCRIPT_FILENAME=/docroot/info.php
1232                         *
1233                         * we now need to figure out what docroot is.
1234                         * if DOCUMENT_ROOT is set, this is easy, otherwise,
1235                         * we have to play the game of hide and seek to figure
1236                         * out what SCRIPT_NAME should be
1237                         */
1238                        size_t slen = len - strlen(pt);
1239                        size_t pilen = env_path_info ? strlen(env_path_info) : 0;
1240                        char *path_info = env_path_info ? env_path_info + pilen - slen : NULL;
1241
1242                        if (orig_path_info != path_info) {
1243                            if (orig_path_info) {
1244                                char old;
1245
1246                                CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
1247                                old = path_info[0];
1248                                path_info[0] = 0;
1249                                if (!orig_script_name ||
1250                                    strcmp(orig_script_name, env_path_info) != 0) {
1251                                    if (orig_script_name) {
1252                                        CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1253                                    }
1254                                    SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_path_info);
1255                                } else {
1256                                    SG(request_info).request_uri = orig_script_name;
1257                                }
1258                                path_info[0] = old;
1259                            }
1260                            env_path_info = CGI_PUTENV("PATH_INFO", path_info);
1261                        }
1262                        if (!orig_script_filename ||
1263                            strcmp(orig_script_filename, pt) != 0) {
1264                            if (orig_script_filename) {
1265                                CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1266                            }
1267                            script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", pt);
1268                        }
1269                        TRANSLATE_SLASHES(pt);
1270
1271                        /* figure out docroot
1272                         * SCRIPT_FILENAME minus SCRIPT_NAME
1273                         */
1274                        if (env_document_root) {
1275                            size_t l = strlen(env_document_root);
1276                            size_t path_translated_len = 0;
1277                            char *path_translated = NULL;
1278
1279                            if (l && env_document_root[l - 1] == '/') {
1280                                --l;
1281                            }
1282
1283                            /* we have docroot, so we should have:
1284                             * DOCUMENT_ROOT=/docroot
1285                             * SCRIPT_FILENAME=/docroot/info.php
1286                             */
1287
1288                            /* PATH_TRANSLATED = DOCUMENT_ROOT + PATH_INFO */
1289                            path_translated_len = l + (env_path_info ? strlen(env_path_info) : 0);
1290                            path_translated = (char *) emalloc(path_translated_len + 1);
1291                            memcpy(path_translated, env_document_root, l);
1292                            if (env_path_info) {
1293                                memcpy(path_translated + l, env_path_info, (path_translated_len - l));
1294                            }
1295                            path_translated[path_translated_len] = '\0';
1296                            if (orig_path_translated) {
1297                                CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1298                            }
1299                            env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
1300                            efree(path_translated);
1301                        } else if ( env_script_name &&
1302                                    strstr(pt, env_script_name)
1303                        ) {
1304                            /* PATH_TRANSLATED = PATH_TRANSLATED - SCRIPT_NAME + PATH_INFO */
1305                            size_t ptlen = strlen(pt) - strlen(env_script_name);
1306                            size_t path_translated_len = ptlen + (env_path_info ? strlen(env_path_info) : 0);
1307                            char *path_translated = NULL;
1308
1309                            path_translated = (char *) emalloc(path_translated_len + 1);
1310                            memcpy(path_translated, pt, ptlen);
1311                            if (env_path_info) {
1312                                memcpy(path_translated + ptlen, env_path_info, path_translated_len - ptlen);
1313                            }
1314                            path_translated[path_translated_len] = '\0';
1315                            if (orig_path_translated) {
1316                                CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1317                            }
1318                            env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
1319                            efree(path_translated);
1320                        }
1321                        break;
1322                    }
1323                }
1324                if (!ptr) {
1325                    /*
1326                     * if we stripped out all the '/' and still didn't find
1327                     * a valid path... we will fail, badly. of course we would
1328                     * have failed anyway... we output 'no input file' now.
1329                     */
1330                    if (orig_script_filename) {
1331                        CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1332                    }
1333                    script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", NULL);
1334                    SG(sapi_headers).http_response_code = 404;
1335                }
1336                if (!SG(request_info).request_uri) {
1337                    if (!orig_script_name ||
1338                        strcmp(orig_script_name, env_script_name) != 0) {
1339                        if (orig_script_name) {
1340                            CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1341                        }
1342                        SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
1343                    } else {
1344                        SG(request_info).request_uri = orig_script_name;
1345                    }
1346                }
1347                if (pt) {
1348                    efree(pt);
1349                }
1350            } else {
1351                /* make sure path_info/translated are empty */
1352                if (!orig_script_filename ||
1353                    (script_path_translated != orig_script_filename &&
1354                    strcmp(script_path_translated, orig_script_filename) != 0)) {
1355                    if (orig_script_filename) {
1356                        CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1357                    }
1358                    script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", script_path_translated);
1359                }
1360                if (env_redirect_url) {
1361                    if (orig_path_info) {
1362                        CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
1363                        CGI_PUTENV("PATH_INFO", NULL);
1364                    }
1365                    if (orig_path_translated) {
1366                        CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1367                        CGI_PUTENV("PATH_TRANSLATED", NULL);
1368                    }
1369                }
1370                if (env_script_name != orig_script_name) {
1371                    if (orig_script_name) {
1372                        CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1373                    }
1374                    SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
1375                } else {
1376                    SG(request_info).request_uri = env_script_name;
1377                }
1378                efree(real_path);
1379            }
1380        } else {
1381            /* pre 4.3 behaviour, shouldn't be used but provides BC */
1382            if (env_path_info) {
1383                SG(request_info).request_uri = env_path_info;
1384            } else {
1385                SG(request_info).request_uri = env_script_name;
1386            }
1387            if (!CGIG(discard_path) && env_path_translated) {
1388                script_path_translated = env_path_translated;
1389            }
1390        }
1391
1392        if (is_valid_path(script_path_translated)) {
1393            SG(request_info).path_translated = estrdup(script_path_translated);
1394        }
1395
1396        SG(request_info).request_method = CGI_GETENV("REQUEST_METHOD");
1397        /* FIXME - Work out proto_num here */
1398        SG(request_info).query_string = CGI_GETENV("QUERY_STRING");
1399        SG(request_info).content_type = (content_type ? content_type : "" );
1400        SG(request_info).content_length = (content_length ? atol(content_length) : 0);
1401
1402        /* The CGI RFC allows servers to pass on unvalidated Authorization data */
1403        auth = CGI_GETENV("HTTP_AUTHORIZATION");
1404        php_handle_auth_data(auth);
1405    }
1406}
1407/* }}} */
1408
1409#ifndef PHP_WIN32
1410/**
1411 * Clean up child processes upon exit
1412 */
1413void fastcgi_cleanup(int signal)
1414{
1415#ifdef DEBUG_FASTCGI
1416    fprintf(stderr, "FastCGI shutdown, pid %d\n", getpid());
1417#endif
1418
1419    sigaction(SIGTERM, &old_term, 0);
1420
1421    /* Kill all the processes in our process group */
1422    kill(-pgroup, SIGTERM);
1423
1424    if (parent && parent_waiting) {
1425        exit_signal = 1;
1426    } else {
1427        exit(0);
1428    }
1429}
1430#endif
1431
1432PHP_INI_BEGIN()
1433    STD_PHP_INI_ENTRY("cgi.rfc2616_headers",     "0",  PHP_INI_ALL,    OnUpdateBool,   rfc2616_headers, php_cgi_globals_struct, php_cgi_globals)
1434    STD_PHP_INI_ENTRY("cgi.nph",                 "0",  PHP_INI_ALL,    OnUpdateBool,   nph, php_cgi_globals_struct, php_cgi_globals)
1435    STD_PHP_INI_ENTRY("cgi.check_shebang_line",  "1",  PHP_INI_SYSTEM, OnUpdateBool,   check_shebang_line, php_cgi_globals_struct, php_cgi_globals)
1436    STD_PHP_INI_ENTRY("cgi.force_redirect",      "1",  PHP_INI_SYSTEM, OnUpdateBool,   force_redirect, php_cgi_globals_struct, php_cgi_globals)
1437    STD_PHP_INI_ENTRY("cgi.redirect_status_env", NULL, PHP_INI_SYSTEM, OnUpdateString, redirect_status_env, php_cgi_globals_struct, php_cgi_globals)
1438    STD_PHP_INI_ENTRY("cgi.fix_pathinfo",        "1",  PHP_INI_SYSTEM, OnUpdateBool,   fix_pathinfo, php_cgi_globals_struct, php_cgi_globals)
1439    STD_PHP_INI_ENTRY("cgi.discard_path",        "0",  PHP_INI_SYSTEM, OnUpdateBool,   discard_path, php_cgi_globals_struct, php_cgi_globals)
1440    STD_PHP_INI_ENTRY("fastcgi.logging",         "1",  PHP_INI_SYSTEM, OnUpdateBool,   fcgi_logging, php_cgi_globals_struct, php_cgi_globals)
1441#ifdef PHP_WIN32
1442    STD_PHP_INI_ENTRY("fastcgi.impersonate",     "0",  PHP_INI_SYSTEM, OnUpdateBool,   impersonate, php_cgi_globals_struct, php_cgi_globals)
1443#endif
1444PHP_INI_END()
1445
1446/* {{{ php_cgi_globals_ctor
1447 */
1448static void php_cgi_globals_ctor(php_cgi_globals_struct *php_cgi_globals)
1449{
1450#ifdef ZTS
1451    ZEND_TSRMLS_CACHE_UPDATE();
1452#endif
1453    php_cgi_globals->rfc2616_headers = 0;
1454    php_cgi_globals->nph = 0;
1455    php_cgi_globals->check_shebang_line = 1;
1456    php_cgi_globals->force_redirect = 1;
1457    php_cgi_globals->redirect_status_env = NULL;
1458    php_cgi_globals->fix_pathinfo = 1;
1459    php_cgi_globals->discard_path = 0;
1460    php_cgi_globals->fcgi_logging = 1;
1461#ifdef PHP_WIN32
1462    php_cgi_globals->impersonate = 0;
1463#endif
1464    zend_hash_init(&php_cgi_globals->user_config_cache, 8, NULL, user_config_cache_entry_dtor, 1);
1465}
1466/* }}} */
1467
1468/* {{{ PHP_MINIT_FUNCTION
1469 */
1470static PHP_MINIT_FUNCTION(cgi)
1471{
1472#ifdef ZTS
1473    ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
1474#else
1475    php_cgi_globals_ctor(&php_cgi_globals);
1476#endif
1477    REGISTER_INI_ENTRIES();
1478    return SUCCESS;
1479}
1480/* }}} */
1481
1482/* {{{ PHP_MSHUTDOWN_FUNCTION
1483 */
1484static PHP_MSHUTDOWN_FUNCTION(cgi)
1485{
1486    zend_hash_destroy(&CGIG(user_config_cache));
1487
1488    UNREGISTER_INI_ENTRIES();
1489    return SUCCESS;
1490}
1491/* }}} */
1492
1493/* {{{ PHP_MINFO_FUNCTION
1494 */
1495static PHP_MINFO_FUNCTION(cgi)
1496{
1497    DISPLAY_INI_ENTRIES();
1498}
1499/* }}} */
1500
1501PHP_FUNCTION(apache_child_terminate) /* {{{ */
1502{
1503    if (ZEND_NUM_ARGS() > 0) {
1504        WRONG_PARAM_COUNT;
1505    }
1506    if (fcgi_is_fastcgi()) {
1507        fcgi_terminate();
1508    }
1509}
1510/* }}} */
1511
1512static void add_request_header(char *var, unsigned int var_len, char *val, unsigned int val_len, void *arg) /* {{{ */
1513{
1514    zval *return_value = (zval*)arg;
1515    char *str = NULL;
1516    char *p;
1517    ALLOCA_FLAG(use_heap)
1518
1519    if (var_len > 5 &&
1520        var[0] == 'H' &&
1521        var[1] == 'T' &&
1522        var[2] == 'T' &&
1523        var[3] == 'P' &&
1524        var[4] == '_') {
1525
1526        var_len -= 5;
1527        p = var + 5;
1528        var = str = do_alloca(var_len + 1, use_heap);
1529        *str++ = *p++;
1530        while (*p) {
1531            if (*p == '_') {
1532                *str++ = '-';
1533                p++;
1534                if (*p) {
1535                    *str++ = *p++;
1536                }
1537            } else if (*p >= 'A' && *p <= 'Z') {
1538                *str++ = (*p++ - 'A' + 'a');
1539            } else {
1540                *str++ = *p++;
1541            }
1542        }
1543        *str = 0;
1544    } else if (var_len == sizeof("CONTENT_TYPE")-1 &&
1545               memcmp(var, "CONTENT_TYPE", sizeof("CONTENT_TYPE")-1) == 0) {
1546        var = "Content-Type";
1547    } else if (var_len == sizeof("CONTENT_LENGTH")-1 &&
1548               memcmp(var, "CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1) == 0) {
1549        var = "Content-Length";
1550    } else {
1551        return;
1552    }
1553    add_assoc_stringl_ex(return_value, var, var_len+1, val, val_len);
1554    if (str) {
1555        free_alloca(var, use_heap);
1556    }
1557}
1558/* }}} */
1559
1560PHP_FUNCTION(apache_request_headers) /* {{{ */
1561{
1562    if (ZEND_NUM_ARGS() > 0) {
1563        WRONG_PARAM_COUNT;
1564    }
1565    array_init(return_value);
1566    if (fcgi_is_fastcgi()) {
1567        fcgi_request *request = (fcgi_request*) SG(server_context);
1568
1569        fcgi_loadenv(request, add_request_header, return_value);
1570    } else {
1571        char buf[128];
1572        char **env, *p, *q, *var, *val, *t = buf;
1573        size_t alloc_size = sizeof(buf);
1574        zend_ulong var_len;
1575
1576        for (env = environ; env != NULL && *env != NULL; env++) {
1577            val = strchr(*env, '=');
1578            if (!val) {             /* malformed entry? */
1579                continue;
1580            }
1581            var_len = val - *env;
1582            if (var_len >= alloc_size) {
1583                alloc_size = var_len + 64;
1584                t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
1585            }
1586            var = *env;
1587            if (var_len > 5 &&
1588                var[0] == 'H' &&
1589                var[1] == 'T' &&
1590                var[2] == 'T' &&
1591                var[3] == 'P' &&
1592                var[4] == '_') {
1593
1594                var_len -= 5;
1595
1596                if (var_len >= alloc_size) {
1597                    alloc_size = var_len + 64;
1598                    t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
1599                }
1600                p = var + 5;
1601
1602                var = q = t;
1603                /* First char keep uppercase */
1604                *q++ = *p++;
1605                while (*p) {
1606                    if (*p == '=') {
1607                        /* End of name */
1608                        break;
1609                    } else if (*p == '_') {
1610                        *q++ = '-';
1611                        p++;
1612                        /* First char after - keep uppercase */
1613                        if (*p && *p!='=') {
1614                            *q++ = *p++;
1615                        }
1616                    } else if (*p >= 'A' && *p <= 'Z') {
1617                        /* lowercase */
1618                        *q++ = (*p++ - 'A' + 'a');
1619                    } else {
1620                        *q++ = *p++;
1621                    }
1622                }
1623                *q = 0;
1624            } else if (var_len == sizeof("CONTENT_TYPE")-1 &&
1625                       memcmp(var, "CONTENT_TYPE", sizeof("CONTENT_TYPE")-1) == 0) {
1626                var = "Content-Type";
1627            } else if (var_len == sizeof("CONTENT_LENGTH")-1 &&
1628                       memcmp(var, "CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1) == 0) {
1629                var = "Content-Length";
1630            } else {
1631                continue;
1632            }
1633            val++;
1634            add_assoc_string_ex(return_value, var, var_len, val);
1635        }
1636        if (t != buf && t != NULL) {
1637            efree(t);
1638        }
1639    }
1640}
1641/* }}} */
1642
1643static void add_response_header(sapi_header_struct *h, zval *return_value) /* {{{ */
1644{
1645    char *s, *p;
1646    size_t len = 0;
1647    ALLOCA_FLAG(use_heap)
1648
1649    if (h->header_len > 0) {
1650        p = strchr(h->header, ':');
1651        if (NULL != p) {
1652            len = p - h->header;
1653        }
1654        if (len > 0) {
1655            do {
1656                len--;
1657            } while (len != 0 && (h->header[len-1] == ' ' || h->header[len-1] == '\t'));
1658            if (len) {
1659                s = do_alloca(len + 1, use_heap);
1660                memcpy(s, h->header, len);
1661                s[len] = 0;
1662                do {
1663                    p++;
1664                } while (*p == ' ' || *p == '\t');
1665                add_assoc_stringl_ex(return_value, s, len, p, h->header_len - (p - h->header));
1666                free_alloca(s, use_heap);
1667            }
1668        }
1669    }
1670}
1671/* }}} */
1672
1673PHP_FUNCTION(apache_response_headers) /* {{{ */
1674{
1675    if (zend_parse_parameters_none() == FAILURE) {
1676        return;
1677    }
1678
1679    array_init(return_value);
1680    zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t)add_response_header, return_value);
1681}
1682/* }}} */
1683
1684ZEND_BEGIN_ARG_INFO(arginfo_no_args, 0)
1685ZEND_END_ARG_INFO()
1686
1687const zend_function_entry cgi_functions[] = {
1688    PHP_FE(apache_child_terminate, arginfo_no_args)
1689    PHP_FE(apache_request_headers, arginfo_no_args)
1690    PHP_FE(apache_response_headers, arginfo_no_args)
1691    PHP_FALIAS(getallheaders, apache_request_headers, arginfo_no_args)
1692    {NULL, NULL, NULL}
1693};
1694
1695static zend_module_entry cgi_module_entry = {
1696    STANDARD_MODULE_HEADER,
1697    "cgi-fcgi",
1698    cgi_functions,
1699    PHP_MINIT(cgi),
1700    PHP_MSHUTDOWN(cgi),
1701    NULL,
1702    NULL,
1703    PHP_MINFO(cgi),
1704    NO_VERSION_YET,
1705    STANDARD_MODULE_PROPERTIES
1706};
1707
1708/* {{{ main
1709 */
1710int main(int argc, char *argv[])
1711{
1712    int free_query_string = 0;
1713    int exit_status = SUCCESS;
1714    int cgi = 0, c, i;
1715    size_t len;
1716    zend_file_handle file_handle;
1717    char *s;
1718
1719    /* temporary locals */
1720    int behavior = PHP_MODE_STANDARD;
1721    int no_headers = 0;
1722    int orig_optind = php_optind;
1723    char *orig_optarg = php_optarg;
1724    char *script_file = NULL;
1725    size_t ini_entries_len = 0;
1726    /* end of temporary locals */
1727
1728#ifdef ZTS
1729    void ***tsrm_ls;
1730#endif
1731
1732    int max_requests = 500;
1733    int requests = 0;
1734    int fastcgi;
1735    char *bindpath = NULL;
1736    int fcgi_fd = 0;
1737    fcgi_request request = {0};
1738    int warmup_repeats = 0;
1739    int repeats = 1;
1740    int benchmark = 0;
1741#if HAVE_GETTIMEOFDAY
1742    struct timeval start, end;
1743#else
1744    time_t start, end;
1745#endif
1746#ifndef PHP_WIN32
1747    int status = 0;
1748#endif
1749    char *query_string;
1750    char *decoded_query_string;
1751    int skip_getopt = 0;
1752
1753#if 0 && defined(PHP_DEBUG)
1754    /* IIS is always making things more difficult.  This allows
1755     * us to stop PHP and attach a debugger before much gets started */
1756    {
1757        char szMessage [256];
1758        wsprintf (szMessage, "Please attach a debugger to the process 0x%X [%d] (%s) and click OK", GetCurrentProcessId(), GetCurrentProcessId(), argv[0]);
1759        MessageBox(NULL, szMessage, "CGI Debug Time!", MB_OK|MB_SERVICE_NOTIFICATION);
1760    }
1761#endif
1762
1763#ifdef HAVE_SIGNAL_H
1764#if defined(SIGPIPE) && defined(SIG_IGN)
1765    signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
1766                                that sockets created via fsockopen()
1767                                don't kill PHP if the remote site
1768                                closes it.  in apache|apxs mode apache
1769                                does that for us!  thies@thieso.net
1770                                20000419 */
1771#endif
1772#endif
1773
1774#ifdef ZTS
1775    tsrm_startup(1, 1, 0, NULL);
1776    tsrm_ls = ts_resource(0);
1777    ZEND_TSRMLS_CACHE_UPDATE();
1778#endif
1779
1780    sapi_startup(&cgi_sapi_module);
1781    fastcgi = fcgi_is_fastcgi();
1782    cgi_sapi_module.php_ini_path_override = NULL;
1783
1784#ifdef PHP_WIN32
1785    _fmode = _O_BINARY; /* sets default for file streams to binary */
1786    setmode(_fileno(stdin),  O_BINARY); /* make the stdio mode be binary */
1787    setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */
1788    setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */
1789#endif
1790
1791    if (!fastcgi) {
1792        /* Make sure we detect we are a cgi - a bit redundancy here,
1793         * but the default case is that we have to check only the first one. */
1794        if (getenv("SERVER_SOFTWARE") ||
1795            getenv("SERVER_NAME") ||
1796            getenv("GATEWAY_INTERFACE") ||
1797            getenv("REQUEST_METHOD")
1798        ) {
1799            cgi = 1;
1800        }
1801    }
1802
1803    if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) {
1804        /* we've got query string that has no = - apache CGI will pass it to command line */
1805        unsigned char *p;
1806        decoded_query_string = strdup(query_string);
1807        php_url_decode(decoded_query_string, strlen(decoded_query_string));
1808        for (p = (unsigned char *)decoded_query_string; *p &&  *p <= ' '; p++) {
1809            /* skip all leading spaces */
1810        }
1811        if(*p == '-') {
1812            skip_getopt = 1;
1813        }
1814        free(decoded_query_string);
1815    }
1816
1817    while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
1818        switch (c) {
1819            case 'c':
1820                if (cgi_sapi_module.php_ini_path_override) {
1821                    free(cgi_sapi_module.php_ini_path_override);
1822                }
1823                cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
1824                break;
1825            case 'n':
1826                cgi_sapi_module.php_ini_ignore = 1;
1827                break;
1828            case 'd': {
1829                /* define ini entries on command line */
1830                size_t len = strlen(php_optarg);
1831                char *val;
1832
1833                if ((val = strchr(php_optarg, '='))) {
1834                    val++;
1835                    if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
1836                        cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
1837                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
1838                        ini_entries_len += (val - php_optarg);
1839                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1);
1840                        ini_entries_len++;
1841                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
1842                        ini_entries_len += len - (val - php_optarg);
1843                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
1844                        ini_entries_len += sizeof("\n\0\"") - 2;
1845                    } else {
1846                        cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
1847                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
1848                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
1849                        ini_entries_len += len + sizeof("\n\0") - 2;
1850                    }
1851                } else {
1852                    cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
1853                    memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
1854                    memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
1855                    ini_entries_len += len + sizeof("=1\n\0") - 2;
1856                }
1857                break;
1858            }
1859            /* if we're started on command line, check to see if
1860             * we are being started as an 'external' fastcgi
1861             * server by accepting a bindpath parameter. */
1862            case 'b':
1863                if (!fastcgi) {
1864                    bindpath = strdup(php_optarg);
1865                }
1866                break;
1867            case 's': /* generate highlighted HTML from source */
1868                behavior = PHP_MODE_HIGHLIGHT;
1869                break;
1870        }
1871    }
1872    php_optind = orig_optind;
1873    php_optarg = orig_optarg;
1874
1875    if (fastcgi || bindpath) {
1876        /* Override SAPI callbacks */
1877        cgi_sapi_module.ub_write     = sapi_fcgi_ub_write;
1878        cgi_sapi_module.flush        = sapi_fcgi_flush;
1879        cgi_sapi_module.read_post    = sapi_fcgi_read_post;
1880        cgi_sapi_module.getenv       = sapi_fcgi_getenv;
1881        cgi_sapi_module.read_cookies = sapi_fcgi_read_cookies;
1882    }
1883
1884#ifdef ZTS
1885    SG(request_info).path_translated = NULL;
1886#endif
1887
1888    cgi_sapi_module.executable_location = argv[0];
1889    if (!cgi && !fastcgi && !bindpath) {
1890        cgi_sapi_module.additional_functions = additional_functions;
1891    }
1892
1893    /* startup after we get the above ini override se we get things right */
1894    if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
1895#ifdef ZTS
1896        tsrm_shutdown();
1897#endif
1898        return FAILURE;
1899    }
1900
1901    /* check force_cgi after startup, so we have proper output */
1902    if (cgi && CGIG(force_redirect)) {
1903        /* Apache will generate REDIRECT_STATUS,
1904         * Netscape and redirect.so will generate HTTP_REDIRECT_STATUS.
1905         * redirect.so and installation instructions available from
1906         * http://www.koehntopp.de/php.
1907         *   -- kk@netuse.de
1908         */
1909        if (!getenv("REDIRECT_STATUS") &&
1910            !getenv ("HTTP_REDIRECT_STATUS") &&
1911            /* this is to allow a different env var to be configured
1912             * in case some server does something different than above */
1913            (!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env)))
1914        ) {
1915            zend_try {
1916                SG(sapi_headers).http_response_code = 400;
1917                PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
1918<p>This PHP CGI binary was compiled with force-cgi-redirect enabled.  This\n\
1919means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
1920set, e.g. via an Apache Action directive.</p>\n\
1921<p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
1922manual page for CGI security</a>.</p>\n\
1923<p>For more information about changing this behaviour or re-enabling this webserver,\n\
1924consult the installation file that came with this distribution, or visit \n\
1925<a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
1926            } zend_catch {
1927            } zend_end_try();
1928#if defined(ZTS) && !defined(PHP_DEBUG)
1929            /* XXX we're crashing here in msvc6 debug builds at
1930             * php_message_handler_for_zend:839 because
1931             * SG(request_info).path_translated is an invalid pointer.
1932             * It still happens even though I set it to null, so something
1933             * weird is going on.
1934             */
1935            tsrm_shutdown();
1936#endif
1937            return FAILURE;
1938        }
1939    }
1940
1941#ifndef HAVE_ATTRIBUTE_WEAK
1942    fcgi_set_logger(fcgi_log);
1943#endif
1944
1945    if (bindpath) {
1946        int backlog = 128;
1947        if (getenv("PHP_FCGI_BACKLOG")) {
1948            backlog = atoi(getenv("PHP_FCGI_BACKLOG"));
1949        }
1950        fcgi_fd = fcgi_listen(bindpath, backlog);
1951        if (fcgi_fd < 0) {
1952            fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath);
1953#ifdef ZTS
1954            tsrm_shutdown();
1955#endif
1956            return FAILURE;
1957        }
1958        fastcgi = fcgi_is_fastcgi();
1959    }
1960    if (fastcgi) {
1961        /* How many times to run PHP scripts before dying */
1962        if (getenv("PHP_FCGI_MAX_REQUESTS")) {
1963            max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS"));
1964            if (max_requests < 0) {
1965                fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n");
1966                return FAILURE;
1967            }
1968        }
1969
1970        /* make php call us to get _ENV vars */
1971        php_php_import_environment_variables = php_import_environment_variables;
1972        php_import_environment_variables = cgi_php_import_environment_variables;
1973
1974        /* library is already initialized, now init our request */
1975        fcgi_init_request(&request, fcgi_fd);
1976
1977#ifndef PHP_WIN32
1978        /* Pre-fork, if required */
1979        if (getenv("PHP_FCGI_CHILDREN")) {
1980            char * children_str = getenv("PHP_FCGI_CHILDREN");
1981            children = atoi(children_str);
1982            if (children < 0) {
1983                fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n");
1984                return FAILURE;
1985            }
1986            fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str));
1987            /* This is the number of concurrent requests, equals FCGI_MAX_CONNS */
1988            fcgi_set_mgmt_var("FCGI_MAX_REQS",  sizeof("FCGI_MAX_REQS")-1,  children_str, strlen(children_str));
1989        } else {
1990            fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1);
1991            fcgi_set_mgmt_var("FCGI_MAX_REQS",  sizeof("FCGI_MAX_REQS")-1,  "1", sizeof("1")-1);
1992        }
1993
1994        if (children) {
1995            int running = 0;
1996            pid_t pid;
1997
1998            /* Create a process group for ourself & children */
1999            setsid();
2000            pgroup = getpgrp();
2001#ifdef DEBUG_FASTCGI
2002            fprintf(stderr, "Process group %d\n", pgroup);
2003#endif
2004
2005            /* Set up handler to kill children upon exit */
2006            act.sa_flags = 0;
2007            act.sa_handler = fastcgi_cleanup;
2008            if (sigaction(SIGTERM, &act, &old_term) ||
2009                sigaction(SIGINT,  &act, &old_int)  ||
2010                sigaction(SIGQUIT, &act, &old_quit)
2011            ) {
2012                perror("Can't set signals");
2013                exit(1);
2014            }
2015
2016            if (fcgi_in_shutdown()) {
2017                goto parent_out;
2018            }
2019
2020            while (parent) {
2021                do {
2022#ifdef DEBUG_FASTCGI
2023                    fprintf(stderr, "Forking, %d running\n", running);
2024#endif
2025                    pid = fork();
2026                    switch (pid) {
2027                    case 0:
2028                        /* One of the children.
2029                         * Make sure we don't go round the
2030                         * fork loop any more
2031                         */
2032                        parent = 0;
2033
2034                        /* don't catch our signals */
2035                        sigaction(SIGTERM, &old_term, 0);
2036                        sigaction(SIGQUIT, &old_quit, 0);
2037                        sigaction(SIGINT,  &old_int,  0);
2038                        break;
2039                    case -1:
2040                        perror("php (pre-forking)");
2041                        exit(1);
2042                        break;
2043                    default:
2044                        /* Fine */
2045                        running++;
2046                        break;
2047                    }
2048                } while (parent && (running < children));
2049
2050                if (parent) {
2051#ifdef DEBUG_FASTCGI
2052                    fprintf(stderr, "Wait for kids, pid %d\n", getpid());
2053#endif
2054                    parent_waiting = 1;
2055                    while (1) {
2056                        if (wait(&status) >= 0) {
2057                            running--;
2058                            break;
2059                        } else if (exit_signal) {
2060                            break;
2061                        }
2062                    }
2063                    if (exit_signal) {
2064#if 0
2065                        while (running > 0) {
2066                            while (wait(&status) < 0) {
2067                            }
2068                            running--;
2069                        }
2070#endif
2071                        goto parent_out;
2072                    }
2073                }
2074            }
2075        } else {
2076            parent = 0;
2077        }
2078
2079#endif /* WIN32 */
2080    }
2081
2082    zend_first_try {
2083        while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) {
2084            switch (c) {
2085                case 'T':
2086                    benchmark = 1;
2087                    {
2088                        char *comma = strchr(php_optarg, ',');
2089                        if (comma) {
2090                            warmup_repeats = atoi(php_optarg);
2091                            repeats = atoi(comma + 1);
2092                        } else {
2093                            repeats = atoi(php_optarg);
2094                        }
2095                    }
2096#ifdef HAVE_GETTIMEOFDAY
2097                    gettimeofday(&start, NULL);
2098#else
2099                    time(&start);
2100#endif
2101                    break;
2102                case 'h':
2103                case '?':
2104                    if (request.listen_socket) {
2105                        fcgi_destroy_request(&request);
2106                    }
2107                    fcgi_shutdown();
2108                    no_headers = 1;
2109                    SG(headers_sent) = 1;
2110                    php_cgi_usage(argv[0]);
2111                    php_output_end_all();
2112                    exit_status = 0;
2113                    goto out;
2114            }
2115        }
2116        php_optind = orig_optind;
2117        php_optarg = orig_optarg;
2118
2119        /* start of FAST CGI loop */
2120        /* Initialise FastCGI request structure */
2121#ifdef PHP_WIN32
2122        /* attempt to set security impersonation for fastcgi
2123         * will only happen on NT based OS, others will ignore it. */
2124        if (fastcgi && CGIG(impersonate)) {
2125            fcgi_impersonate();
2126        }
2127#endif
2128        while (!fastcgi || fcgi_accept_request(&request) >= 0) {
2129            SG(server_context) = fastcgi ? (void *)&request : (void *) 1;
2130            init_request_info(&request);
2131
2132            if (!cgi && !fastcgi) {
2133                while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
2134                    switch (c) {
2135
2136                        case 'a':   /* interactive mode */
2137                            printf("Interactive mode enabled\n\n");
2138                            break;
2139
2140                        case 'C': /* don't chdir to the script directory */
2141                            SG(options) |= SAPI_OPTION_NO_CHDIR;
2142                            break;
2143
2144                        case 'e': /* enable extended info output */
2145                            CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
2146                            break;
2147
2148                        case 'f': /* parse file */
2149                            if (script_file) {
2150                                efree(script_file);
2151                            }
2152                            script_file = estrdup(php_optarg);
2153                            no_headers = 1;
2154                            break;
2155
2156                        case 'i': /* php info & quit */
2157                            if (script_file) {
2158                                efree(script_file);
2159                            }
2160                            if (php_request_startup() == FAILURE) {
2161                                SG(server_context) = NULL;
2162                                php_module_shutdown();
2163                                return FAILURE;
2164                            }
2165                            if (no_headers) {
2166                                SG(headers_sent) = 1;
2167                                SG(request_info).no_headers = 1;
2168                            }
2169                            php_print_info(0xFFFFFFFF);
2170                            php_request_shutdown((void *) 0);
2171                            fcgi_shutdown();
2172                            exit_status = 0;
2173                            goto out;
2174
2175                        case 'l': /* syntax check mode */
2176                            no_headers = 1;
2177                            behavior = PHP_MODE_LINT;
2178                            break;
2179
2180                        case 'm': /* list compiled in modules */
2181                            if (script_file) {
2182                                efree(script_file);
2183                            }
2184                            SG(headers_sent) = 1;
2185                            php_printf("[PHP Modules]\n");
2186                            print_modules();
2187                            php_printf("\n[Zend Modules]\n");
2188                            print_extensions();
2189                            php_printf("\n");
2190                            php_output_end_all();
2191                            fcgi_shutdown();
2192                            exit_status = 0;
2193                            goto out;
2194
2195                        case 'q': /* do not generate HTTP headers */
2196                            no_headers = 1;
2197                            break;
2198
2199                        case 'v': /* show php version & quit */
2200                            if (script_file) {
2201                                efree(script_file);
2202                            }
2203                            no_headers = 1;
2204                            if (php_request_startup() == FAILURE) {
2205                                SG(server_context) = NULL;
2206                                php_module_shutdown();
2207                                return FAILURE;
2208                            }
2209                            if (no_headers) {
2210                                SG(headers_sent) = 1;
2211                                SG(request_info).no_headers = 1;
2212                            }
2213#if ZEND_DEBUG
2214                            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());
2215#else
2216                            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());
2217#endif
2218                            php_request_shutdown((void *) 0);
2219                            fcgi_shutdown();
2220                            exit_status = 0;
2221                            goto out;
2222
2223                        case 'w':
2224                            behavior = PHP_MODE_STRIP;
2225                            break;
2226
2227                        case 'z': /* load extension file */
2228                            zend_load_extension(php_optarg);
2229                            break;
2230
2231                        default:
2232                            break;
2233                    }
2234                }
2235
2236                if (script_file) {
2237                    /* override path_translated if -f on command line */
2238                    if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2239                    SG(request_info).path_translated = script_file;
2240                    /* before registering argv to module exchange the *new* argv[0] */
2241                    /* we can achieve this without allocating more memory */
2242                    SG(request_info).argc = argc - (php_optind - 1);
2243                    SG(request_info).argv = &argv[php_optind - 1];
2244                    SG(request_info).argv[0] = script_file;
2245                } else if (argc > php_optind) {
2246                    /* file is on command line, but not in -f opt */
2247                    if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2248                    SG(request_info).path_translated = estrdup(argv[php_optind]);
2249                    /* arguments after the file are considered script args */
2250                    SG(request_info).argc = argc - php_optind;
2251                    SG(request_info).argv = &argv[php_optind];
2252                }
2253
2254                if (no_headers) {
2255                    SG(headers_sent) = 1;
2256                    SG(request_info).no_headers = 1;
2257                }
2258
2259                /* all remaining arguments are part of the query string
2260                 * this section of code concatenates all remaining arguments
2261                 * into a single string, separating args with a &
2262                 * this allows command lines like:
2263                 *
2264                 *  test.php v1=test v2=hello+world!
2265                 *  test.php "v1=test&v2=hello world!"
2266                 *  test.php v1=test "v2=hello world!"
2267                */
2268                if (!SG(request_info).query_string && argc > php_optind) {
2269                    size_t slen = strlen(PG(arg_separator).input);
2270                    len = 0;
2271                    for (i = php_optind; i < argc; i++) {
2272                        if (i < (argc - 1)) {
2273                            len += strlen(argv[i]) + slen;
2274                        } else {
2275                            len += strlen(argv[i]);
2276                        }
2277                    }
2278
2279                    len += 2;
2280                    s = malloc(len);
2281                    *s = '\0';          /* we are pretending it came from the environment  */
2282                    for (i = php_optind; i < argc; i++) {
2283                        strlcat(s, argv[i], len);
2284                        if (i < (argc - 1)) {
2285                            strlcat(s, PG(arg_separator).input, len);
2286                        }
2287                    }
2288                    SG(request_info).query_string = s;
2289                    free_query_string = 1;
2290                }
2291            } /* end !cgi && !fastcgi */
2292
2293            /*
2294                we never take stdin if we're (f)cgi, always
2295                rely on the web server giving us the info
2296                we need in the environment.
2297            */
2298            if (SG(request_info).path_translated || cgi || fastcgi) {
2299                file_handle.type = ZEND_HANDLE_FILENAME;
2300                file_handle.filename = SG(request_info).path_translated;
2301                file_handle.handle.fp = NULL;
2302            } else {
2303                file_handle.filename = "-";
2304                file_handle.type = ZEND_HANDLE_FP;
2305                file_handle.handle.fp = stdin;
2306            }
2307
2308            file_handle.opened_path = NULL;
2309            file_handle.free_filename = 0;
2310
2311            /* request startup only after we've done all we can to
2312             * get path_translated */
2313            if (php_request_startup() == FAILURE) {
2314                if (fastcgi) {
2315                    fcgi_finish_request(&request, 1);
2316                }
2317                SG(server_context) = NULL;
2318                php_module_shutdown();
2319                return FAILURE;
2320            }
2321            if (no_headers) {
2322                SG(headers_sent) = 1;
2323                SG(request_info).no_headers = 1;
2324            }
2325
2326            /*
2327                at this point path_translated will be set if:
2328                1. we are running from shell and got filename was there
2329                2. we are running as cgi or fastcgi
2330            */
2331            if (cgi || fastcgi || SG(request_info).path_translated) {
2332                if (php_fopen_primary_script(&file_handle) == FAILURE) {
2333                    zend_try {
2334                        if (errno == EACCES) {
2335                            SG(sapi_headers).http_response_code = 403;
2336                            PUTS("Access denied.\n");
2337                        } else {
2338                            SG(sapi_headers).http_response_code = 404;
2339                            PUTS("No input file specified.\n");
2340                        }
2341                    } zend_catch {
2342                    } zend_end_try();
2343                    /* we want to serve more requests if this is fastcgi
2344                     * so cleanup and continue, request shutdown is
2345                     * handled later */
2346                    if (fastcgi) {
2347                        goto fastcgi_request_done;
2348                    }
2349
2350                    if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2351
2352                    if (free_query_string && SG(request_info).query_string) {
2353                        free(SG(request_info).query_string);
2354                        SG(request_info).query_string = NULL;
2355                    }
2356
2357                    php_request_shutdown((void *) 0);
2358                    SG(server_context) = NULL;
2359                    php_module_shutdown();
2360                    sapi_shutdown();
2361#ifdef ZTS
2362                    tsrm_shutdown();
2363#endif
2364                    return FAILURE;
2365                }
2366            }
2367
2368            if (CGIG(check_shebang_line)) {
2369                /* #!php support */
2370                switch (file_handle.type) {
2371                    case ZEND_HANDLE_FD:
2372                        if (file_handle.handle.fd < 0) {
2373                            break;
2374                        }
2375                        file_handle.type = ZEND_HANDLE_FP;
2376                        file_handle.handle.fp = fdopen(file_handle.handle.fd, "rb");
2377                        /* break missing intentionally */
2378                    case ZEND_HANDLE_FP:
2379                        if (!file_handle.handle.fp ||
2380                            (file_handle.handle.fp == stdin)) {
2381                            break;
2382                        }
2383                        c = fgetc(file_handle.handle.fp);
2384                        if (c == '#') {
2385                            while (c != '\n' && c != '\r' && c != EOF) {
2386                                c = fgetc(file_handle.handle.fp);   /* skip to end of line */
2387                            }
2388                            /* handle situations where line is terminated by \r\n */
2389                            if (c == '\r') {
2390                                if (fgetc(file_handle.handle.fp) != '\n') {
2391                                    zend_long pos = zend_ftell(file_handle.handle.fp);
2392                                    zend_fseek(file_handle.handle.fp, pos - 1, SEEK_SET);
2393                                }
2394                            }
2395                            CG(start_lineno) = 2;
2396                        } else {
2397                            rewind(file_handle.handle.fp);
2398                        }
2399                        break;
2400                    case ZEND_HANDLE_STREAM:
2401                        c = php_stream_getc((php_stream*)file_handle.handle.stream.handle);
2402                        if (c == '#') {
2403                            while (c != '\n' && c != '\r' && c != EOF) {
2404                                c = php_stream_getc((php_stream*)file_handle.handle.stream.handle); /* skip to end of line */
2405                            }
2406                            /* handle situations where line is terminated by \r\n */
2407                            if (c == '\r') {
2408                                if (php_stream_getc((php_stream*)file_handle.handle.stream.handle) != '\n') {
2409                                    zend_off_t pos = php_stream_tell((php_stream*)file_handle.handle.stream.handle);
2410                                    php_stream_seek((php_stream*)file_handle.handle.stream.handle, pos - 1, SEEK_SET);
2411                                }
2412                            }
2413                            CG(start_lineno) = 2;
2414                        } else {
2415                            php_stream_rewind((php_stream*)file_handle.handle.stream.handle);
2416                        }
2417                        break;
2418                    case ZEND_HANDLE_MAPPED:
2419                        if (file_handle.handle.stream.mmap.buf[0] == '#') {
2420                            size_t i = 1;
2421
2422                            c = file_handle.handle.stream.mmap.buf[i++];
2423                            while (c != '\n' && c != '\r' && i < file_handle.handle.stream.mmap.len) {
2424                                c = file_handle.handle.stream.mmap.buf[i++];
2425                            }
2426                            if (c == '\r') {
2427                                if (i < file_handle.handle.stream.mmap.len && file_handle.handle.stream.mmap.buf[i] == '\n') {
2428                                    i++;
2429                                }
2430                            }
2431                            if(i > file_handle.handle.stream.mmap.len) {
2432                                i = file_handle.handle.stream.mmap.len;
2433                            }
2434                            file_handle.handle.stream.mmap.buf += i;
2435                            file_handle.handle.stream.mmap.len -= i;
2436                        }
2437                        break;
2438                    default:
2439                        break;
2440                }
2441            }
2442
2443            switch (behavior) {
2444                case PHP_MODE_STANDARD:
2445                    php_execute_script(&file_handle);
2446                    break;
2447                case PHP_MODE_LINT:
2448                    PG(during_request_startup) = 0;
2449                    exit_status = php_lint_script(&file_handle);
2450                    if (exit_status == SUCCESS) {
2451                        zend_printf("No syntax errors detected in %s\n", file_handle.filename);
2452                    } else {
2453                        zend_printf("Errors parsing %s\n", file_handle.filename);
2454                    }
2455                    break;
2456                case PHP_MODE_STRIP:
2457                    if (open_file_for_scanning(&file_handle) == SUCCESS) {
2458                        zend_strip();
2459                        zend_file_handle_dtor(&file_handle);
2460                        php_output_teardown();
2461                    }
2462                    return SUCCESS;
2463                    break;
2464                case PHP_MODE_HIGHLIGHT:
2465                    {
2466                        zend_syntax_highlighter_ini syntax_highlighter_ini;
2467
2468                        if (open_file_for_scanning(&file_handle) == SUCCESS) {
2469                            php_get_highlight_struct(&syntax_highlighter_ini);
2470                            zend_highlight(&syntax_highlighter_ini);
2471                            if (fastcgi) {
2472                                goto fastcgi_request_done;
2473                            }
2474                            zend_file_handle_dtor(&file_handle);
2475                            php_output_teardown();
2476                        }
2477                        return SUCCESS;
2478                    }
2479                    break;
2480            }
2481
2482fastcgi_request_done:
2483            {
2484                if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2485
2486                php_request_shutdown((void *) 0);
2487
2488                if (exit_status == 0) {
2489                    exit_status = EG(exit_status);
2490                }
2491
2492                if (free_query_string && SG(request_info).query_string) {
2493                    free(SG(request_info).query_string);
2494                    SG(request_info).query_string = NULL;
2495                }
2496            }
2497
2498            if (!fastcgi) {
2499                if (benchmark) {
2500                    if (warmup_repeats) {
2501                        warmup_repeats--;
2502                        if (!warmup_repeats) {
2503#ifdef HAVE_GETTIMEOFDAY
2504                            gettimeofday(&start, NULL);
2505#else
2506                            time(&start);
2507#endif
2508                        }
2509                        continue;
2510                    } else {
2511                        repeats--;
2512                        if (repeats > 0) {
2513                            script_file = NULL;
2514                            php_optind = orig_optind;
2515                            php_optarg = orig_optarg;
2516                            continue;
2517                        }
2518                    }
2519                }
2520                break;
2521            }
2522
2523            /* only fastcgi will get here */
2524            requests++;
2525            if (max_requests && (requests == max_requests)) {
2526                fcgi_finish_request(&request, 1);
2527                if (bindpath) {
2528                    free(bindpath);
2529                }
2530                if (max_requests != 1) {
2531                    /* no need to return exit_status of the last request */
2532                    exit_status = 0;
2533                }
2534                break;
2535            }
2536            /* end of fastcgi loop */
2537        }
2538
2539        if (request.listen_socket) {
2540            fcgi_destroy_request(&request);
2541        }
2542        fcgi_shutdown();
2543
2544        if (cgi_sapi_module.php_ini_path_override) {
2545            free(cgi_sapi_module.php_ini_path_override);
2546        }
2547        if (cgi_sapi_module.ini_entries) {
2548            free(cgi_sapi_module.ini_entries);
2549        }
2550    } zend_catch {
2551        exit_status = 255;
2552    } zend_end_try();
2553
2554out:
2555    if (benchmark) {
2556        int sec;
2557#ifdef HAVE_GETTIMEOFDAY
2558        int usec;
2559
2560        gettimeofday(&end, NULL);
2561        sec = (int)(end.tv_sec - start.tv_sec);
2562        if (end.tv_usec >= start.tv_usec) {
2563            usec = (int)(end.tv_usec - start.tv_usec);
2564        } else {
2565            sec -= 1;
2566            usec = (int)(end.tv_usec + 1000000 - start.tv_usec);
2567        }
2568        fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec);
2569#else
2570        time(&end);
2571        sec = (int)(end - start);
2572        fprintf(stderr, "\nElapsed time: %d sec\n", sec);
2573#endif
2574    }
2575
2576#ifndef PHP_WIN32
2577parent_out:
2578#endif
2579
2580    SG(server_context) = NULL;
2581    php_module_shutdown();
2582    sapi_shutdown();
2583
2584#ifdef ZTS
2585    tsrm_shutdown();
2586#endif
2587
2588#if defined(PHP_WIN32) && ZEND_DEBUG && 0
2589    _CrtDumpMemoryLeaks();
2590#endif
2591
2592    return exit_status;
2593}
2594/* }}} */
2595
2596/*
2597 * Local variables:
2598 * tab-width: 4
2599 * c-basic-offset: 4
2600 * End:
2601 * vim600: sw=4 ts=4 fdm=marker
2602 * vim<600: sw=4 ts=4
2603 */
2604