PHP  
 PHP: Test and Code Coverage Analysis
downloads | QA | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
 

LCOV - code coverage report
Current view: top level - sapi/cgi - cgi_main.c (source / functions) Hit Total Coverage
Test: PHP Code Coverage Lines: 513 1078 47.6 %
Date: 2016-08-31 Functions: 20 42 47.6 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10

Generated at Wed, 31 Aug 2016 04:11:20 +0000 (17 hours ago)

Copyright © 2005-2016 The PHP Group
All rights reserved.