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