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 ZEND_SIGNALS
1777    zend_signal_startup();
1778#endif
1779
1780#ifdef ZTS
1781    ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
1782#else
1783    php_cgi_globals_ctor(&php_cgi_globals);
1784#endif
1785
1786    sapi_startup(&cgi_sapi_module);
1787    fastcgi = fcgi_is_fastcgi();
1788    cgi_sapi_module.php_ini_path_override = NULL;
1789
1790#ifdef PHP_WIN32
1791    _fmode = _O_BINARY; /* sets default for file streams to binary */
1792    setmode(_fileno(stdin),  O_BINARY); /* make the stdio mode be binary */
1793    setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */
1794    setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */
1795#endif
1796
1797    if (!fastcgi) {
1798        /* Make sure we detect we are a cgi - a bit redundancy here,
1799         * but the default case is that we have to check only the first one. */
1800        if (getenv("SERVER_SOFTWARE") ||
1801            getenv("SERVER_NAME") ||
1802            getenv("GATEWAY_INTERFACE") ||
1803            getenv("REQUEST_METHOD")
1804        ) {
1805            cgi = 1;
1806        }
1807    }
1808
1809    if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) {
1810        /* we've got query string that has no = - apache CGI will pass it to command line */
1811        unsigned char *p;
1812        decoded_query_string = strdup(query_string);
1813        php_url_decode(decoded_query_string, strlen(decoded_query_string));
1814        for (p = (unsigned char *)decoded_query_string; *p &&  *p <= ' '; p++) {
1815            /* skip all leading spaces */
1816        }
1817        if(*p == '-') {
1818            skip_getopt = 1;
1819        }
1820        free(decoded_query_string);
1821    }
1822
1823    while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
1824        switch (c) {
1825            case 'c':
1826                if (cgi_sapi_module.php_ini_path_override) {
1827                    free(cgi_sapi_module.php_ini_path_override);
1828                }
1829                cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
1830                break;
1831            case 'n':
1832                cgi_sapi_module.php_ini_ignore = 1;
1833                break;
1834            case 'd': {
1835                /* define ini entries on command line */
1836                size_t len = strlen(php_optarg);
1837                char *val;
1838
1839                if ((val = strchr(php_optarg, '='))) {
1840                    val++;
1841                    if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
1842                        cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
1843                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
1844                        ini_entries_len += (val - php_optarg);
1845                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1);
1846                        ini_entries_len++;
1847                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
1848                        ini_entries_len += len - (val - php_optarg);
1849                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
1850                        ini_entries_len += sizeof("\n\0\"") - 2;
1851                    } else {
1852                        cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
1853                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
1854                        memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
1855                        ini_entries_len += len + sizeof("\n\0") - 2;
1856                    }
1857                } else {
1858                    cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
1859                    memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
1860                    memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
1861                    ini_entries_len += len + sizeof("=1\n\0") - 2;
1862                }
1863                break;
1864            }
1865            /* if we're started on command line, check to see if
1866             * we are being started as an 'external' fastcgi
1867             * server by accepting a bindpath parameter. */
1868            case 'b':
1869                if (!fastcgi) {
1870                    bindpath = strdup(php_optarg);
1871                }
1872                break;
1873            case 's': /* generate highlighted HTML from source */
1874                behavior = PHP_MODE_HIGHLIGHT;
1875                break;
1876        }
1877    }
1878    php_optind = orig_optind;
1879    php_optarg = orig_optarg;
1880
1881    if (fastcgi || bindpath) {
1882        /* Override SAPI callbacks */
1883        cgi_sapi_module.ub_write     = sapi_fcgi_ub_write;
1884        cgi_sapi_module.flush        = sapi_fcgi_flush;
1885        cgi_sapi_module.read_post    = sapi_fcgi_read_post;
1886        cgi_sapi_module.getenv       = sapi_fcgi_getenv;
1887        cgi_sapi_module.read_cookies = sapi_fcgi_read_cookies;
1888    }
1889
1890#ifdef ZTS
1891    SG(request_info).path_translated = NULL;
1892#endif
1893
1894    cgi_sapi_module.executable_location = argv[0];
1895    if (!cgi && !fastcgi && !bindpath) {
1896        cgi_sapi_module.additional_functions = additional_functions;
1897    }
1898
1899    /* startup after we get the above ini override se we get things right */
1900    if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
1901#ifdef ZTS
1902        tsrm_shutdown();
1903#endif
1904        return FAILURE;
1905    }
1906
1907    /* check force_cgi after startup, so we have proper output */
1908    if (cgi && CGIG(force_redirect)) {
1909        /* Apache will generate REDIRECT_STATUS,
1910         * Netscape and redirect.so will generate HTTP_REDIRECT_STATUS.
1911         * redirect.so and installation instructions available from
1912         * http://www.koehntopp.de/php.
1913         *   -- kk@netuse.de
1914         */
1915        if (!getenv("REDIRECT_STATUS") &&
1916            !getenv ("HTTP_REDIRECT_STATUS") &&
1917            /* this is to allow a different env var to be configured
1918             * in case some server does something different than above */
1919            (!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env)))
1920        ) {
1921            zend_try {
1922                SG(sapi_headers).http_response_code = 400;
1923                PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
1924<p>This PHP CGI binary was compiled with force-cgi-redirect enabled.  This\n\
1925means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
1926set, e.g. via an Apache Action directive.</p>\n\
1927<p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
1928manual page for CGI security</a>.</p>\n\
1929<p>For more information about changing this behaviour or re-enabling this webserver,\n\
1930consult the installation file that came with this distribution, or visit \n\
1931<a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
1932            } zend_catch {
1933            } zend_end_try();
1934#if defined(ZTS) && !defined(PHP_DEBUG)
1935            /* XXX we're crashing here in msvc6 debug builds at
1936             * php_message_handler_for_zend:839 because
1937             * SG(request_info).path_translated is an invalid pointer.
1938             * It still happens even though I set it to null, so something
1939             * weird is going on.
1940             */
1941            tsrm_shutdown();
1942#endif
1943            return FAILURE;
1944        }
1945    }
1946
1947#ifndef HAVE_ATTRIBUTE_WEAK
1948    fcgi_set_logger(fcgi_log);
1949#endif
1950
1951    if (bindpath) {
1952        int backlog = 128;
1953        if (getenv("PHP_FCGI_BACKLOG")) {
1954            backlog = atoi(getenv("PHP_FCGI_BACKLOG"));
1955        }
1956        fcgi_fd = fcgi_listen(bindpath, backlog);
1957        if (fcgi_fd < 0) {
1958            fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath);
1959#ifdef ZTS
1960            tsrm_shutdown();
1961#endif
1962            return FAILURE;
1963        }
1964        fastcgi = fcgi_is_fastcgi();
1965    }
1966    if (fastcgi) {
1967        /* How many times to run PHP scripts before dying */
1968        if (getenv("PHP_FCGI_MAX_REQUESTS")) {
1969            max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS"));
1970            if (max_requests < 0) {
1971                fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n");
1972                return FAILURE;
1973            }
1974        }
1975
1976        /* make php call us to get _ENV vars */
1977        php_php_import_environment_variables = php_import_environment_variables;
1978        php_import_environment_variables = cgi_php_import_environment_variables;
1979
1980        /* library is already initialized, now init our request */
1981        request = fcgi_init_request(fcgi_fd, NULL, NULL, NULL);
1982
1983#ifndef PHP_WIN32
1984        /* Pre-fork, if required */
1985        if (getenv("PHP_FCGI_CHILDREN")) {
1986            char * children_str = getenv("PHP_FCGI_CHILDREN");
1987            children = atoi(children_str);
1988            if (children < 0) {
1989                fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n");
1990                return FAILURE;
1991            }
1992            fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str));
1993            /* This is the number of concurrent requests, equals FCGI_MAX_CONNS */
1994            fcgi_set_mgmt_var("FCGI_MAX_REQS",  sizeof("FCGI_MAX_REQS")-1,  children_str, strlen(children_str));
1995        } else {
1996            fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1);
1997            fcgi_set_mgmt_var("FCGI_MAX_REQS",  sizeof("FCGI_MAX_REQS")-1,  "1", sizeof("1")-1);
1998        }
1999
2000        if (children) {
2001            int running = 0;
2002            pid_t pid;
2003
2004            /* Create a process group for ourself & children */
2005            setsid();
2006            pgroup = getpgrp();
2007#ifdef DEBUG_FASTCGI
2008            fprintf(stderr, "Process group %d\n", pgroup);
2009#endif
2010
2011            /* Set up handler to kill children upon exit */
2012            act.sa_flags = 0;
2013            act.sa_handler = fastcgi_cleanup;
2014            if (sigaction(SIGTERM, &act, &old_term) ||
2015                sigaction(SIGINT,  &act, &old_int)  ||
2016                sigaction(SIGQUIT, &act, &old_quit)
2017            ) {
2018                perror("Can't set signals");
2019                exit(1);
2020            }
2021
2022            if (fcgi_in_shutdown()) {
2023                goto parent_out;
2024            }
2025
2026            while (parent) {
2027                do {
2028#ifdef DEBUG_FASTCGI
2029                    fprintf(stderr, "Forking, %d running\n", running);
2030#endif
2031                    pid = fork();
2032                    switch (pid) {
2033                    case 0:
2034                        /* One of the children.
2035                         * Make sure we don't go round the
2036                         * fork loop any more
2037                         */
2038                        parent = 0;
2039
2040                        /* don't catch our signals */
2041                        sigaction(SIGTERM, &old_term, 0);
2042                        sigaction(SIGQUIT, &old_quit, 0);
2043                        sigaction(SIGINT,  &old_int,  0);
2044                        break;
2045                    case -1:
2046                        perror("php (pre-forking)");
2047                        exit(1);
2048                        break;
2049                    default:
2050                        /* Fine */
2051                        running++;
2052                        break;
2053                    }
2054                } while (parent && (running < children));
2055
2056                if (parent) {
2057#ifdef DEBUG_FASTCGI
2058                    fprintf(stderr, "Wait for kids, pid %d\n", getpid());
2059#endif
2060                    parent_waiting = 1;
2061                    while (1) {
2062                        if (wait(&status) >= 0) {
2063                            running--;
2064                            break;
2065                        } else if (exit_signal) {
2066                            break;
2067                        }
2068                    }
2069                    if (exit_signal) {
2070#if 0
2071                        while (running > 0) {
2072                            while (wait(&status) < 0) {
2073                            }
2074                            running--;
2075                        }
2076#endif
2077                        goto parent_out;
2078                    }
2079                }
2080            }
2081        } else {
2082            parent = 0;
2083        }
2084
2085#endif /* WIN32 */
2086    }
2087
2088    zend_first_try {
2089        while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) {
2090            switch (c) {
2091                case 'T':
2092                    benchmark = 1;
2093                    {
2094                        char *comma = strchr(php_optarg, ',');
2095                        if (comma) {
2096                            warmup_repeats = atoi(php_optarg);
2097                            repeats = atoi(comma + 1);
2098                        } else {
2099                            repeats = atoi(php_optarg);
2100                        }
2101                    }
2102#ifdef HAVE_GETTIMEOFDAY
2103                    gettimeofday(&start, NULL);
2104#else
2105                    time(&start);
2106#endif
2107                    break;
2108                case 'h':
2109                case '?':
2110                    if (request) {
2111                        fcgi_destroy_request(request);
2112                    }
2113                    fcgi_shutdown();
2114                    no_headers = 1;
2115                    SG(headers_sent) = 1;
2116                    php_cgi_usage(argv[0]);
2117                    php_output_end_all();
2118                    exit_status = 0;
2119                    goto out;
2120            }
2121        }
2122        php_optind = orig_optind;
2123        php_optarg = orig_optarg;
2124
2125        /* start of FAST CGI loop */
2126        /* Initialise FastCGI request structure */
2127#ifdef PHP_WIN32
2128        /* attempt to set security impersonation for fastcgi
2129         * will only happen on NT based OS, others will ignore it. */
2130        if (fastcgi && CGIG(impersonate)) {
2131            fcgi_impersonate();
2132        }
2133#endif
2134        while (!fastcgi || fcgi_accept_request(request) >= 0) {
2135            SG(server_context) = fastcgi ? (void *)request : (void *) 1;
2136            init_request_info(request);
2137
2138            if (!cgi && !fastcgi) {
2139                while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
2140                    switch (c) {
2141
2142                        case 'a':   /* interactive mode */
2143                            printf("Interactive mode enabled\n\n");
2144                            break;
2145
2146                        case 'C': /* don't chdir to the script directory */
2147                            SG(options) |= SAPI_OPTION_NO_CHDIR;
2148                            break;
2149
2150                        case 'e': /* enable extended info output */
2151                            CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
2152                            break;
2153
2154                        case 'f': /* parse file */
2155                            if (script_file) {
2156                                efree(script_file);
2157                            }
2158                            script_file = estrdup(php_optarg);
2159                            no_headers = 1;
2160                            break;
2161
2162                        case 'i': /* php info & quit */
2163                            if (script_file) {
2164                                efree(script_file);
2165                            }
2166                            if (php_request_startup() == FAILURE) {
2167                                SG(server_context) = NULL;
2168                                php_module_shutdown();
2169                                return FAILURE;
2170                            }
2171                            if (no_headers) {
2172                                SG(headers_sent) = 1;
2173                                SG(request_info).no_headers = 1;
2174                            }
2175                            php_print_info(0xFFFFFFFF);
2176                            php_request_shutdown((void *) 0);
2177                            fcgi_shutdown();
2178                            exit_status = 0;
2179                            goto out;
2180
2181                        case 'l': /* syntax check mode */
2182                            no_headers = 1;
2183                            behavior = PHP_MODE_LINT;
2184                            break;
2185
2186                        case 'm': /* list compiled in modules */
2187                            if (script_file) {
2188                                efree(script_file);
2189                            }
2190                            SG(headers_sent) = 1;
2191                            php_printf("[PHP Modules]\n");
2192                            print_modules();
2193                            php_printf("\n[Zend Modules]\n");
2194                            print_extensions();
2195                            php_printf("\n");
2196                            php_output_end_all();
2197                            fcgi_shutdown();
2198                            exit_status = 0;
2199                            goto out;
2200
2201                        case 'q': /* do not generate HTTP headers */
2202                            no_headers = 1;
2203                            break;
2204
2205                        case 'v': /* show php version & quit */
2206                            if (script_file) {
2207                                efree(script_file);
2208                            }
2209                            no_headers = 1;
2210                            if (php_request_startup() == FAILURE) {
2211                                SG(server_context) = NULL;
2212                                php_module_shutdown();
2213                                return FAILURE;
2214                            }
2215                            if (no_headers) {
2216                                SG(headers_sent) = 1;
2217                                SG(request_info).no_headers = 1;
2218                            }
2219#if ZEND_DEBUG
2220                            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());
2221#else
2222                            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());
2223#endif
2224                            php_request_shutdown((void *) 0);
2225                            fcgi_shutdown();
2226                            exit_status = 0;
2227                            goto out;
2228
2229                        case 'w':
2230                            behavior = PHP_MODE_STRIP;
2231                            break;
2232
2233                        case 'z': /* load extension file */
2234                            zend_load_extension(php_optarg);
2235                            break;
2236
2237                        default:
2238                            break;
2239                    }
2240                }
2241
2242                if (script_file) {
2243                    /* override path_translated if -f on command line */
2244                    if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2245                    SG(request_info).path_translated = script_file;
2246                    /* before registering argv to module exchange the *new* argv[0] */
2247                    /* we can achieve this without allocating more memory */
2248                    SG(request_info).argc = argc - (php_optind - 1);
2249                    SG(request_info).argv = &argv[php_optind - 1];
2250                    SG(request_info).argv[0] = script_file;
2251                } else if (argc > php_optind) {
2252                    /* file is on command line, but not in -f opt */
2253                    if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2254                    SG(request_info).path_translated = estrdup(argv[php_optind]);
2255                    /* arguments after the file are considered script args */
2256                    SG(request_info).argc = argc - php_optind;
2257                    SG(request_info).argv = &argv[php_optind];
2258                }
2259
2260                if (no_headers) {
2261                    SG(headers_sent) = 1;
2262                    SG(request_info).no_headers = 1;
2263                }
2264
2265                /* all remaining arguments are part of the query string
2266                 * this section of code concatenates all remaining arguments
2267                 * into a single string, separating args with a &
2268                 * this allows command lines like:
2269                 *
2270                 *  test.php v1=test v2=hello+world!
2271                 *  test.php "v1=test&v2=hello world!"
2272                 *  test.php v1=test "v2=hello world!"
2273                */
2274                if (!SG(request_info).query_string && argc > php_optind) {
2275                    size_t slen = strlen(PG(arg_separator).input);
2276                    len = 0;
2277                    for (i = php_optind; i < argc; i++) {
2278                        if (i < (argc - 1)) {
2279                            len += strlen(argv[i]) + slen;
2280                        } else {
2281                            len += strlen(argv[i]);
2282                        }
2283                    }
2284
2285                    len += 2;
2286                    s = malloc(len);
2287                    *s = '\0';          /* we are pretending it came from the environment  */
2288                    for (i = php_optind; i < argc; i++) {
2289                        strlcat(s, argv[i], len);
2290                        if (i < (argc - 1)) {
2291                            strlcat(s, PG(arg_separator).input, len);
2292                        }
2293                    }
2294                    SG(request_info).query_string = s;
2295                    free_query_string = 1;
2296                }
2297            } /* end !cgi && !fastcgi */
2298
2299            /*
2300                we never take stdin if we're (f)cgi, always
2301                rely on the web server giving us the info
2302                we need in the environment.
2303            */
2304            if (SG(request_info).path_translated || cgi || fastcgi) {
2305                file_handle.type = ZEND_HANDLE_FILENAME;
2306                file_handle.filename = SG(request_info).path_translated;
2307                file_handle.handle.fp = NULL;
2308            } else {
2309                file_handle.filename = "-";
2310                file_handle.type = ZEND_HANDLE_FP;
2311                file_handle.handle.fp = stdin;
2312            }
2313
2314            file_handle.opened_path = NULL;
2315            file_handle.free_filename = 0;
2316
2317            /* request startup only after we've done all we can to
2318             * get path_translated */
2319            if (php_request_startup() == FAILURE) {
2320                if (fastcgi) {
2321                    fcgi_finish_request(request, 1);
2322                }
2323                SG(server_context) = NULL;
2324                php_module_shutdown();
2325                return FAILURE;
2326            }
2327            if (no_headers) {
2328                SG(headers_sent) = 1;
2329                SG(request_info).no_headers = 1;
2330            }
2331
2332            /*
2333                at this point path_translated will be set if:
2334                1. we are running from shell and got filename was there
2335                2. we are running as cgi or fastcgi
2336            */
2337            if (cgi || fastcgi || SG(request_info).path_translated) {
2338                if (php_fopen_primary_script(&file_handle) == FAILURE) {
2339                    zend_try {
2340                        if (errno == EACCES) {
2341                            SG(sapi_headers).http_response_code = 403;
2342                            PUTS("Access denied.\n");
2343                        } else {
2344                            SG(sapi_headers).http_response_code = 404;
2345                            PUTS("No input file specified.\n");
2346                        }
2347                    } zend_catch {
2348                    } zend_end_try();
2349                    /* we want to serve more requests if this is fastcgi
2350                     * so cleanup and continue, request shutdown is
2351                     * handled later */
2352                    if (fastcgi) {
2353                        goto fastcgi_request_done;
2354                    }
2355
2356                    if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2357
2358                    if (free_query_string && SG(request_info).query_string) {
2359                        free(SG(request_info).query_string);
2360                        SG(request_info).query_string = NULL;
2361                    }
2362
2363                    php_request_shutdown((void *) 0);
2364                    SG(server_context) = NULL;
2365                    php_module_shutdown();
2366                    sapi_shutdown();
2367#ifdef ZTS
2368                    tsrm_shutdown();
2369#endif
2370                    return FAILURE;
2371                }
2372            }
2373
2374            if (CGIG(check_shebang_line)) {
2375                /* #!php support */
2376                switch (file_handle.type) {
2377                    case ZEND_HANDLE_FD:
2378                        if (file_handle.handle.fd < 0) {
2379                            break;
2380                        }
2381                        file_handle.type = ZEND_HANDLE_FP;
2382                        file_handle.handle.fp = fdopen(file_handle.handle.fd, "rb");
2383                        /* break missing intentionally */
2384                    case ZEND_HANDLE_FP:
2385                        if (!file_handle.handle.fp ||
2386                            (file_handle.handle.fp == stdin)) {
2387                            break;
2388                        }
2389                        c = fgetc(file_handle.handle.fp);
2390                        if (c == '#') {
2391                            while (c != '\n' && c != '\r' && c != EOF) {
2392                                c = fgetc(file_handle.handle.fp);   /* skip to end of line */
2393                            }
2394                            /* handle situations where line is terminated by \r\n */
2395                            if (c == '\r') {
2396                                if (fgetc(file_handle.handle.fp) != '\n') {
2397                                    zend_long pos = zend_ftell(file_handle.handle.fp);
2398                                    zend_fseek(file_handle.handle.fp, pos - 1, SEEK_SET);
2399                                }
2400                            }
2401                            CG(start_lineno) = 2;
2402                        } else {
2403                            rewind(file_handle.handle.fp);
2404                        }
2405                        break;
2406                    case ZEND_HANDLE_STREAM:
2407                        c = php_stream_getc((php_stream*)file_handle.handle.stream.handle);
2408                        if (c == '#') {
2409                            while (c != '\n' && c != '\r' && c != EOF) {
2410                                c = php_stream_getc((php_stream*)file_handle.handle.stream.handle); /* skip to end of line */
2411                            }
2412                            /* handle situations where line is terminated by \r\n */
2413                            if (c == '\r') {
2414                                if (php_stream_getc((php_stream*)file_handle.handle.stream.handle) != '\n') {
2415                                    zend_off_t pos = php_stream_tell((php_stream*)file_handle.handle.stream.handle);
2416                                    php_stream_seek((php_stream*)file_handle.handle.stream.handle, pos - 1, SEEK_SET);
2417                                }
2418                            }
2419                            CG(start_lineno) = 2;
2420                        } else {
2421                            php_stream_rewind((php_stream*)file_handle.handle.stream.handle);
2422                        }
2423                        break;
2424                    case ZEND_HANDLE_MAPPED:
2425                        if (file_handle.handle.stream.mmap.buf[0] == '#') {
2426                            size_t i = 1;
2427
2428                            c = file_handle.handle.stream.mmap.buf[i++];
2429                            while (c != '\n' && c != '\r' && i < file_handle.handle.stream.mmap.len) {
2430                                c = file_handle.handle.stream.mmap.buf[i++];
2431                            }
2432                            if (c == '\r') {
2433                                if (i < file_handle.handle.stream.mmap.len && file_handle.handle.stream.mmap.buf[i] == '\n') {
2434                                    i++;
2435                                }
2436                            }
2437                            if(i > file_handle.handle.stream.mmap.len) {
2438                                i = file_handle.handle.stream.mmap.len;
2439                            }
2440                            file_handle.handle.stream.mmap.buf += i;
2441                            file_handle.handle.stream.mmap.len -= i;
2442                        }
2443                        break;
2444                    default:
2445                        break;
2446                }
2447            }
2448
2449            switch (behavior) {
2450                case PHP_MODE_STANDARD:
2451                    php_execute_script(&file_handle);
2452                    break;
2453                case PHP_MODE_LINT:
2454                    PG(during_request_startup) = 0;
2455                    exit_status = php_lint_script(&file_handle);
2456                    if (exit_status == SUCCESS) {
2457                        zend_printf("No syntax errors detected in %s\n", file_handle.filename);
2458                    } else {
2459                        zend_printf("Errors parsing %s\n", file_handle.filename);
2460                    }
2461                    break;
2462                case PHP_MODE_STRIP:
2463                    if (open_file_for_scanning(&file_handle) == SUCCESS) {
2464                        zend_strip();
2465                        zend_file_handle_dtor(&file_handle);
2466                        php_output_teardown();
2467                    }
2468                    return SUCCESS;
2469                    break;
2470                case PHP_MODE_HIGHLIGHT:
2471                    {
2472                        zend_syntax_highlighter_ini syntax_highlighter_ini;
2473
2474                        if (open_file_for_scanning(&file_handle) == SUCCESS) {
2475                            php_get_highlight_struct(&syntax_highlighter_ini);
2476                            zend_highlight(&syntax_highlighter_ini);
2477                            if (fastcgi) {
2478                                goto fastcgi_request_done;
2479                            }
2480                            zend_file_handle_dtor(&file_handle);
2481                            php_output_teardown();
2482                        }
2483                        return SUCCESS;
2484                    }
2485                    break;
2486            }
2487
2488fastcgi_request_done:
2489            {
2490                if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
2491
2492                php_request_shutdown((void *) 0);
2493
2494                if (exit_status == 0) {
2495                    exit_status = EG(exit_status);
2496                }
2497
2498                if (free_query_string && SG(request_info).query_string) {
2499                    free(SG(request_info).query_string);
2500                    SG(request_info).query_string = NULL;
2501                }
2502            }
2503
2504            if (!fastcgi) {
2505                if (benchmark) {
2506                    if (warmup_repeats) {
2507                        warmup_repeats--;
2508                        if (!warmup_repeats) {
2509#ifdef HAVE_GETTIMEOFDAY
2510                            gettimeofday(&start, NULL);
2511#else
2512                            time(&start);
2513#endif
2514                        }
2515                        continue;
2516                    } else {
2517                        repeats--;
2518                        if (repeats > 0) {
2519                            script_file = NULL;
2520                            php_optind = orig_optind;
2521                            php_optarg = orig_optarg;
2522                            continue;
2523                        }
2524                    }
2525                }
2526                break;
2527            }
2528
2529            /* only fastcgi will get here */
2530            requests++;
2531            if (max_requests && (requests == max_requests)) {
2532                fcgi_finish_request(request, 1);
2533                if (bindpath) {
2534                    free(bindpath);
2535                }
2536                if (max_requests != 1) {
2537                    /* no need to return exit_status of the last request */
2538                    exit_status = 0;
2539                }
2540                break;
2541            }
2542            /* end of fastcgi loop */
2543        }
2544
2545        if (request) {
2546            fcgi_destroy_request(request);
2547        }
2548        fcgi_shutdown();
2549
2550        if (cgi_sapi_module.php_ini_path_override) {
2551            free(cgi_sapi_module.php_ini_path_override);
2552        }
2553        if (cgi_sapi_module.ini_entries) {
2554            free(cgi_sapi_module.ini_entries);
2555        }
2556    } zend_catch {
2557        exit_status = 255;
2558    } zend_end_try();
2559
2560out:
2561    if (benchmark) {
2562        int sec;
2563#ifdef HAVE_GETTIMEOFDAY
2564        int usec;
2565
2566        gettimeofday(&end, NULL);
2567        sec = (int)(end.tv_sec - start.tv_sec);
2568        if (end.tv_usec >= start.tv_usec) {
2569            usec = (int)(end.tv_usec - start.tv_usec);
2570        } else {
2571            sec -= 1;
2572            usec = (int)(end.tv_usec + 1000000 - start.tv_usec);
2573        }
2574        fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec);
2575#else
2576        time(&end);
2577        sec = (int)(end - start);
2578        fprintf(stderr, "\nElapsed time: %d sec\n", sec);
2579#endif
2580    }
2581
2582#ifndef PHP_WIN32
2583parent_out:
2584#endif
2585
2586    SG(server_context) = NULL;
2587    php_module_shutdown();
2588    sapi_shutdown();
2589
2590#ifdef ZTS
2591    tsrm_shutdown();
2592#endif
2593
2594#if defined(PHP_WIN32) && ZEND_DEBUG && 0
2595    _CrtDumpMemoryLeaks();
2596#endif
2597
2598    return exit_status;
2599}
2600/* }}} */
2601
2602/*
2603 * Local variables:
2604 * tab-width: 4
2605 * c-basic-offset: 4
2606 * End:
2607 * vim600: sw=4 ts=4 fdm=marker
2608 * vim<600: sw=4 ts=4
2609 */
2610