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