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: 565 1121 50.4 %
Date: 2018-12-08 Functions: 22 42 52.4 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10

Generated at Sat, 08 Dec 2018 23:47:53 +0000 (31 hours ago)

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