1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2015 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.php.net/license/3_01.txt                                  |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca>                       |
16   |          Stig Bakken <ssb@php.net>                                   |
17   |          Zeev Suraski <zeev@zend.com>                                |
18   | FastCGI: Ben Mansell <php@slimyhorror.com>                           |
19   |          Shane Caraveo <shane@caraveo.com>                           |
20   |          Dmitry Stogov <dmitry@zend.com>                             |
21   +----------------------------------------------------------------------+
22*/
23
24/* $Id$ */
25
26#include "php.h"
27#include "php_globals.h"
28#include "php_variables.h"
29#include "zend_modules.h"
30
31#include "SAPI.h"
32
33#include <stdio.h>
34#include "php.h"
35
36#ifdef PHP_WIN32
37# include "win32/time.h"
38# include "win32/signal.h"
39# include <process.h>
40#endif
41
42#if HAVE_SYS_TIME_H
43# include <sys/time.h>
44#endif
45
46#if HAVE_UNISTD_H
47# include <unistd.h>
48#endif
49
50#if HAVE_SIGNAL_H
51# include <signal.h>
52#endif
53
54#if HAVE_SETLOCALE
55# include <locale.h>
56#endif
57
58#if HAVE_SYS_TYPES_H
59# include <sys/types.h>
60#endif
61
62#if HAVE_SYS_WAIT_H
63# include <sys/wait.h>
64#endif
65
66#include "zend.h"
67#include "zend_extensions.h"
68#include "php_ini.h"
69#include "php_globals.h"
70#include "php_main.h"
71#include "fopen_wrappers.h"
72#include "http_status_codes.h"
73#include "ext/standard/php_standard.h"
74#include "ext/standard/url.h"
75
76#ifdef PHP_WIN32
77# include <io.h>
78# include <fcntl.h>
79# include "win32/php_registry.h"
80#endif
81
82#ifdef __riscos__
83# include <unixlib/local.h>
84int __riscosify_control = __RISCOSIFY_STRICT_UNIX_SPECS;
85#endif
86
87#include "zend_compile.h"
88#include "zend_execute.h"
89#include "zend_highlight.h"
90#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, 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 ret, len = (int)strlen(message);
703            char *buf = malloc(len+2);
704
705            memcpy(buf, message, len);
706            memcpy(buf + len, "\n", sizeof("\n"));
707            ret = fcgi_write(request, FCGI_STDERR, buf, (int)(len + 1));
708            free(buf);
709            if (ret < 0) {
710                php_handle_aborted_connection();
711            }
712        } else {
713            fprintf(stderr, "%s\n", message);
714        }
715        /* ignore return code */
716    } else {
717        fprintf(stderr, "%s\n", message);
718    }
719}
720
721/* {{{ php_cgi_ini_activate_user_config
722 */
723static void php_cgi_ini_activate_user_config(char *path, size_t path_len, const char *doc_root, size_t doc_root_len, int start)
724{
725    char *ptr;
726    user_config_cache_entry *new_entry, *entry;
727    time_t request_time = (time_t)sapi_get_request_time();
728
729    /* Find cached config entry: If not found, create one */
730    if ((entry = zend_hash_str_find_ptr(&CGIG(user_config_cache), path, path_len)) == NULL) {
731        new_entry = pemalloc(sizeof(user_config_cache_entry), 1);
732        new_entry->expires = 0;
733        new_entry->user_config = (HashTable *) pemalloc(sizeof(HashTable), 1);
734        zend_hash_init(new_entry->user_config, 8, NULL, (dtor_func_t) config_zval_dtor, 1);
735        entry = zend_hash_str_update_ptr(&CGIG(user_config_cache), path, path_len, new_entry);
736    }
737
738    /* Check whether cache entry has expired and rescan if it is */
739    if (request_time > entry->expires) {
740        char *real_path = NULL;
741        size_t real_path_len;
742        char *s1, *s2;
743        size_t s_len;
744
745        /* Clear the expired config */
746        zend_hash_clean(entry->user_config);
747
748        if (!IS_ABSOLUTE_PATH(path, path_len)) {
749            real_path = tsrm_realpath(path, NULL);
750            if (real_path == NULL) {
751                return;
752            }
753            real_path_len = strlen(real_path);
754            path = real_path;
755            path_len = real_path_len;
756        }
757
758        if (path_len > doc_root_len) {
759            s1 = (char *) doc_root;
760            s2 = path;
761            s_len = doc_root_len;
762        } else {
763            s1 = path;
764            s2 = (char *) doc_root;
765            s_len = path_len;
766        }
767
768        /* we have to test if path is part of DOCUMENT_ROOT.
769          if it is inside the docroot, we scan the tree up to the docroot
770            to find more user.ini, if not we only scan the current path.
771          */
772#ifdef PHP_WIN32
773        if (strnicmp(s1, s2, s_len) == 0) {
774#else
775        if (strncmp(s1, s2, s_len) == 0) {
776#endif
777            ptr = s2 + start;  /* start is the point where doc_root ends! */
778            while ((ptr = strchr(ptr, DEFAULT_SLASH)) != NULL) {
779                *ptr = 0;
780                php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config);
781                *ptr = '/';
782                ptr++;
783            }
784        } else {
785            php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config);
786        }
787
788        if (real_path) {
789            efree(real_path);
790        }
791        entry->expires = request_time + PG(user_ini_cache_ttl);
792    }
793
794    /* Activate ini entries with values from the user config hash */
795    php_ini_activate_config(entry->user_config, PHP_INI_PERDIR, PHP_INI_STAGE_HTACCESS);
796}
797/* }}} */
798
799static int sapi_cgi_activate(void)
800{
801    char *path, *doc_root, *server_name;
802    size_t path_len, doc_root_len, server_name_len;
803
804    /* PATH_TRANSLATED should be defined at this stage but better safe than sorry :) */
805    if (!SG(request_info).path_translated) {
806        return FAILURE;
807    }
808
809    if (php_ini_has_per_host_config()) {
810        /* Activate per-host-system-configuration defined in php.ini and stored into configuration_hash during startup */
811        if (fcgi_is_fastcgi()) {
812            fcgi_request *request = (fcgi_request*) SG(server_context);
813
814            server_name = FCGI_GETENV(request, "SERVER_NAME");
815        } else {
816            server_name = getenv("SERVER_NAME");
817        }
818        /* SERVER_NAME should also be defined at this stage..but better check it anyway */
819        if (server_name) {
820            server_name_len = strlen(server_name);
821            server_name = estrndup(server_name, server_name_len);
822            zend_str_tolower(server_name, server_name_len);
823            php_ini_activate_per_host_config(server_name, server_name_len);
824            efree(server_name);
825        }
826    }
827
828    if (php_ini_has_per_dir_config() ||
829        (PG(user_ini_filename) && *PG(user_ini_filename))
830    ) {
831        /* Prepare search path */
832        path_len = strlen(SG(request_info).path_translated);
833
834        /* Make sure we have trailing slash! */
835        if (!IS_SLASH(SG(request_info).path_translated[path_len])) {
836            path = emalloc(path_len + 2);
837            memcpy(path, SG(request_info).path_translated, path_len + 1);
838            path_len = zend_dirname(path, path_len);
839            path[path_len++] = DEFAULT_SLASH;
840        } else {
841            path = estrndup(SG(request_info).path_translated, path_len);
842            path_len = zend_dirname(path, path_len);
843        }
844        path[path_len] = 0;
845
846        /* Activate per-dir-system-configuration defined in php.ini and stored into configuration_hash during startup */
847        php_ini_activate_per_dir_config(path, path_len); /* Note: for global settings sake we check from root to path */
848
849        /* Load and activate user ini files in path starting from DOCUMENT_ROOT */
850        if (PG(user_ini_filename) && *PG(user_ini_filename)) {
851            if (fcgi_is_fastcgi()) {
852                fcgi_request *request = (fcgi_request*) SG(server_context);
853
854                doc_root = FCGI_GETENV(request, "DOCUMENT_ROOT");
855            } else {
856                doc_root = getenv("DOCUMENT_ROOT");
857            }
858            /* DOCUMENT_ROOT should also be defined at this stage..but better check it anyway */
859            if (doc_root) {
860                doc_root_len = strlen(doc_root);
861                if (doc_root_len > 0 && IS_SLASH(doc_root[doc_root_len - 1])) {
862                    --doc_root_len;
863                }
864#ifdef PHP_WIN32
865                /* paths on windows should be case-insensitive */
866                doc_root = estrndup(doc_root, doc_root_len);
867                zend_str_tolower(doc_root, doc_root_len);
868#endif
869                php_cgi_ini_activate_user_config(path, path_len, doc_root, doc_root_len, (doc_root_len > 0 && (doc_root_len - 1)));
870
871#ifdef PHP_WIN32
872                efree(doc_root);
873#endif
874            }
875        }
876
877        efree(path);
878    }
879
880    return SUCCESS;
881}
882
883static int sapi_cgi_deactivate(void)
884{
885    /* flush only when SAPI was started. The reasons are:
886        1. SAPI Deactivate is called from two places: module init and request shutdown
887        2. When the first call occurs and the request is not set up, flush fails on FastCGI.
888    */
889    if (SG(sapi_started)) {
890        if (fcgi_is_fastcgi()) {
891            if (
892#ifndef PHP_WIN32
893                !parent &&
894#endif
895                !fcgi_finish_request((fcgi_request*)SG(server_context), 0)) {
896                php_handle_aborted_connection();
897            }
898        } else {
899            sapi_cgi_flush(SG(server_context));
900        }
901    }
902    return SUCCESS;
903}
904
905static int php_cgi_startup(sapi_module_struct *sapi_module)
906{
907    if (php_module_startup(sapi_module, &cgi_module_entry, 1) == FAILURE) {
908        return FAILURE;
909    }
910    return SUCCESS;
911}
912
913/* {{{ sapi_module_struct cgi_sapi_module
914 */
915static sapi_module_struct cgi_sapi_module = {
916    "cgi-fcgi",                     /* name */
917    "CGI/FastCGI",                  /* pretty name */
918
919    php_cgi_startup,                /* startup */
920    php_module_shutdown_wrapper,    /* shutdown */
921
922    sapi_cgi_activate,              /* activate */
923    sapi_cgi_deactivate,            /* deactivate */
924
925    sapi_cgi_ub_write,              /* unbuffered write */
926    sapi_cgi_flush,                 /* flush */
927    NULL,                           /* get uid */
928    sapi_cgi_getenv,                /* getenv */
929
930    php_error,                      /* error handler */
931
932    NULL,                           /* header handler */
933    sapi_cgi_send_headers,          /* send headers handler */
934    NULL,                           /* send header handler */
935
936    sapi_cgi_read_post,             /* read POST data */
937    sapi_cgi_read_cookies,          /* read Cookies */
938
939    sapi_cgi_register_variables,    /* register server variables */
940    sapi_cgi_log_message,           /* Log message */
941    NULL,                           /* Get request time */
942    NULL,                           /* Child terminate */
943
944    STANDARD_SAPI_MODULE_PROPERTIES
945};
946/* }}} */
947
948/* {{{ arginfo ext/standard/dl.c */
949ZEND_BEGIN_ARG_INFO(arginfo_dl, 0)
950    ZEND_ARG_INFO(0, extension_filename)
951ZEND_END_ARG_INFO()
952/* }}} */
953
954static const zend_function_entry additional_functions[] = {
955    ZEND_FE(dl, arginfo_dl)
956    {NULL, NULL, NULL}
957};
958
959/* {{{ php_cgi_usage
960 */
961static void php_cgi_usage(char *argv0)
962{
963    char *prog;
964
965    prog = strrchr(argv0, '/');
966    if (prog) {
967        prog++;
968    } else {
969        prog = "php";
970    }
971
972    php_printf( "Usage: %s [-q] [-h] [-s] [-v] [-i] [-f <file>]\n"
973                "       %s <file> [args...]\n"
974                "  -a               Run interactively\n"
975                "  -b <address:port>|<port> Bind Path for external FASTCGI Server mode\n"
976                "  -C               Do not chdir to the script's directory\n"
977                "  -c <path>|<file> Look for php.ini file in this directory\n"
978                "  -n               No php.ini file will be used\n"
979                "  -d foo[=bar]     Define INI entry foo with value 'bar'\n"
980                "  -e               Generate extended information for debugger/profiler\n"
981                "  -f <file>        Parse <file>.  Implies `-q'\n"
982                "  -h               This help\n"
983                "  -i               PHP information\n"
984                "  -l               Syntax check only (lint)\n"
985                "  -m               Show compiled in modules\n"
986                "  -q               Quiet-mode.  Suppress HTTP Header output.\n"
987                "  -s               Display colour syntax highlighted source.\n"
988                "  -v               Version number\n"
989                "  -w               Display source with stripped comments and whitespace.\n"
990                "  -z <file>        Load Zend extension <file>.\n"
991                "  -T <count>       Measure execution time of script repeated <count> times.\n",
992                prog, prog);
993}
994/* }}} */
995
996/* {{{ is_valid_path
997 *
998 * some server configurations allow '..' to slip through in the
999 * translated path.   We'll just refuse to handle such a path.
1000 */
1001static int is_valid_path(const char *path)
1002{
1003    const char *p = path;
1004
1005    if (UNEXPECTED(!p)) {
1006        return 0;
1007    }
1008    if (UNEXPECTED(*p == '.') && *(p+1) == '.' && (!*(p+2) || IS_SLASH(*(p+2)))) {
1009        return 0;
1010    }
1011    while (*p) {
1012        if (IS_SLASH(*p)) {
1013            p++;
1014            if (UNEXPECTED(*p == '.')) {
1015                p++;
1016                if (UNEXPECTED(*p == '.')) {
1017                    p++;
1018                    if (UNEXPECTED(!*p) || UNEXPECTED(IS_SLASH(*p))) {
1019                        return 0;
1020                    }
1021                }
1022            }
1023        }
1024        p++;
1025    }
1026    return 1;
1027}
1028/* }}} */
1029
1030#define CGI_GETENV(name) \
1031    ((request) ? \
1032        FCGI_GETENV(request, name) : \
1033        getenv(name))
1034
1035#define CGI_PUTENV(name, value) \
1036    ((request) ? \
1037        FCGI_PUTENV(request, name, value) : \
1038        _sapi_cgi_putenv(name, sizeof(name)-1, value))
1039
1040/* {{{ init_request_info
1041
1042  initializes request_info structure
1043
1044  specificly in this section we handle proper translations
1045  for:
1046
1047  PATH_INFO
1048    derived from the portion of the URI path following
1049    the script name but preceding any query data
1050    may be empty
1051
1052  PATH_TRANSLATED
1053    derived by taking any path-info component of the
1054    request URI and performing any virtual-to-physical
1055    translation appropriate to map it onto the server's
1056    document repository structure
1057
1058    empty if PATH_INFO is empty
1059
1060    The env var PATH_TRANSLATED **IS DIFFERENT** than the
1061    request_info.path_translated variable, the latter should
1062    match SCRIPT_FILENAME instead.
1063
1064  SCRIPT_NAME
1065    set to a URL path that could identify the CGI script
1066    rather than the interpreter.  PHP_SELF is set to this
1067
1068  REQUEST_URI
1069    uri section following the domain:port part of a URI
1070
1071  SCRIPT_FILENAME
1072    The virtual-to-physical translation of SCRIPT_NAME (as per
1073    PATH_TRANSLATED)
1074
1075  These settings are documented at
1076  http://cgi-spec.golux.com/
1077
1078
1079  Based on the following URL request:
1080
1081  http://localhost/info.php/test?a=b
1082
1083  should produce, which btw is the same as if
1084  we were running under mod_cgi on apache (ie. not
1085  using ScriptAlias directives):
1086
1087  PATH_INFO=/test
1088  PATH_TRANSLATED=/docroot/test
1089  SCRIPT_NAME=/info.php
1090  REQUEST_URI=/info.php/test?a=b
1091  SCRIPT_FILENAME=/docroot/info.php
1092  QUERY_STRING=a=b
1093
1094  but what we get is (cgi/mod_fastcgi under apache):
1095
1096  PATH_INFO=/info.php/test
1097  PATH_TRANSLATED=/docroot/info.php/test
1098  SCRIPT_NAME=/php/php-cgi  (from the Action setting I suppose)
1099  REQUEST_URI=/info.php/test?a=b
1100  SCRIPT_FILENAME=/path/to/php/bin/php-cgi  (Action setting translated)
1101  QUERY_STRING=a=b
1102
1103  Comments in the code below refer to using the above URL in a request
1104
1105 */
1106static void init_request_info(fcgi_request *request)
1107{
1108    char *env_script_filename = CGI_GETENV("SCRIPT_FILENAME");
1109    char *env_path_translated = CGI_GETENV("PATH_TRANSLATED");
1110    char *script_path_translated = env_script_filename;
1111
1112    /* some broken servers do not have script_filename or argv0
1113     * an example, IIS configured in some ways.  then they do more
1114     * broken stuff and set path_translated to the cgi script location */
1115    if (!script_path_translated && env_path_translated) {
1116        script_path_translated = env_path_translated;
1117    }
1118
1119    /* initialize the defaults */
1120    SG(request_info).path_translated = NULL;
1121    SG(request_info).request_method = NULL;
1122    SG(request_info).proto_num = 1000;
1123    SG(request_info).query_string = NULL;
1124    SG(request_info).request_uri = NULL;
1125    SG(request_info).content_type = NULL;
1126    SG(request_info).content_length = 0;
1127    SG(sapi_headers).http_response_code = 200;
1128
1129    /* script_path_translated being set is a good indication that
1130     * we are running in a cgi environment, since it is always
1131     * null otherwise.  otherwise, the filename
1132     * of the script will be retreived later via argc/argv */
1133    if (script_path_translated) {
1134        const char *auth;
1135        char *content_length = CGI_GETENV("CONTENT_LENGTH");
1136        char *content_type = CGI_GETENV("CONTENT_TYPE");
1137        char *env_path_info = CGI_GETENV("PATH_INFO");
1138        char *env_script_name = CGI_GETENV("SCRIPT_NAME");
1139
1140#ifdef PHP_WIN32
1141        /* Hack for buggy IIS that sets incorrect PATH_INFO */
1142        char *env_server_software = CGI_GETENV("SERVER_SOFTWARE");
1143
1144        if (env_server_software &&
1145            env_script_name &&
1146            env_path_info &&
1147            strncmp(env_server_software, "Microsoft-IIS", sizeof("Microsoft-IIS")-1) == 0 &&
1148            strncmp(env_path_info, env_script_name, strlen(env_script_name)) == 0
1149        ) {
1150            env_path_info = CGI_PUTENV("ORIG_PATH_INFO", env_path_info);
1151            env_path_info += strlen(env_script_name);
1152            if (*env_path_info == 0) {
1153                env_path_info = NULL;
1154            }
1155            env_path_info = CGI_PUTENV("PATH_INFO", env_path_info);
1156        }
1157#endif
1158
1159        if (CGIG(fix_pathinfo)) {
1160            zend_stat_t st;
1161            char *real_path = NULL;
1162            char *env_redirect_url = CGI_GETENV("REDIRECT_URL");
1163            char *env_document_root = CGI_GETENV("DOCUMENT_ROOT");
1164            char *orig_path_translated = env_path_translated;
1165            char *orig_path_info = env_path_info;
1166            char *orig_script_name = env_script_name;
1167            char *orig_script_filename = env_script_filename;
1168            size_t script_path_translated_len;
1169
1170            if (!env_document_root && PG(doc_root)) {
1171                env_document_root = CGI_PUTENV("DOCUMENT_ROOT", PG(doc_root));
1172                /* fix docroot */
1173                TRANSLATE_SLASHES(env_document_root);
1174            }
1175
1176            if (env_path_translated != NULL && env_redirect_url != NULL &&
1177                env_path_translated != script_path_translated &&
1178                strcmp(env_path_translated, script_path_translated) != 0) {
1179                /*
1180                 * pretty much apache specific.  If we have a redirect_url
1181                 * then our script_filename and script_name point to the
1182                 * php executable
1183                 */
1184                script_path_translated = env_path_translated;
1185                /* we correct SCRIPT_NAME now in case we don't have PATH_INFO */
1186                env_script_name = env_redirect_url;
1187            }
1188
1189#ifdef __riscos__
1190            /* Convert path to unix format*/
1191            __riscosify_control |= __RISCOSIFY_DONT_CHECK_DIR;
1192            script_path_translated = __unixify(script_path_translated, 0, NULL, 1, 0);
1193#endif
1194
1195            /*
1196             * if the file doesn't exist, try to extract PATH_INFO out
1197             * of it by stat'ing back through the '/'
1198             * this fixes url's like /info.php/test
1199             */
1200            if (script_path_translated &&
1201                (script_path_translated_len = strlen(script_path_translated)) > 0 &&
1202                (script_path_translated[script_path_translated_len-1] == '/' ||
1203#ifdef PHP_WIN32
1204                script_path_translated[script_path_translated_len-1] == '\\' ||
1205#endif
1206                (real_path = tsrm_realpath(script_path_translated, NULL)) == NULL)
1207            ) {
1208                char *pt = estrndup(script_path_translated, script_path_translated_len);
1209                size_t len = script_path_translated_len;
1210                char *ptr;
1211
1212                while ((ptr = strrchr(pt, '/')) || (ptr = strrchr(pt, '\\'))) {
1213                    *ptr = 0;
1214                    if (zend_stat(pt, &st) == 0 && S_ISREG(st.st_mode)) {
1215                        /*
1216                         * okay, we found the base script!
1217                         * work out how many chars we had to strip off;
1218                         * then we can modify PATH_INFO
1219                         * accordingly
1220                         *
1221                         * we now have the makings of
1222                         * PATH_INFO=/test
1223                         * SCRIPT_FILENAME=/docroot/info.php
1224                         *
1225                         * we now need to figure out what docroot is.
1226                         * if DOCUMENT_ROOT is set, this is easy, otherwise,
1227                         * we have to play the game of hide and seek to figure
1228                         * out what SCRIPT_NAME should be
1229                         */
1230                        size_t slen = len - strlen(pt);
1231                        size_t pilen = env_path_info ? strlen(env_path_info) : 0;
1232                        char *path_info = env_path_info ? env_path_info + pilen - slen : NULL;
1233
1234                        if (orig_path_info != path_info) {
1235                            if (orig_path_info) {
1236                                char old;
1237
1238                                CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
1239                                old = path_info[0];
1240                                path_info[0] = 0;
1241                                if (!orig_script_name ||
1242                                    strcmp(orig_script_name, env_path_info) != 0) {
1243                                    if (orig_script_name) {
1244                                        CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1245                                    }
1246                                    SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_path_info);
1247                                } else {
1248                                    SG(request_info).request_uri = orig_script_name;
1249                                }
1250                                path_info[0] = old;
1251                            }
1252                            env_path_info = CGI_PUTENV("PATH_INFO", path_info);
1253                        }
1254                        if (!orig_script_filename ||
1255                            strcmp(orig_script_filename, pt) != 0) {
1256                            if (orig_script_filename) {
1257                                CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1258                            }
1259                            script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", pt);
1260                        }
1261                        TRANSLATE_SLASHES(pt);
1262
1263                        /* figure out docroot
1264                         * SCRIPT_FILENAME minus SCRIPT_NAME
1265                         */
1266                        if (env_document_root) {
1267                            size_t l = strlen(env_document_root);
1268                            size_t path_translated_len = 0;
1269                            char *path_translated = NULL;
1270
1271                            if (l && env_document_root[l - 1] == '/') {
1272                                --l;
1273                            }
1274
1275                            /* we have docroot, so we should have:
1276                             * DOCUMENT_ROOT=/docroot
1277                             * SCRIPT_FILENAME=/docroot/info.php
1278                             */
1279
1280                            /* PATH_TRANSLATED = DOCUMENT_ROOT + PATH_INFO */
1281                            path_translated_len = l + (env_path_info ? strlen(env_path_info) : 0);
1282                            path_translated = (char *) emalloc(path_translated_len + 1);
1283                            memcpy(path_translated, env_document_root, l);
1284                            if (env_path_info) {
1285                                memcpy(path_translated + l, env_path_info, (path_translated_len - l));
1286                            }
1287                            path_translated[path_translated_len] = '\0';
1288                            if (orig_path_translated) {
1289                                CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1290                            }
1291                            env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
1292                            efree(path_translated);
1293                        } else if ( env_script_name &&
1294                                    strstr(pt, env_script_name)
1295                        ) {
1296                            /* PATH_TRANSLATED = PATH_TRANSLATED - SCRIPT_NAME + PATH_INFO */
1297                            size_t ptlen = strlen(pt) - strlen(env_script_name);
1298                            size_t path_translated_len = ptlen + (env_path_info ? strlen(env_path_info) : 0);
1299                            char *path_translated = NULL;
1300
1301                            path_translated = (char *) emalloc(path_translated_len + 1);
1302                            memcpy(path_translated, pt, ptlen);
1303                            if (env_path_info) {
1304                                memcpy(path_translated + ptlen, env_path_info, path_translated_len - ptlen);
1305                            }
1306                            path_translated[path_translated_len] = '\0';
1307                            if (orig_path_translated) {
1308                                CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1309                            }
1310                            env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
1311                            efree(path_translated);
1312                        }
1313                        break;
1314                    }
1315                }
1316                if (!ptr) {
1317                    /*
1318                     * if we stripped out all the '/' and still didn't find
1319                     * a valid path... we will fail, badly. of course we would
1320                     * have failed anyway... we output 'no input file' now.
1321                     */
1322                    if (orig_script_filename) {
1323                        CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1324                    }
1325                    script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", NULL);
1326                    SG(sapi_headers).http_response_code = 404;
1327                }
1328                if (!SG(request_info).request_uri) {
1329                    if (!orig_script_name ||
1330                        strcmp(orig_script_name, env_script_name) != 0) {
1331                        if (orig_script_name) {
1332                            CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1333                        }
1334                        SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
1335                    } else {
1336                        SG(request_info).request_uri = orig_script_name;
1337                    }
1338                }
1339                if (pt) {
1340                    efree(pt);
1341                }
1342            } else {
1343                /* make sure path_info/translated are empty */
1344                if (!orig_script_filename ||
1345                    (script_path_translated != orig_script_filename &&
1346                    strcmp(script_path_translated, orig_script_filename) != 0)) {
1347                    if (orig_script_filename) {
1348                        CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
1349                    }
1350                    script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", script_path_translated);
1351                }
1352                if (env_redirect_url) {
1353                    if (orig_path_info) {
1354                        CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
1355                        CGI_PUTENV("PATH_INFO", NULL);
1356                    }
1357                    if (orig_path_translated) {
1358                        CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
1359                        CGI_PUTENV("PATH_TRANSLATED", NULL);
1360                    }
1361                }
1362                if (env_script_name != orig_script_name) {
1363                    if (orig_script_name) {
1364                        CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
1365                    }
1366                    SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
1367                } else {
1368                    SG(request_info).request_uri = env_script_name;
1369                }
1370                efree(real_path);
1371            }
1372        } else {
1373            /* pre 4.3 behaviour, shouldn't be used but provides BC */
1374            if (env_path_info) {
1375                SG(request_info).request_uri = env_path_info;
1376            } else {
1377                SG(request_info).request_uri = env_script_name;
1378            }
1379            if (!CGIG(discard_path) && env_path_translated) {
1380                script_path_translated = env_path_translated;
1381            }
1382        }
1383
1384        if (is_valid_path(script_path_translated)) {
1385            SG(request_info).path_translated = estrdup(script_path_translated);
1386        }
1387
1388        SG(request_info).request_method = CGI_GETENV("REQUEST_METHOD");
1389        /* FIXME - Work out proto_num here */
1390        SG(request_info).query_string = CGI_GETENV("QUERY_STRING");
1391        SG(request_info).content_type = (content_type ? content_type : "" );
1392        SG(request_info).content_length = (content_length ? atol(content_length) : 0);
1393
1394        /* The CGI RFC allows servers to pass on unvalidated Authorization data */
1395        auth = CGI_GETENV("HTTP_AUTHORIZATION");
1396        php_handle_auth_data(auth);
1397    }
1398}
1399/* }}} */
1400
1401#ifndef PHP_WIN32
1402/**
1403 * Clean up child processes upon exit
1404 */
1405void fastcgi_cleanup(int signal)
1406{
1407#ifdef DEBUG_FASTCGI
1408    fprintf(stderr, "FastCGI shutdown, pid %d\n", getpid());
1409#endif
1410
1411    sigaction(SIGTERM, &old_term, 0);
1412
1413    /* Kill all the processes in our process group */
1414    kill(-pgroup, SIGTERM);
1415
1416    if (parent && parent_waiting) {
1417        exit_signal = 1;
1418    } else {
1419        exit(0);
1420    }
1421}
1422#endif
1423
1424PHP_INI_BEGIN()
1425    STD_PHP_INI_ENTRY("cgi.rfc2616_headers",     "0",  PHP_INI_ALL,    OnUpdateBool,   rfc2616_headers, php_cgi_globals_struct, php_cgi_globals)
1426    STD_PHP_INI_ENTRY("cgi.nph",                 "0",  PHP_INI_ALL,    OnUpdateBool,   nph, php_cgi_globals_struct, php_cgi_globals)
1427    STD_PHP_INI_ENTRY("cgi.check_shebang_line",  "1",  PHP_INI_SYSTEM, OnUpdateBool,   check_shebang_line, php_cgi_globals_struct, php_cgi_globals)
1428    STD_PHP_INI_ENTRY("cgi.force_redirect",      "1",  PHP_INI_SYSTEM, OnUpdateBool,   force_redirect, php_cgi_globals_struct, php_cgi_globals)
1429    STD_PHP_INI_ENTRY("cgi.redirect_status_env", NULL, PHP_INI_SYSTEM, OnUpdateString, redirect_status_env, php_cgi_globals_struct, php_cgi_globals)
1430    STD_PHP_INI_ENTRY("cgi.fix_pathinfo",        "1",  PHP_INI_SYSTEM, OnUpdateBool,   fix_pathinfo, php_cgi_globals_struct, php_cgi_globals)
1431    STD_PHP_INI_ENTRY("cgi.discard_path",        "0",  PHP_INI_SYSTEM, OnUpdateBool,   discard_path, php_cgi_globals_struct, php_cgi_globals)
1432    STD_PHP_INI_ENTRY("fastcgi.logging",         "1",  PHP_INI_SYSTEM, OnUpdateBool,   fcgi_logging, php_cgi_globals_struct, php_cgi_globals)
1433#ifdef PHP_WIN32
1434    STD_PHP_INI_ENTRY("fastcgi.impersonate",     "0",  PHP_INI_SYSTEM, OnUpdateBool,   impersonate, php_cgi_globals_struct, php_cgi_globals)
1435#endif
1436PHP_INI_END()
1437
1438/* {{{ php_cgi_globals_ctor
1439 */
1440static void php_cgi_globals_ctor(php_cgi_globals_struct *php_cgi_globals)
1441{
1442#ifdef ZTS
1443    ZEND_TSRMLS_CACHE_UPDATE();
1444#endif
1445    php_cgi_globals->rfc2616_headers = 0;
1446    php_cgi_globals->nph = 0;
1447    php_cgi_globals->check_shebang_line = 1;
1448    php_cgi_globals->force_redirect = 1;
1449    php_cgi_globals->redirect_status_env = NULL;
1450    php_cgi_globals->fix_pathinfo = 1;
1451    php_cgi_globals->discard_path = 0;
1452    php_cgi_globals->fcgi_logging = 1;
1453#ifdef PHP_WIN32
1454    php_cgi_globals->impersonate = 0;
1455#endif
1456    zend_hash_init(&php_cgi_globals->user_config_cache, 8, NULL, user_config_cache_entry_dtor, 1);
1457}
1458/* }}} */
1459
1460/* {{{ PHP_MINIT_FUNCTION
1461 */
1462static PHP_MINIT_FUNCTION(cgi)
1463{
1464#ifdef ZTS
1465    ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
1466#else
1467    php_cgi_globals_ctor(&php_cgi_globals);
1468#endif
1469    REGISTER_INI_ENTRIES();
1470    return SUCCESS;
1471}
1472/* }}} */
1473
1474/* {{{ PHP_MSHUTDOWN_FUNCTION
1475 */
1476static PHP_MSHUTDOWN_FUNCTION(cgi)
1477{
1478    zend_hash_destroy(&CGIG(user_config_cache));
1479
1480    UNREGISTER_INI_ENTRIES();
1481    return SUCCESS;
1482}
1483/* }}} */
1484
1485/* {{{ PHP_MINFO_FUNCTION
1486 */
1487static PHP_MINFO_FUNCTION(cgi)
1488{
1489    DISPLAY_INI_ENTRIES();
1490}
1491/* }}} */
1492
1493PHP_FUNCTION(apache_child_terminate) /* {{{ */
1494{
1495    if (ZEND_NUM_ARGS() > 0) {
1496        WRONG_PARAM_COUNT;
1497    }
1498    if (fcgi_is_fastcgi()) {
1499        fcgi_terminate();
1500    }
1501}
1502/* }}} */
1503
1504static void add_request_header(char *var, unsigned int var_len, char *val, unsigned int val_len, void *arg) /* {{{ */
1505{
1506    zval *return_value = (zval*)arg;
1507    char *str = NULL;
1508    char *p;
1509    ALLOCA_FLAG(use_heap)
1510
1511    if (var_len > 5 &&
1512        var[0] == 'H' &&
1513        var[1] == 'T' &&
1514        var[2] == 'T' &&
1515        var[3] == 'P' &&
1516        var[4] == '_') {
1517
1518        var_len -= 5;
1519        p = var + 5;
1520        var = str = do_alloca(var_len + 1, use_heap);
1521        *str++ = *p++;
1522        while (*p) {
1523            if (*p == '_') {
1524                *str++ = '-';
1525                p++;
1526                if (*p) {
1527                    *str++ = *p++;
1528                }
1529            } else if (*p >= 'A' && *p <= 'Z') {
1530                *str++ = (*p++ - 'A' + 'a');
1531            } else {
1532                *str++ = *p++;
1533            }
1534        }
1535        *str = 0;
1536    } else if (var_len == sizeof("CONTENT_TYPE")-1 &&
1537               memcmp(var, "CONTENT_TYPE", sizeof("CONTENT_TYPE")-1) == 0) {
1538        var = "Content-Type";
1539    } else if (var_len == sizeof("CONTENT_LENGTH")-1 &&
1540               memcmp(var, "CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1) == 0) {
1541        var = "Content-Length";
1542    } else {
1543        return;
1544    }
1545    add_assoc_stringl_ex(return_value, var, var_len+1, val, val_len);
1546    if (str) {
1547        free_alloca(var, use_heap);
1548    }
1549}
1550/* }}} */
1551
1552PHP_FUNCTION(apache_request_headers) /* {{{ */
1553{
1554    if (ZEND_NUM_ARGS() > 0) {
1555        WRONG_PARAM_COUNT;
1556    }
1557    array_init(return_value);
1558    if (fcgi_is_fastcgi()) {
1559        fcgi_request *request = (fcgi_request*) SG(server_context);
1560
1561        fcgi_loadenv(request, add_request_header, return_value);
1562    } else {
1563        char buf[128];
1564        char **env, *p, *q, *var, *val, *t = buf;
1565        size_t alloc_size = sizeof(buf);
1566        zend_ulong var_len;
1567
1568        for (env = environ; env != NULL && *env != NULL; env++) {
1569            val = strchr(*env, '=');
1570            if (!val) {             /* malformed entry? */
1571                continue;
1572            }
1573            var_len = val - *env;
1574            if (var_len >= alloc_size) {
1575                alloc_size = var_len + 64;
1576                t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
1577            }
1578            var = *env;
1579            if (var_len > 5 &&
1580                var[0] == 'H' &&
1581                var[1] == 'T' &&
1582                var[2] == 'T' &&
1583                var[3] == 'P' &&
1584                var[4] == '_') {
1585
1586                var_len -= 5;
1587
1588                if (var_len >= alloc_size) {
1589                    alloc_size = var_len + 64;
1590                    t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
1591                }
1592                p = var + 5;
1593
1594                var = q = t;
1595                /* First char keep uppercase */
1596                *q++ = *p++;
1597                while (*p) {
1598                    if (*p == '=') {
1599                        /* End of name */
1600                        break;
1601                    } else if (*p == '_') {
1602                        *q++ = '-';
1603                        p++;
1604                        /* First char after - keep uppercase */
1605                        if (*p && *p!='=') {
1606                            *q++ = *p++;
1607                        }
1608                    } else if (*p >= 'A' && *p <= 'Z') {
1609                        /* lowercase */
1610                        *q++ = (*p++ - 'A' + 'a');
1611                    } else {
1612                        *q++ = *p++;
1613                    }
1614                }
1615                *q = 0;
1616            } else if (var_len == sizeof("CONTENT_TYPE")-1 &&
1617                       memcmp(var, "CONTENT_TYPE", sizeof("CONTENT_TYPE")-1) == 0) {
1618                var = "Content-Type";
1619            } else if (var_len == sizeof("CONTENT_LENGTH")-1 &&
1620                       memcmp(var, "CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1) == 0) {
1621                var = "Content-Length";
1622            } else {
1623                continue;
1624            }
1625            val++;
1626            add_assoc_string_ex(return_value, var, var_len, val);
1627        }
1628        if (t != buf && t != NULL) {
1629            efree(t);
1630        }
1631    }
1632}
1633/* }}} */
1634
1635static void add_response_header(sapi_header_struct *h, zval *return_value) /* {{{ */
1636{
1637    char *s, *p;
1638    size_t len = 0;
1639    ALLOCA_FLAG(use_heap)
1640
1641    if (h->header_len > 0) {
1642        p = strchr(h->header, ':');
1643        if (NULL != p) {
1644            len = p - h->header;
1645        }
1646        if (len > 0) {
1647            do {
1648                len--;
1649            } while (len != 0 && (h->header[len-1] == ' ' || h->header[len-1] == '\t'));
1650            if (len) {
1651                s = do_alloca(len + 1, use_heap);
1652                memcpy(s, h->header, len);
1653                s[len] = 0;
1654                do {
1655                    p++;
1656                } while (*p == ' ' || *p == '\t');
1657                add_assoc_stringl_ex(return_value, s, len, p, h->header_len - (p - h->header));
1658                free_alloca(s, use_heap);
1659            }
1660        }
1661    }
1662}
1663/* }}} */
1664
1665PHP_FUNCTION(apache_response_headers) /* {{{ */
1666{
1667    if (zend_parse_parameters_none() == FAILURE) {
1668        return;
1669    }
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-2015 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-2015 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                            size_t i = 1;
2415
2416                            c = file_handle.handle.stream.mmap.buf[i++];
2417                            while (c != '\n' && c != '\r' && i < file_handle.handle.stream.mmap.len) {
2418                                c = file_handle.handle.stream.mmap.buf[i++];
2419                            }
2420                            if (c == '\r') {
2421                                if (i < file_handle.handle.stream.mmap.len && file_handle.handle.stream.mmap.buf[i] == '\n') {
2422                                    i++;
2423                                }
2424                            }
2425                            if(i > file_handle.handle.stream.mmap.len) {
2426                                i = file_handle.handle.stream.mmap.len;
2427                            }
2428                            file_handle.handle.stream.mmap.buf += i;
2429                            file_handle.handle.stream.mmap.len -= i;
2430                        }
2431                        break;
2432                    default:
2433                        break;
2434                }
2435            }
2436
2437            switch (behavior) {
2438                case PHP_MODE_STANDARD:
2439                    php_execute_script(&file_handle);
2440                    break;
2441                case PHP_MODE_LINT:
2442                    PG(during_request_startup) = 0;
2443                    exit_status = php_lint_script(&file_handle);
2444                    if (exit_status == SUCCESS) {
2445                        zend_printf("No syntax errors detected in %s\n", file_handle.filename);
2446                    } else {
2447                        zend_printf("Errors parsing %s\n", file_handle.filename);
2448                    }
2449                    break;
2450                case PHP_MODE_STRIP:
2451                    if (open_file_for_scanning(&file_handle) == SUCCESS) {
2452                        zend_strip();
2453                        zend_file_handle_dtor(&file_handle);
2454                        php_output_teardown();
2455                    }
2456                    return SUCCESS;
2457                    break;
2458                case PHP_MODE_HIGHLIGHT:
2459                    {
2460                        zend_syntax_highlighter_ini syntax_highlighter_ini;
2461
2462                        if (open_file_for_scanning(&file_handle) == SUCCESS) {
2463                            php_get_highlight_struct(&syntax_highlighter_ini);
2464                            zend_highlight(&syntax_highlighter_ini);
2465                            if (fastcgi) {
2466                                goto fastcgi_request_done;
2467                            }
2468                            zend_file_handle_dtor(&file_handle);
2469                            php_output_teardown();
2470                        }
2471                        return SUCCESS;
2472                    }
2473                    break;
2474#if 0
2475                /* Zeev might want to do something with this one day */
2476                case PHP_MODE_INDENT:
2477                    open_file_for_scanning(&file_handle);
2478                    zend_indent();
2479                    zend_file_handle_dtor(&file_handle);
2480                    php_output_teardown();
2481                    return SUCCESS;
2482                    break;
2483#endif
2484            }
2485
2486fastcgi_request_done:
2487            {
2488                if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2489
2490                php_request_shutdown((void *) 0);
2491
2492                if (exit_status == 0) {
2493                    exit_status = EG(exit_status);
2494                }
2495
2496                if (free_query_string && SG(request_info).query_string) {
2497                    free(SG(request_info).query_string);
2498                    SG(request_info).query_string = NULL;
2499                }
2500            }
2501
2502            if (!fastcgi) {
2503                if (benchmark) {
2504                    if (warmup_repeats) {
2505                        warmup_repeats--;
2506                        if (!warmup_repeats) {
2507#ifdef HAVE_GETTIMEOFDAY
2508                            gettimeofday(&start, NULL);
2509#else
2510                            time(&start);
2511#endif
2512                        }
2513                        continue;
2514                    } else {
2515                        repeats--;
2516                        if (repeats > 0) {
2517                            script_file = NULL;
2518                            php_optind = orig_optind;
2519                            php_optarg = orig_optarg;
2520                            continue;
2521                        }
2522                    }
2523                }
2524                break;
2525            }
2526
2527            /* only fastcgi will get here */
2528            requests++;
2529            if (max_requests && (requests == max_requests)) {
2530                fcgi_finish_request(request, 1);
2531                if (bindpath) {
2532                    free(bindpath);
2533                }
2534                if (max_requests != 1) {
2535                    /* no need to return exit_status of the last request */
2536                    exit_status = 0;
2537                }
2538                break;
2539            }
2540            /* end of fastcgi loop */
2541        }
2542        if (request) {
2543            fcgi_destroy_request(request);
2544        }
2545        fcgi_shutdown();
2546
2547        if (cgi_sapi_module.php_ini_path_override) {
2548            free(cgi_sapi_module.php_ini_path_override);
2549        }
2550        if (cgi_sapi_module.ini_entries) {
2551            free(cgi_sapi_module.ini_entries);
2552        }
2553    } zend_catch {
2554        exit_status = 255;
2555    } zend_end_try();
2556
2557out:
2558    if (benchmark) {
2559        int sec;
2560#ifdef HAVE_GETTIMEOFDAY
2561        int usec;
2562
2563        gettimeofday(&end, NULL);
2564        sec = (int)(end.tv_sec - start.tv_sec);
2565        if (end.tv_usec >= start.tv_usec) {
2566            usec = (int)(end.tv_usec - start.tv_usec);
2567        } else {
2568            sec -= 1;
2569            usec = (int)(end.tv_usec + 1000000 - start.tv_usec);
2570        }
2571        fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec);
2572#else
2573        time(&end);
2574        sec = (int)(end - start);
2575        fprintf(stderr, "\nElapsed time: %d sec\n", sec);
2576#endif
2577    }
2578
2579#ifndef PHP_WIN32
2580parent_out:
2581#endif
2582
2583    SG(server_context) = NULL;
2584    php_module_shutdown();
2585    sapi_shutdown();
2586
2587#ifdef ZTS
2588    tsrm_shutdown();
2589#endif
2590
2591#if defined(PHP_WIN32) && ZEND_DEBUG && 0
2592    _CrtDumpMemoryLeaks();
2593#endif
2594
2595    return exit_status;
2596}
2597/* }}} */
2598
2599/*
2600 * Local variables:
2601 * tab-width: 4
2602 * c-basic-offset: 4
2603 * End:
2604 * vim600: sw=4 ts=4 fdm=marker
2605 * vim<600: sw=4 ts=4
2606 */
2607